diff --git a/.agents/skills/update-openapi-templates/SKILL.md b/.agents/skills/update-openapi-templates/SKILL.md new file mode 100644 index 0000000..4e586b0 --- /dev/null +++ b/.agents/skills/update-openapi-templates/SKILL.md @@ -0,0 +1,132 @@ +--- +name: update-openapi-templates +description: Reconcile the custom OpenAPI Generator Mustache templates in sdk/java-restclient and sdk/java-resttemplate against upstream after a generator version bump, then regenerate and verify. Use when the openapi-generator version changes, when generation fails with a Mustache parse error, or when checking whether our templates have drifted from upstream. +--- + +# Update OpenAPI Generator templates + +Four SDK modules override generator templates. When the generator version is bumped, upstream +changes must be reconciled into those overrides. + +Our deliberate divergences are recorded in `sdk/custom-template-changes.md`. **Read it first** — it is +the list of things a reconciliation must preserve, and each entry says what breaks if it is lost. + +## Overridden templates + +``` +sdk/java-restclient/templates/ (java, library restclient) +sdk/java-resttemplate/templates/ (java, library resttemplate) +sdk/swift/templates/ (swift5) +sdk/python/templates/ (python) +``` + +Reconcile each against the upstream directory for **its own** generator. + +## Steps + +### 1 — Identify the versions + +```bash +git log --oneline -10 -- gradle/libs.versions.toml +grep -n 'openapi' gradle/libs.versions.toml +``` + +### 2 — Extract the upstream templates for the version we run + +Take them from the generator jar, not GitHub, so they match the running version exactly: + +```bash +V=7.22.0 +JAR=$(find ~/.gradle/caches/modules-2/files-2.1/org.openapitools/openapi-generator/$V \ + -name "openapi-generator-$V.jar" ! -name '*sources*' | head -1) +unzip -o "$JAR" 'Java/*' -d /tmp/upstream-$V +``` + +### 3 — Diff against the *library-specific* baseline + +The `java` generator resolves `pojo.mustache` per library. Diffing against the generic +`Java/pojo.mustache` gives plausible but wrong results — it lacks the JSpecify type-position wiring +these libraries use, and reconciling against it silently drops nullability annotations. + +| Module | Baseline | +| --- | --- | +| `sdk/java-restclient` | `Java/libraries/restclient/pojo.mustache` | +| `sdk/java-resttemplate` | `Java/libraries/resttemplate/pojo.mustache` | + +The two differ from each other — reconcile each module separately. + +Our copies follow upstream formatting. If a diff is unreadable because of indentation noise, compare +whitespace-insensitively (`diff -uwB`) to find the semantic changes. + +### 4 — Reconcile + +Prefer re-forking from the upstream baseline and re-applying the divergences in +`sdk/custom-template-changes.md` over hand-patching our copy. Re-forking picks up upstream fixes that +are dormant for our spec today (they render nothing now, but will if the spec grows into them); +hand-patching only ever finds what you already went looking for. + +Classify each upstream change: + +- **Cosmetic / structural** — take it as-is. +- **Touches `required` / `isNullable` / `x-is-jackson-optional-nullable`** — re-apply through the + polarity swap in change (1) of `custom-template-changes.md`. +- **New upstream behaviour we do not customise** — take it, and do not document it. +- **Superseded by one of our divergences** — skip, and check the divergence still reads correctly + against the new upstream code. + +### 5 — Check tag balance before generating + +A mismatched section tag fails generation with `Section close tag with mismatched open tag`, naming a +line in the *rendered* partial rather than in the file at fault. Verify balance directly: + +```bash +python3 - sdk/java-restclient/templates/pojo.mustache <<'PY' +import re, sys +stack = [] +for m in re.finditer(r'\{\{([#^/])([^}]+)\}\}', open(sys.argv[1]).read()): + kind, name = m.group(1), m.group(2).strip() + if kind in '#^': + stack.append(name) + else: + assert stack and stack[-1] == name, f"close {name} vs open {stack[-1] if stack else None}" + stack.pop() +assert not stack, f"unclosed: {stack}" +print("balanced") +PY +``` + +### 6 — Regenerate and build + +Compilation depends on generation, so a build regenerates first: + +```bash +source "$HOME/.sdkman/bin/sdkman-init.sh" && sdk env && \ + ./gradlew :java-restclient:build :java-resttemplate:build +``` + +### 7 — Verify against the previous output + +Copy the generated models aside *before* regenerating, then compare. Whitespace will move when +upstream reformats; what matters is that these hold: + +- `toString` line count unchanged — the `x-log` privacy allow-list survived +- no `_JsonNullable` occurrences — the public API shape survived +- `JsonNullable<@Nullable` present — JSpecify annotates the value, not the wrapper +- `@Nullable` in type position (`private @Nullable String x;`) +- no `@jakarta.annotation.Nullable` / `Nonnull` left in models + +The `toString` check is the important one: losing it is invisible in a build and starts writing +personal data to logs. + +### 8 — Update the documentation + +Revise `sdk/custom-template-changes.md` so it describes only what still differs from upstream. Drop +entries that upstream has absorbed. + +### 9 — Commit + +Commit the templates, the regenerated sources and the documentation together: + +``` +Update OpenAPI generator templates to v +``` diff --git a/.claude/skills/update-openapi-templates b/.claude/skills/update-openapi-templates new file mode 120000 index 0000000..7f5e845 --- /dev/null +++ b/.claude/skills/update-openapi-templates @@ -0,0 +1 @@ +../../.agents/skills/update-openapi-templates \ No newline at end of file diff --git a/.github/workflows/sdk.yml b/.github/workflows/sdk.yml new file mode 100644 index 0000000..82f3cf9 --- /dev/null +++ b/.github/workflows/sdk.yml @@ -0,0 +1,146 @@ +name: SDK + +on: + push: + branches: [main] + paths: ['spec/**', 'sdk/**', 'buildSrc/**', 'gradle/**', 'build.gradle', 'settings.gradle', '.github/workflows/sdk.yml'] + pull_request: + paths: ['spec/**', 'sdk/**', 'buildSrc/**', 'gradle/**', 'build.gradle', 'settings.gradle', '.github/workflows/sdk.yml'] + workflow_dispatch: + +permissions: + contents: read + checks: write + +concurrency: + group: sdk-${{ github.event.pull_request.head.ref || github.ref_name }} + cancel-in-progress: true + +jobs: + generated-sources: + name: Generated sources + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - uses: troii-actions/setup-jvm@v1 + with: + java-version-file: .sdkmanrc + + - name: Generate SDKs + run: ./gradlew openApiGenerate --scan + + - name: Verify generated sources are committed + run: | + # `git diff` alone ignores untracked files, so a newly emitted generated + # file would pass while missing from the repository. + git add --all --intent-to-add . + git diff --exit-code || ( + echo "Generated sources are out of date. Run ./gradlew openApiGenerate and commit the results." + exit 1 + ) + + jvm: + name: ${{ matrix.name }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - name: Java RestClient + module: java-restclient + path: sdk/java-restclient + - name: Java RestTemplate + module: java-resttemplate + path: sdk/java-resttemplate + - name: Kotlin OkHttp + module: kotlin-okhttp + path: sdk/kotlin-okhttp + steps: + - uses: actions/checkout@v6 + + - uses: troii-actions/setup-jvm@v1 + with: + java-version-file: .sdkmanrc + + - name: Assemble and test + run: ./gradlew :${{ matrix.module }}:assemble :${{ matrix.module }}:test --scan + + - name: Publish test report + if: failure() + uses: mikepenz/action-junit-report@v6 + with: + report_paths: '${{ matrix.path }}/build/test-results/test/TEST-*.xml' + check_name: Tests ${{ matrix.name }} + detailed_summary: true + + dotnet: + name: .NET + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - uses: troii-actions/setup-jvm@v1 + with: + java-version-file: .sdkmanrc + + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 8.x + 10.x + + - name: Build .NET SDK + run: ./gradlew :dotnet:dotnetBuild --scan + + swift: + name: Swift + runs-on: macos-latest + steps: + - uses: actions/checkout@v6 + + - uses: troii-actions/setup-jvm@v1 + with: + java-version-file: .sdkmanrc + + - name: Assemble Swift SDK + run: ./gradlew :swift:assemble --scan + + python: + name: Python + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-python@v6 + with: + python-version: '3.9' + + - name: Install SDK + working-directory: sdk/python + run: | + python -m pip install --upgrade pip + pip install . + + # Importing the package exercises every module, so a generator change that + # emits invalid Python fails here. mypy is not run yet: the generator emits a + # duplicate "OAuth2" AuthSettings key for our two-flow OAuth2 scheme. + - name: Verify the package imports + working-directory: sdk/python + run: python -c "import timr_api; print(timr_api.__name__)" + + typescript: + name: TypeScript + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Build TypeScript SDK + working-directory: sdk/typescript-fetch + run: | + npm install + npm run build diff --git a/.gitignore b/.gitignore index cc652ad..592671e 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,9 @@ site/.spec.overlaid.yaml !src/**/build/ .gradletasknamecache +# Python packaging metadata, written next to the package by setuptools and pip install -e +*.egg-info/ + # IntelliJ .idea/* !.idea/codeStyles @@ -18,4 +21,5 @@ site/.spec.overlaid.yaml *.iws out/ -.claude/ +.claude/* +!.claude/skills diff --git a/.sdkmanrc b/.sdkmanrc new file mode 100644 index 0000000..4565c4e --- /dev/null +++ b/.sdkmanrc @@ -0,0 +1,3 @@ +# Enable auto-env through the sdkman_auto_env config +# Add key=value pairs of SDKs to use below +java=25-tem diff --git a/AGENTS.md b/AGENTS.md index 672b024..935c779 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,20 +15,28 @@ finished until the README says so. which overwrites the file. Editing it in this repository has no effect and no lifetime; a contract problem is raised as an issue and corrected at the source. -Everything a tool needs on top of the contract belongs in an overlay, not in the specification: the -try-it console settings live in `spec/overlay.yaml`, applied to the contract by the site build. +Everything a generator needs on top of the contract belongs in an overlay, not in the specification: +try-it console settings, environment-specific servers, and generator capabilities such as `x-parent`. +Whether a generator can express inheritance is a property of that generator — the Java modules ask +for it in their own overlay, while Kotlin cannot extend a final data class and flattens instead. ## Overlays -Overlays are [OpenAPI Overlay 1.0](https://spec.openapis.org/overlay/v1.0.0) documents. The site -applies `spec/overlay.yaml` with bump-cli through `site/scripts/compose-spec.mjs`. +Overlays are [OpenAPI Overlay 1.0](https://spec.openapis.org/overlay/v1.0.0) documents. The format is +what the two builds share; each applies it with the tool native to its own toolchain, because there +is no implementation that serves both. The documentation site applies `spec/overlay.yaml` with +bump-cli through `site/scripts/compose-spec.mjs`. SDK generation applies `sdk/overlay.yaml` to every module and `sdk//openapi-overlay.yaml` to one, in that order, through `ApplyOpenApiOverlaysTask` — OpenAPI Generator has no overlay support of its own, and its normalizer only offers a fixed set of rules. -**An action whose target matches nothing fails the build.** This is deliberate and stricter than the -specification allows, which asks only that such an action be skipped — and a silently skipped action -is how an overlay drifts away from the contract it patches. bump-cli reports it as a warning and -exits successfully, so the site build turns that warning into an error itself. When a specification -sync breaks an overlay, repoint the action; do not delete it without establishing what its target -became. +**An action whose target matches nothing fails the build, on both sides.** This is deliberate and +stricter than the specification allows, which asks only that such an action be skipped — and a +silently skipped action is how an overlay drifts away from the contract it patches. bump-cli reports +it as a warning and exits successfully, so the site build turns that warning into an error itself. +When a specification sync breaks an overlay, repoint the action; do not delete it without +establishing what its target became. + +`x-log` is an allow-list: a field is absent from generated `toString` output unless it is named +there, and `x-log-count` records a collection's size instead of its contents. Adding a field is a +deliberate decision about what may reach a log, not a formality. ## The documentation site @@ -45,3 +53,48 @@ A pull request builds the site and attaches it as an artifact; it is not deploye console only completes its flow on a redirect URI registered with the authorization server, and a preview URL is not one. +## Generated sources are committed + +Regenerate and commit whenever the specification or an overlay changes; CI fails on any drift. + +```bash +./gradlew openApiGenerate +``` + +Generation is wired into the build: every task that reads the generated sources declares a dependency +on `openApiGenerate`, so `./gradlew build` regenerates first and a single invocation is fine. This is +what makes a green build meaningful — before the dependency existed, `build` compiled the *previous* +generation's output and passed even when the current templates or specification did not. + +Gradle modules are named after their directories under `sdk/`: + +```bash +./gradlew :kotlin-okhttp:assemble +``` + +Each SDK carries its own version in `sdk/versions.properties`; `VERSIONING.md` says when which one +moves. + +## Custom generator templates + +The Java modules override generator templates under `sdk/java-*/templates`. Every deliberate +divergence from upstream is recorded in `sdk/custom-template-changes.md` — read it before touching a +template, and keep it accurate afterwards. + +Two things there are easy to break silently: `toString` is an `x-log` allow-list that keeps personal +data out of logs, and the `java` generator resolves `pojo.mustache` **per library**, so the upstream +baseline is `Java/libraries//pojo.mustache`, not `Java/pojo.mustache`. + +Use the `update-openapi-templates` skill when the generator version changes. + +## Skills + +Reusable agent workflows live in `.agents/skills//SKILL.md` — the single source of truth. +Claude Code picks them up through a symlink: + +``` +.claude/commands/.md -> ../../.agents/skills//SKILL.md +``` + +When adding a skill, create the `SKILL.md` (with `name:` and `description:` frontmatter) and the +symlink. Never duplicate the content. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 39eeb31..a83a912 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,27 +5,48 @@ questions and observations are as welcome as patches. ## Where a change belongs +Most of this repository is generated, which decides where a fix has to be made. + **The specification** — `spec/openapi.yaml` — is maintained together with the service and published here with each release. Editing it here has no effect: the next release replaces the file. If an endpoint behaves differently from how it is described, if a field is missing, or if something is described ambiguously, please open an issue. Include the endpoint, what you expected and what you observed; we will correct it at the source and it will arrive with the next release. +**The SDKs** in `sdk/` are generated from the specification. Editing generated sources has the same +problem: the next regeneration overwrites them. What *is* worth changing: + +- the generator configuration in each module's `build.gradle` +- a module's `openapi-overlay.yaml`, when one language needs something the others do not +- the Mustache templates in a module's `templates/` + +If a generated client is awkward to use, an issue describing the awkwardness is more valuable than a +patch to the output — the fix belongs in the configuration or the template, so that it survives. + **The documentation site** in `site/`, and the prose in this repository, can be changed directly. ## Reporting a problem -Please open an issue with the endpoint involved, what you expected, and what happened instead, -including the request and the response with credentials and personal data removed. +Please open an issue with the endpoint or SDK involved, the version, what you expected, and what +happened instead. For an SDK, the language and version help; for the API, the request and the +response, with credentials and personal data removed. Security issues should not be reported through public issues — write to [security@timr.com](mailto:security@timr.com) instead. ## Pull requests -Build what you touched before opening one: +Run the checks before opening one. Generated sources are committed and CI fails on any difference, +so regenerate and include the result: + +```bash +./gradlew openApiGenerate +``` + +Then build what you touched, as separate invocations from the generation step: ```bash +./gradlew :kotlin-okhttp:assemble cd site && npm ci && npm run build ``` diff --git a/README.md b/README.md index 9d3c4ea..299ff3d 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,31 @@ # timr API The public REST API of [timr](https://www.timr.com), the time tracking service: the OpenAPI -specification that defines it, and the developer documentation published at -. +specification that defines it, the developer documentation published at +, and the client SDKs generated from it. Version 1.0 is the first public release of this API. ## How it fits together -The specification is the contract, and the documentation is rendered from it, so it cannot drift -apart from what the service actually serves. +The specification is the contract, and everything else here is derived from it. The documentation +renders it, and every SDK is generated from it, so a single specification update moves the +documentation and all SDKs together and they cannot drift apart from what the service actually +serves. + +``` +spec/openapi.yaml ──┬── site/ → developer.timr.com + └── sdk/ → one client library per language +``` The specification is maintained together with the service and published here with each release. It is therefore not edited in this repository — see [CONTRIBUTING.md](CONTRIBUTING.md) if something in it looks wrong or missing. +The specification carries a version, and each SDK carries a version of its own that states which +contract it speaks — see [VERSIONING.md](VERSIONING.md) for how they move and what a release of each +kind means for an integration. + ## Layout ### `spec/` @@ -38,18 +49,47 @@ copy of the specification as a tag that carries the prose but no operations, gro API itself, so a reader moves from a guide to an endpoint within one navigation rather than crossing into a separate site. The contract itself never carries them. +### `sdk/` + +One generated client library per language, each with the generator configuration it is produced +from. `sdk/overlay.yaml` applies to all of them, and a module carries an `openapi-overlay.yaml` of +its own where a language needs something the others do not: + +| Directory | Language and flavour | +|--------------------------|-----------------------------------| +| `sdk/java-restclient/` | Java, Spring `RestClient` | +| `sdk/java-resttemplate/` | Java, Spring `RestTemplate` | +| `sdk/kotlin-okhttp/` | Kotlin, OkHttp, coroutines | +| `sdk/python/` | Python | +| `sdk/typescript-fetch/` | TypeScript, `fetch` | +| `sdk/swift/` | Swift, Alamofire, async/await | +| `sdk/dotnet/` | C# | + +The generated sources are committed, so the library you read here is exactly the one you get. They +are produced by [OpenAPI Generator](https://openapi-generator.tech) and regenerated whenever the +specification changes; every artifact carries the version of the specification it was built from. + ## Local development +The documentation site: + ```bash cd site npm ci npm run dev ``` -The console runs the OAuth2 authorization code flow with PKCE against the timr authorization server, +Its console runs the OAuth2 authorization code flow with PKCE against the timr authorization server, which accepts only registered redirect URIs — use `http://127.0.0.1:5173/` rather than `localhost`. +The SDKs: + +```bash +./gradlew openApiGenerate +./gradlew :kotlin-okhttp:assemble +``` + ## Contributing Questions, bug reports and pull requests are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). We are -especially interested in how the API holds up in real integrations. +especially interested in how the API and its SDKs hold up in real integrations. diff --git a/VERSIONING.md b/VERSIONING.md new file mode 100644 index 0000000..74ed8fe --- /dev/null +++ b/VERSIONING.md @@ -0,0 +1,59 @@ +# Versioning + +Three numbers describe this API. They move at different rates, so they are kept apart. + +## The path version + +`/v1/` in the server URL is the compatibility boundary. It changes only when the contract breaks, and a +new path version does not retire the old one: both stay served while integrations depend on them. + +## The specification version + +`info.version` is the version of the published contract — what the documentation shows and what a +release note attaches to. It is not a build number and does not track the software behind the API. + +Under a stable path version it moves semantically: **minor** for anything additive (an endpoint, a +field, an enum value), **patch** for a correction that leaves the shape alone (a description, an +example). A break is not a major bump; it is a new path version. + +A version is published only once the API serves what it describes. Anything a release announces can +be called the day it is published. + +Every release ships release notes as a guide, in the same navigation as the rest of the documentation. +They are written against the difference between two releases, not from memory: the difference says +what changed, the notes say what is worth acting on. + +## SDK versions + +Each SDK carries its own semantic version, describing its own surface rather than the contract's. A +generator upgrade that renames methods, a language baseline that drops a runtime, or a package rename +breaks callers while the contract stands still, and a version derived from the contract has no field +left to say so. + +An SDK bumps **major** when its surface breaks, including when it moves to a new path version; +**minor** when regenerating against a new contract adds to it; **patch** for generator, template or +packaging fixes. Majors may move together on a new path version and may drift apart afterwards. +Versions are declared in `sdk/versions.properties`; `sdk/bump-versions.sh minor` carries the whole set +through a contract change, `patch ` moves the clients a fix belongs to, and a major stays a hand +edit. + +Which contract an SDK was generated from is recorded by the commit that built it: specification and +SDKs live in this repository at one revision. The `User-Agent` names the SDK and its version — +`timr-sdk-python/3.1.0` — and nothing else. + +## Publishing + +A release of this repository is a release of the contract: the tag is the contract version, bare, and +the GitHub release is the one to watch for API changes. SDKs are not released by tagging here; each +publishes to its registry at its own version. + +## Release types + +A contract release always carries every SDK with it, regenerated and republished, so no client is left +describing a contract that moved. An SDK release does not imply a contract release. + +| Change | Version affected | Published | +| --- | --- | --- | +| The contract changes | specification minor or patch, SDK minor | documentation, release notes, every SDK | +| A guide or the site changes | none | documentation | +| A generator, template or packaging fix | SDK patch | the SDKs concerned | diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..ca4f7e9 --- /dev/null +++ b/build.gradle @@ -0,0 +1,65 @@ +import com.timr.gradle.ApplyOpenApiOverlaysTask + +// Generate deterministically in UTC, independent of the machine's local time zone, +// so date/date-time example values in the generated code don't drift per developer. +// (-Duser.timezone is ignored on macOS once the default TZ is cached, so set it directly.) +TimeZone.setDefault(TimeZone.getTimeZone('UTC')) + +group = 'com.timr' + +// Each SDK is versioned on its own, in sdk/versions.properties. One version across all of them would +// mean a fix to a single client republishing the other six unchanged, and a version derived from the +// specification could not express a break that is the SDK's own. +ext.sdkVersions = new Properties().with { versions -> + file('sdk/versions.properties').withInputStream { versions.load(it) } + versions +} + +allprojects { + group = rootProject.group +} + +subprojects { + def declared = rootProject.ext.sdkVersions[name] + if (!declared) { + throw new GradleException("sdk/versions.properties declares no version for ${name}") + } + version = declared +} + +def generatedOpenApiSpec = { Project sdkProject -> + sdkProject.layout.buildDirectory.file('generated/openapi/openapi.yaml') +} + +subprojects { sdkProject -> + sdkProject.plugins.withId('org.openapi.generator') { + def prepareOpenApiSpec = sdkProject.tasks.register('prepareOpenApiSpec', ApplyOpenApiOverlaysTask) { + baseSpec = rootProject.layout.projectDirectory.file('spec/openapi.yaml') + overlays.from( + rootProject.layout.projectDirectory.file('sdk/overlay.yaml'), + sdkProject.layout.projectDirectory.file('openapi-overlay.yaml') + ) + outputSpec = generatedOpenApiSpec(sdkProject) + } + + sdkProject.tasks.named('openApiGenerate').configure { task -> + inputSpec.set(generatedOpenApiSpec(sdkProject)) + task.dependsOn(prepareOpenApiSpec) + } + } +} + +tasks.register('openApiGenerate') { + group = 'openapi tools' + subprojects.each { subproject -> + dependsOn subproject.tasks.matching { it.name == 'openApiGenerate' } + } +} + +tasks.register('sdkVersions') { + group = 'help' + description = 'Prints each SDK and the version it publishes at' + doLast { + subprojects.sort { it.name }.each { println "${it.name}=${it.version}" } + } +} diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle new file mode 100644 index 0000000..a4443a8 --- /dev/null +++ b/buildSrc/build.gradle @@ -0,0 +1,14 @@ +plugins { + id 'groovy' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation localGroovy() + implementation gradleApi() + implementation 'org.yaml:snakeyaml:2.2' + implementation 'com.jayway.jsonpath:json-path:2.9.0' +} diff --git a/buildSrc/src/main/groovy/com/timr/gradle/ApplyOpenApiOverlaysTask.groovy b/buildSrc/src/main/groovy/com/timr/gradle/ApplyOpenApiOverlaysTask.groovy new file mode 100644 index 0000000..d3ff6ad --- /dev/null +++ b/buildSrc/src/main/groovy/com/timr/gradle/ApplyOpenApiOverlaysTask.groovy @@ -0,0 +1,197 @@ +package com.timr.gradle + +import com.jayway.jsonpath.Configuration +import com.jayway.jsonpath.JsonPath +import com.jayway.jsonpath.Option +import org.gradle.api.DefaultTask +import org.gradle.api.GradleException +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.InputFile +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import org.yaml.snakeyaml.DumperOptions +import org.yaml.snakeyaml.LoaderOptions +import org.yaml.snakeyaml.Yaml +import org.yaml.snakeyaml.constructor.SafeConstructor + +/** + * Applies OpenAPI Overlay 1.0 documents to a specification. + * + * Unmatched targets fail the build rather than being skipped as the specification allows: a + * silently ignored action is how an overlay drifts away from the contract it patches. + */ +class ApplyOpenApiOverlaysTask extends DefaultTask { + + @InputFile + final RegularFileProperty baseSpec = project.objects.fileProperty() + + @InputFiles + @PathSensitive(PathSensitivity.RELATIVE) + final ConfigurableFileCollection overlays = project.objects.fileCollection() + + @OutputFile + final RegularFileProperty outputSpec = project.objects.fileProperty() + + protected static final Configuration PATHS = Configuration.builder() + .options(Option.AS_PATH_LIST, Option.SUPPRESS_EXCEPTIONS) + .build() + + @TaskAction + void apply() { + def spec = loadYaml(baseSpec.get().asFile) + overlays.files.findAll { it.exists() }.unique().each { overlayFile -> + applyOverlay(spec, loadYaml(overlayFile), overlayFile.name) + } + writeYaml(spec, outputSpec.get().asFile) + } + + protected static void applyOverlay(Object spec, Object overlay, String name) { + if (overlay == null) { + return + } + if (!(overlay instanceof Map) || !((Map) overlay).containsKey('actions')) { + throw new GradleException("$name is not an Overlay document: expected an 'actions' array") + } + def actions = ((Map) overlay).actions + if (!(actions instanceof List)) { + throw new GradleException("$name: 'actions' must be a list") + } + actions.eachWithIndex { Object action, int index -> + if (!(action instanceof Map)) { + throw new GradleException("$name: action #$index must be a mapping") + } + applyAction(spec, (Map) action, "$name action #$index") + } + } + + protected static void applyAction(Object spec, Map action, String where) { + def target = action.target as String + if (!target) { + throw new GradleException("$where is missing a target") + } + List matches = JsonPath.using(PATHS).parse(spec).read(target) as List + if (!matches) { + throw new GradleException("$where matches nothing: $target") + } + boolean remove = action.remove == true + if (remove && action.containsKey('update')) { + throw new GradleException("$where must not combine 'remove' with 'update'") + } + matches.each { String path -> + def tokens = parsePath(path) + if (remove) { + removeAt(spec, tokens) + } else { + merge(resolve(spec, tokens), action.update) + } + } + } + + /** Splits a JsonPath-normalised path such as {@code $['a'][0]['b']} into its tokens. */ + protected static List parsePath(String path) { + def tokens = [] + def matcher = path =~ /\[(?:'([^']*)'|(\d+))]/ + while (matcher.find()) { + tokens << (matcher.group(1) != null ? matcher.group(1) : Integer.parseInt(matcher.group(2))) + } + tokens + } + + protected static Object resolve(Object root, List tokens) { + tokens.inject(root) { node, token -> child(node, token) } + } + + protected static Object child(Object node, Object token) { + if (node instanceof Map) { + return ((Map) node).get(token) + } + if (node instanceof List && token instanceof Integer) { + return ((List) node).get((int) token) + } + throw new GradleException("Cannot navigate into ${node?.class?.simpleName} with '$token'") + } + + protected static void removeAt(Object root, List tokens) { + if (tokens.isEmpty()) { + throw new GradleException('Cannot remove the document root') + } + def parent = resolve(root, tokens[0.. + if (isExtension(key)) { + normaliseRefSibling(targetMap) + } + def existing = targetMap.get(key) + if (existing instanceof Map && value instanceof Map) { + merge(existing, value) + } else { + targetMap.put(key, value) + } + } + } + + protected static boolean isExtension(Object key) { + key instanceof String && ((String) key).startsWith('x-') + } + + /** + * A sibling of {@code $ref} is ignored by JSON Schema, so wrap the reference in an allOf before + * an extension is added next to it. + */ + protected static void normaliseRefSibling(Map node) { + if (!node.containsKey('$ref')) { + return + } + def ref = node.remove('$ref') + def allOf = node.get('allOf') + if (!(allOf instanceof List)) { + node.put('allOf', [['$ref': ref]]) + } else if (!allOf.any { it instanceof Map && ((Map) it).get('$ref') == ref }) { + allOf.add(0, ['$ref': ref]) + } + } + + protected static Object loadYaml(File file) { + if (!file.exists()) { + throw new GradleException("Spec file not found: $file") + } + def loaderOptions = new LoaderOptions() + loaderOptions.codePointLimit = 16 * 1024 * 1024 + def yaml = new Yaml(new SafeConstructor(loaderOptions)) + file.withReader('UTF-8') { reader -> yaml.load(reader) } + } + + protected static void writeYaml(Object data, File destination) { + destination.parentFile.mkdirs() + def options = new DumperOptions() + options.defaultFlowStyle = DumperOptions.FlowStyle.BLOCK + options.prettyFlow = true + options.indent = 2 + options.indicatorIndent = 1 + options.defaultScalarStyle = DumperOptions.ScalarStyle.PLAIN + destination.withWriter('UTF-8') { writer -> new Yaml(options).dump(data, writer) } + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..86bc023 --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +org.gradle.welcome=never diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..b87d4c2 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,32 @@ +[versions] +openapi-generator = "7.22.0" +spring-boot = "4.0.5" +jackson-nullable = "0.2.10" +jakarta-annotation = "3.0.0" +jspecify = "1.0.0" +swagger-annotations = "1.6.14" +junit-jupiter = "5.12.2" +junit-platform = "1.12.2" +kotlin = "2.4.10" +kotlinx-coroutines = "1.8.0" +gson = "2.10.1" +okhttp = "4.12.0" + +[libraries] +jackson-nullable = { module = "org.openapitools:jackson-databind-nullable", version.ref = "jackson-nullable" } +spring-boot-dependencies = { module = "org.springframework.boot:spring-boot-dependencies", version.ref = "spring-boot" } +jakarta-annotation = { module = "jakarta.annotation:jakarta.annotation-api", version.ref = "jakarta-annotation" } +jspecify = { module = "org.jspecify:jspecify", version.ref = "jspecify" } +swagger-annotations = { module = "io.swagger:swagger-annotations", version.ref = "swagger-annotations" } +junit-jupiter-api = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit-jupiter" } +junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine", version.ref = "junit-jupiter" } +junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher", version.ref = "junit-platform" } +kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8", version.ref = "kotlin" } +kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } +kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" } +gson = { module = "com.google.code.gson:gson", version.ref = "gson" } +okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } + +[plugins] +openapi = { id = "org.openapi.generator", version.ref = "openapi-generator" } +kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..eddabd2 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ad7845b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..249efbb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..a51ec4f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/sdk/bump-versions.sh b/sdk/bump-versions.sh new file mode 100755 index 0000000..7a48e84 --- /dev/null +++ b/sdk/bump-versions.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# Bumps the versions in sdk/versions.properties. +# +# sdk/bump-versions.sh minor every SDK, for a release that follows a specification update +# sdk/bump-versions.sh patch python one or more SDKs, for a generator, template or packaging fix +# +# A specification update carries every client with it, so the whole set moves together; a fix that is +# one client's own moves that client alone. Names are the module directories under sdk/. See +# VERSIONING.md for which level a change calls for. +set -euo pipefail + +versions="$(cd "$(dirname "$0")" && pwd)/versions.properties" + +usage() { + echo "usage: $(basename "$0") minor|patch [sdk...]" >&2 + exit 2 +} + +[ $# -ge 1 ] || usage +level=$1 +shift +case $level in + minor | patch) ;; + *) usage ;; +esac + +declared=$(grep -oE '^[^#][^=]*' "$versions" | sed 's/[[:space:]]*$//') + +# Resolve every requested name before touching the file, so a typo cannot leave a half applied bump. +if [ $# -eq 0 ]; then + selected=$declared +else + selected="" + for name in "$@"; do + match=$(printf '%s\n' "$declared" | grep -xF "$name" || true) + case $(printf '%s' "$match" | grep -c .) in + 1) selected="$selected$match"$'\n' ;; + 0) + echo "error: $versions declares no SDK matching '$name'" >&2 + exit 1 + ;; + *) + echo "error: '$name' matches more than one SDK:" >&2 + printf ' %s\n' $match >&2 + exit 1 + ;; + esac + done +fi + +bump() { + local current=$1 + if ! [[ $current =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then + echo "error: '$current' is not a version this script can bump" >&2 + exit 1 + fi + local major=${BASH_REMATCH[1]} minor_part=${BASH_REMATCH[2]} patch_part=${BASH_REMATCH[3]} + if [ "$level" = minor ]; then + echo "$major.$((minor_part + 1)).0" + else + echo "$major.$minor_part.$((patch_part + 1))" + fi +} + +for name in $selected; do + current=$(grep -E "^$name=" "$versions" | cut -d= -f2) + next=$(bump "$current") + # Rewrite in place, leaving the comments and the order of the file alone. + awk -v name="$name" -v bumped="$next" -F= ' + $1 == name { print name "=" bumped; next } + { print } + ' "$versions" > "$versions.rewritten" + mv "$versions.rewritten" "$versions" + printf '%-24s %s -> %s\n' "$name" "$current" "$next" +done diff --git a/sdk/custom-template-changes.md b/sdk/custom-template-changes.md new file mode 100644 index 0000000..445df4c --- /dev/null +++ b/sdk/custom-template-changes.md @@ -0,0 +1,146 @@ +# Custom OpenAPI Generator templates + +The Java, Swift and Python SDK modules override some of the generator's Mustache templates. This +file records only what **differs** from upstream, so a version bump can be reconciled by diffing our +copy against the matching upstream file and checking each difference below still applies. + +Generator version: **7.22.0** (`libs.plugins.openapi`). + +## Java + +### Upstream source + +The `java` generator resolves `pojo.mustache` **per library**, so the upstream baseline is not the +generic `Java/pojo.mustache`: + +| Module | Upstream baseline | +| --- | --- | +| `sdk/java-restclient` | `Java/libraries/restclient/pojo.mustache` | +| `sdk/java-resttemplate` | `Java/libraries/resttemplate/pojo.mustache` | + +The two library templates differ from each other (`{{>sealed}}`/`{{>permits}}` and the +`additional_properties` partial path), so the modules do **not** share one file. Diffing against +`Java/pojo.mustache` produces plausible but wrong results — it omits the JSpecify type-position +wiring these libraries use. + +`nullable_var_annotations.mustache` is upstream **verbatim**; it is present only because a +template directory must supply every partial it references indirectly. Under `useJspecify` the +`jSpecifyNullable` lambda deliberately renders nothing there — the annotation moves to the type +position via `nullableDatatypeWithEnum`. + +Extract both from the generator jar rather than GitHub, so the templates match the version we run: + +```bash +unzip -o ~/.gradle/caches/modules-2/files-2.1/org.openapitools/openapi-generator/7.22.0/*/openapi-generator-7.22.0.jar 'Java/*' -d /tmp/upstream +``` + +### Our changes + +### Java 1 — Optionality drives `JsonNullable`, not nullability + +Upstream keys the `JsonNullable` wrapper on `{{#vendorExtensions.x-is-jackson-optional-nullable}}` +(the property is *nullable*). We key it on `{{^required}}` (the property is *optional*), so every +non-required property is wrapped. + +This is the central customisation: the API distinguishes "absent" from "explicitly null", and +`JsonNullable.undefined()` is what carries "absent" through to serialization. A required property is +declared as a plain type even when it is nullable. + +Applied as a polarity swap — `{{#…x-is-jackson-optional-nullable}}` → `{{^required}}`, +`{{^…}}` → `{{#required}}`, `{{/…}}` → `{{/required}}`. Mustache closes both `{{#x}}` and `{{^x}}` +with `{{/x}}`, so renaming all three forms is a safe textual transformation. + +### Java 2 — `equalsNullable` / `hashCodeNullable` are gated on `openApiNullable` + +Consequence of (1). Upstream emits the helpers under +`{{#vendorExtensions.x-jackson-optional-nullable-helpers}}`, which the generator sets only when it +considers a property optional-nullable. Because we call the helpers for every non-required property, +that extension is false for models the helpers are still needed in, so the gate is +`{{#openApiNullable}}` instead — the config option, which is always on here. + +Symptom if this is lost: `cannot find symbol: equalsNullable` on models whose optional properties are +not nullable. + +### Java 3 — `JsonNullable` is part of the public API + +Upstream generates `T getX()` (unwrapping via `.orElse(null)`, annotated `@JsonIgnore`) plus +`JsonNullable getX_JsonNullable()`, and the same split for setters. We generate a single +`JsonNullable getX()` / `void setX(JsonNullable)` pair and no `_JsonNullable` accessors, so +callers see and set the three-state value directly. The plain `setX(T)` is generated for required +properties only. + +Changing this is a breaking change for SDK consumers, not a template detail. + +### Java 4 — JSpecify annotates the wrapped value, not the wrapper + +Where a field or getter is `JsonNullable<…>`, the inner type is rendered with +`{{>nullableDatatypeWithEnum}}`, giving `JsonNullable<@Nullable T>`. Annotating the wrapper instead +would claim the `JsonNullable` reference itself can be null, which it never is — it is initialised to +`JsonNullable.undefined()`. + +### Java 5 — `toString` is an allow-list + +Upstream prints every property. We print a property only if it carries `x-log`, or its size only if it +carries `x-log-count`. Both are set in `sdk/overlay.yaml`. + +This is a privacy control, not formatting: names, plates, e-mail addresses and other personal data +must not reach a log. A refork that restores upstream's unconditional `{{#vars}}` loop silently starts +logging all of it. See `AGENTS.md`. + +### Java 6 — Imports + +`JsonNullable` and `com.fasterxml.jackson.annotation.*` are prepended, since (1) and (3) reference +them in models where upstream would not. + +## Swift + +Upstream baseline: `swift5/*.mustache`. + +`projectName` is `Timr`, which is what makes the generated API class read `TimrAPI`. Upstream ties +the Swift module, the SwiftPM package and the pod name to that same property, which would make them +`Timr` too, so three overrides pull the packaging identity back to `TimrApi`: + +- **`Package.swift.mustache`** and **`Podspec.mustache`** — these read `{{moduleName}}` where + upstream reads `{{projectName}}`, and nothing else differs. `moduleName` is passed through + `additionalProperties` in `build.gradle`, so both names stay single-sourced there rather than + baked into a template. (`configOptions` does *not* reach the template context for this generator; + `additionalProperties` does.) +- The generator names the podspec file after `projectName` in *code*, not in a template, so + `openApiGenerate` is finalized by a `renamePodspec` task that moves `Timr.podspec` to + `TimrApi.podspec`. CocoaPods requires the filename to match the pod name. + +Neither file is frozen, so the pod version keeps tracking `info.version` from the specification. +`Package.swift` carries no version at all — SwiftPM resolves versions from git tags. + +- **`APIs.mustache`** — `Task` is written as `_Concurrency.Task`, because the API has a `Task` + schema whose generated model shadows Swift's `Task` and breaks `Task.checkCancellation()`. + `addCredential()` also returns `Self` and is no longer called from the initializer, so credentials + are attached explicitly rather than on every request. + +## Python + +Upstream baseline: `python/*.mustache`. + +- **`setup.mustache`** — `PYTHON_REQUIRES` is `>= 3.9`. Upstream hardcodes `>= 3.10` there while + `pyproject.mustache` hardcodes `>=3.9`, so the two shipped files contradict each other and neither + is configurable. The generated code is 3.9-compatible — no PEP 604 unions, `typing_extensions.Self` + rather than `typing.Self` — so 3.9 is the truthful bound. + +## Verifying a refork + +Compilation depends on generation, so one invocation regenerates and rebuilds: + +```bash +./gradlew :java-restclient:build :java-resttemplate:build +``` + +Then confirm against the previously generated sources: + +- `toString` line count is unchanged — proves (5) survived +- no `_JsonNullable` occurrences — proves (3) survived +- `JsonNullable<@Nullable` appears — proves (4) survived +- `@Nullable` is in type position (`private @Nullable String x;`) + +A mismatched Mustache section tag fails generation with +`Section close tag with mismatched open tag`, naming a line in the *rendered* partial rather than our +file, so check tag balance before generating. diff --git a/sdk/dotnet/.gitignore b/sdk/dotnet/.gitignore new file mode 100644 index 0000000..5d74f71 --- /dev/null +++ b/sdk/dotnet/.gitignore @@ -0,0 +1,496 @@ +# Created by https://www.toptal.com/developers/gitignore/api/dotnetcore,visualstudio,rider +# Edit at https://www.toptal.com/developers/gitignore?templates=dotnetcore,visualstudio,rider + +### DotnetCore ### +# .NET Core build folders +bin/ +obj/ + +# Common node modules locations +/node_modules +/wwwroot/node_modules + +### Rider ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/dotnetcore,visualstudio,rider + +# OpenApiGenerator generated meta files +.openapi-generator diff --git a/sdk/dotnet/.openapi-generator-ignore b/sdk/dotnet/.openapi-generator-ignore new file mode 100644 index 0000000..45f6e45 --- /dev/null +++ b/sdk/dotnet/.openapi-generator-ignore @@ -0,0 +1,14 @@ +.gitignore +appveyor.yml +README.md + +api/** +docs/** + +Timr.Api.sln + +Timr.Api/Timr.Api.csproj +Timr.Api/README.md +Timr.Api/Program.cs + +Timr.Api.Test/ diff --git a/sdk/dotnet/Timr.Api.Test/JsonSerializerFixture.cs b/sdk/dotnet/Timr.Api.Test/JsonSerializerFixture.cs new file mode 100644 index 0000000..5586f70 --- /dev/null +++ b/sdk/dotnet/Timr.Api.Test/JsonSerializerFixture.cs @@ -0,0 +1,32 @@ +using System; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Timr.Api.Client; + +namespace Timr.Api.Test; + +/// +/// Builds the same JsonSerializerOptions the SDK uses in production. +/// +public sealed class JsonSerializerFixture : IDisposable +{ + private readonly ServiceProvider _provider; + + public JsonSerializerOptions Options { get; } + + public JsonSerializerFixture() + { + var services = new ServiceCollection(); + + // HostConfiguration wires up all custom converters and registers the provider. + new HostConfiguration(services); + + _provider = services.BuildServiceProvider(); + Options = _provider.GetRequiredService().Options; + } + + public T Deserialize(string json) => + JsonSerializer.Deserialize(json, Options)!; + + public void Dispose() => _provider.Dispose(); +} diff --git a/sdk/dotnet/Timr.Api.Test/Model/ProjectTimeJsonTests.cs b/sdk/dotnet/Timr.Api.Test/Model/ProjectTimeJsonTests.cs new file mode 100644 index 0000000..cce3969 --- /dev/null +++ b/sdk/dotnet/Timr.Api.Test/Model/ProjectTimeJsonTests.cs @@ -0,0 +1,153 @@ +using Timr.Api.Model; +using Xunit; + +namespace Timr.Api.Test.Model; + +public class ProjectTimeJsonTests : IClassFixture +{ + private readonly JsonSerializerFixture _fixture; + + public ProjectTimeJsonTests(JsonSerializerFixture fixture) + { + _fixture = fixture; + } + + [Fact] + public void Deserializes_ProjectTime_With_Null_EndPlatform() + { + const string json = """ + { + "id": "a131c9ef-9b3c-448a-808f-4f412f1eb344", + "start": "2025-11-19T08:00:00+01:00", + "end": null, + "break_time_total_minutes": 0, + "break_times": [], + "changed": false, + "user": { + "id": "ad903edc-0a96-4ec1-ba22-f18e721978e1", + "firstname": "Max", + "lastname": "Muster", + "fullname": "Max Muster", + "email": "max@example.com", + "employee_number": null, + "external_id": null + }, + "task": { + "id": "ad903edc-0a96-4ec1-ba22-f18e721978e1", + "name": "Task", + "breadcrumbs": "Task", + "external_id": null + }, + "billable": true, + "start_platform": "timr_api", + "end_platform": null, + "last_modified": "2025-11-19T08:00:00+01:00", + "status": "running", + "duration": null, + "notes": null, + "start_location": null, + "end_location": null, + "last_modified_by": null + } + """; + + var projectTime = _fixture.Deserialize(json); + + Assert.Equal(Platform.TimrApi, projectTime.StartPlatform); + Assert.Null(projectTime.EndPlatform); + } + + [Fact] + public void Deserializes_ProjectTime_With_Null_StartPlatform() + { + // start_platform is required (always present) but nullable: getCurrentPlatform() + // on the backend returns null for non-platform auth contexts, so the value can be null. + const string json = """ + { + "id": "a131c9ef-9b3c-448a-808f-4f412f1eb344", + "start": "2025-11-19T08:00:00+01:00", + "end": null, + "break_time_total_minutes": 0, + "break_times": [], + "changed": false, + "user": { + "id": "ad903edc-0a96-4ec1-ba22-f18e721978e1", + "firstname": "Max", + "lastname": "Muster", + "fullname": "Max Muster", + "email": "max@example.com", + "employee_number": null, + "external_id": null + }, + "task": { + "id": "ad903edc-0a96-4ec1-ba22-f18e721978e1", + "name": "Task", + "breadcrumbs": "Task", + "external_id": null + }, + "billable": true, + "start_platform": null, + "end_platform": null, + "last_modified": "2025-11-19T08:00:00+01:00", + "status": "running", + "duration": null, + "notes": null, + "start_location": null, + "end_location": null, + "last_modified_by": null + } + """; + + var projectTime = _fixture.Deserialize(json); + + Assert.Null(projectTime.StartPlatform); + Assert.Null(projectTime.EndPlatform); + } + + [Fact] + public void Leaves_Optional_Property_Unset_When_Absent_From_Json() + { + // "metadata" is the only non-required property on ProjectTime and is + // deliberately omitted here; an absent optional property must stay unset + // (IsSet == false), as opposed to a present-but-null required property. + const string json = """ + { + "id": "a131c9ef-9b3c-448a-808f-4f412f1eb344", + "start": "2025-11-19T08:00:00+01:00", + "end": "2025-11-19T09:00:00+01:00", + "break_time_total_minutes": 0, + "break_times": [], + "changed": false, + "user": { + "id": "ad903edc-0a96-4ec1-ba22-f18e721978e1", + "firstname": "Max", + "lastname": "Muster", + "fullname": "Max Muster", + "email": "max@example.com", + "employee_number": null, + "external_id": null + }, + "task": { + "id": "ad903edc-0a96-4ec1-ba22-f18e721978e1", + "name": "Task", + "breadcrumbs": "Task", + "external_id": null + }, + "billable": true, + "start_platform": "timr_api", + "end_platform": "timr_api", + "last_modified": "2025-11-19T08:00:00+01:00", + "status": "approved", + "duration": null, + "notes": null, + "start_location": null, + "end_location": null, + "last_modified_by": null + } + """; + + var projectTime = _fixture.Deserialize(json); + + Assert.False(projectTime.MetadataOption.IsSet); + } +} diff --git a/sdk/dotnet/Timr.Api.Test/Model/TaskJsonTests.cs b/sdk/dotnet/Timr.Api.Test/Model/TaskJsonTests.cs new file mode 100644 index 0000000..2e41b5b --- /dev/null +++ b/sdk/dotnet/Timr.Api.Test/Model/TaskJsonTests.cs @@ -0,0 +1,86 @@ +using System; +using Timr.Api.Client; +using Timr.Api.Model; +using Xunit; + +namespace Timr.Api.Test.Model; + +public class TaskJsonTests : IClassFixture +{ + private readonly JsonSerializerFixture _fixture; + + public TaskJsonTests(JsonSerializerFixture fixture) + { + _fixture = fixture; + } + + [Fact] + public void Deserializes_Task_With_Custom_Converters() + { + const string json = """ + { + "id": "a131c9ef-9b3c-448a-808f-4f412f1eb344", + "name": "10010 - Wildpfad 167, Hagen", + "breadcrumbs": "Acadoro Aufträge Süd-West/10010 - Wildpfad 167, Hagen", + "external_id": "10010", + "parent_task": { + "id": "ad903edc-0a96-4ec1-ba22-f18e721978e1", + "name": "Acadoro Aufträge Süd-West", + "breadcrumbs": "Acadoro Aufträge Süd-West", + "external_id": "rootSuedWest" + }, + "description": null, + "description_external": null, + "bookable": false, + "billable": true, + "project_time_notes_required": false, + "start_date": null, + "end_date": "2025-11-19", + "lock_date": null, + "earliest_start_time": null, + "latest_end_time": null, + "active_from": null, + "active_to": "2025-11-19", + "location_inherited": true, + "location": null, + "location_restriction_radius_meters": null, + "custom_field_1": "10010", + "custom_field_2": null, + "custom_field_3": null + } + """; + + var task = _fixture.Deserialize(json); + + Assert.Equal("a131c9ef-9b3c-448a-808f-4f412f1eb344", task.Id); + Assert.Equal("10010 - Wildpfad 167, Hagen", task.Name); + Assert.Equal("Acadoro Aufträge Süd-West/10010 - Wildpfad 167, Hagen", task.Breadcrumbs); + Assert.Equal("10010", task.ExternalId); + + // Parent Task + + Assert.Null(task.Description); + Assert.Null(task.DescriptionExternal); + Assert.False(task.Bookable); + Assert.True(task.Billable); + Assert.False(task.ProjectTimeNotesRequired); + Assert.Null(task.StartDate); + Assert.Equal(new DateOnly(2025, 11, 19), task.EndDate); + Assert.Null(task.LockDate); + Assert.Null(task.EarliestStartTime); + Assert.Null(task.LatestEndTime); + Assert.Null(task.ActiveFrom); + Assert.Equal(new DateOnly(2025, 11, 19), task.ActiveTo); + Assert.True(task.LocationInherited); + Assert.Null(task.Location); + Assert.Null(task.LocationRestrictionRadiusMeters); + Assert.Equal("10010", task.CustomField1); + + Assert.False(task.BudgetInheritedOption.IsSet); + Assert.False(task.BudgetPlanningTypeOption.IsSet); + Assert.False(task.BudgetHourlyRateOption.IsSet); + Assert.False(task.BudgetPlannedOption.IsSet); + Assert.False(task.BudgetIncludeNonBillableProjectTimesOption.IsSet); + + } +} diff --git a/sdk/dotnet/Timr.Api.Test/Timr.Api.Test.csproj b/sdk/dotnet/Timr.Api.Test/Timr.Api.Test.csproj new file mode 100644 index 0000000..3bbfeba --- /dev/null +++ b/sdk/dotnet/Timr.Api.Test/Timr.Api.Test.csproj @@ -0,0 +1,20 @@ + + + + Timr.Api.Test + Timr.Api.Test + net8.0;net10.0 + false + enable + + + + + + + + + + + + diff --git a/sdk/dotnet/Timr.Api.slnx b/sdk/dotnet/Timr.Api.slnx new file mode 100644 index 0000000..32605d8 --- /dev/null +++ b/sdk/dotnet/Timr.Api.slnx @@ -0,0 +1,4 @@ + + + + diff --git a/sdk/dotnet/Timr.Api/Api/CarApi.cs b/sdk/dotnet/Timr.Api/Api/CarApi.cs new file mode 100644 index 0000000..d86701e --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/CarApi.cs @@ -0,0 +1,1985 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface ICarApi : IApi + { + /// + /// The class containing the events + /// + CarApiEvents Events { get; } + + /// + /// Create a Car + /// + /// + /// Creates a Car from the data in the request body. + /// + /// Thrown when fails to make API call + /// Car entity + /// Cancellation Token to cancel the request. + /// <> + Task CreateCarAsync(CarCreate carCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Car + /// + /// + /// Creates a Car from the data in the request body. + /// + /// Car entity + /// Cancellation Token to cancel the request. + /// <?> + Task CreateCarOrDefaultAsync(CarCreate carCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Cars + /// + /// + /// Lists the Cars the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Cars whose name or plate contains this text. (optional) + /// Only return Cars that are usable (true) or not usable (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchCarsAsync(Option nameOrPlate = default, Option usable = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Cars + /// + /// + /// Lists the Cars the authenticated user or API token can access. + /// + /// Only return Cars whose name or plate contains this text. (optional) + /// Only return Cars that are usable (true) or not usable (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchCarsOrDefaultAsync(Option nameOrPlate = default, Option usable = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Car + /// + /// + /// Returns a single Car by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Car. + /// Cancellation Token to cancel the request. + /// <> + Task GetCarAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Car + /// + /// + /// Returns a single Car by its ID. + /// + /// ID of the Car. + /// Cancellation Token to cancel the request. + /// <?> + Task GetCarOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Car + /// + /// + /// Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Car. + /// Car entity + /// Cancellation Token to cancel the request. + /// <> + Task UpdateCarAsync(string id, CarUpdate carUpdate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Car + /// + /// + /// Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Car. + /// Car entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpdateCarOrDefaultAsync(string id, CarUpdate carUpdate, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateCarApiResponse : Timr.Api.Client.IApiResponse, ICreated, IBadRequest, IForbidden, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IFetchCarsApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetCarApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IUpdateCarApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest, IForbidden, INotFound, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class CarApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateCar; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateCar; + + internal void ExecuteOnCreateCar(CarApi.CreateCarApiResponse apiResponse) + { + OnCreateCar?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateCar(Exception exception) + { + OnErrorCreateCar?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchCars; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchCars; + + internal void ExecuteOnFetchCars(CarApi.FetchCarsApiResponse apiResponse) + { + OnFetchCars?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchCars(Exception exception) + { + OnErrorFetchCars?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetCar; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetCar; + + internal void ExecuteOnGetCar(CarApi.GetCarApiResponse apiResponse) + { + OnGetCar?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetCar(Exception exception) + { + OnErrorGetCar?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpdateCar; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateCar; + + internal void ExecuteOnUpdateCar(CarApi.UpdateCarApiResponse apiResponse) + { + OnUpdateCar?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateCar(Exception exception) + { + OnErrorUpdateCar?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class CarApi : ICarApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public CarApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public CarApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, CarApiEvents carApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = carApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateCar(CarCreate carCreate); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateCar(CarCreate carCreate) + { + if (carCreate == null) + throw new ArgumentNullException(nameof(carCreate)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateCarDefaultImplementation(ICreateCarApiResponse apiResponseLocalVar, CarCreate carCreate) + { + bool suppressDefaultLog = false; + AfterCreateCar(ref suppressDefaultLog, apiResponseLocalVar, carCreate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateCar(ref bool suppressDefaultLog, ICreateCarApiResponse apiResponseLocalVar, CarCreate carCreate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateCarDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, CarCreate carCreate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateCar(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, carCreate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateCar(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, CarCreate carCreate); + + /// + /// Create a Car Creates a Car from the data in the request body. + /// + /// Car entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateCarOrDefaultAsync(CarCreate carCreate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateCarAsync(carCreate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Car Creates a Car from the data in the request body. + /// + /// Thrown when fails to make API call + /// Car entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateCarAsync(CarCreate carCreate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateCar(carCreate); + + FormatCreateCar(carCreate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cars" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/cars"); + + httpRequestMessageLocalVar.Content = (carCreate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(carCreate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateCarApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/cars", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateCarDefaultImplementation(apiResponseLocalVar, carCreate); + + Events.ExecuteOnCreateCar(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateCarDefaultImplementation(e, "/cars", uriBuilderLocalVar.Path, carCreate); + Events.ExecuteOnErrorCreateCar(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateCarApiResponse : Timr.Api.Client.ApiResponse, ICreateCarApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateCarApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateCarApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.Car? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.Car? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchCars(ref Option nameOrPlate, ref Option usable, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchCars(Option nameOrPlate, Option pageToken) + { + if (nameOrPlate.IsSet && nameOrPlate.Value == null) + throw new ArgumentNullException(nameof(nameOrPlate)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchCarsDefaultImplementation(IFetchCarsApiResponse apiResponseLocalVar, Option nameOrPlate, Option usable, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchCars(ref suppressDefaultLog, apiResponseLocalVar, nameOrPlate, usable, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchCars(ref bool suppressDefaultLog, IFetchCarsApiResponse apiResponseLocalVar, Option nameOrPlate, Option usable, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchCarsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option nameOrPlate, Option usable, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchCars(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, nameOrPlate, usable, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchCars(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option nameOrPlate, Option usable, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Cars Lists the Cars the authenticated user or API token can access. + /// + /// Only return Cars whose name or plate contains this text. (optional) + /// Only return Cars that are usable (true) or not usable (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchCarsOrDefaultAsync(Option nameOrPlate = default, Option usable = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchCarsAsync(nameOrPlate, usable, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Cars Lists the Cars the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Cars whose name or plate contains this text. (optional) + /// Only return Cars that are usable (true) or not usable (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchCarsAsync(Option nameOrPlate = default, Option usable = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchCars(nameOrPlate, pageToken); + + FormatFetchCars(ref nameOrPlate, ref usable, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cars" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/cars"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (nameOrPlate.IsSet) + parseQueryStringLocalVar["name_or_plate"] = ClientUtils.ParameterToString(nameOrPlate.Value); + + if (usable.IsSet) + parseQueryStringLocalVar["usable"] = ClientUtils.ParameterToString(usable.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchCarsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/cars", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchCarsDefaultImplementation(apiResponseLocalVar, nameOrPlate, usable, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchCars(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchCarsDefaultImplementation(e, "/cars", uriBuilderLocalVar.Path, nameOrPlate, usable, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchCars(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchCarsApiResponse : Timr.Api.Client.ApiResponse, IFetchCarsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchCarsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchCarsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.CarsPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.CarsPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetCar(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetCar(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetCarDefaultImplementation(IGetCarApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetCar(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetCar(ref bool suppressDefaultLog, IGetCarApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetCarDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetCar(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetCar(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Car Returns a single Car by its ID. + /// + /// ID of the Car. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetCarOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetCarAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Car Returns a single Car by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Car. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetCarAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetCar(id); + + FormatGetCar(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cars/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/cars/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetCarApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/cars/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetCarDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetCar(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetCarDefaultImplementation(e, "/cars/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetCar(e); + throw; + } + } + + /// + /// The + /// + public partial class GetCarApiResponse : Timr.Api.Client.ApiResponse, IGetCarApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetCarApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetCarApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.Car? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.Car? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpdateCar(ref string id, CarUpdate carUpdate); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateCar(string id, CarUpdate carUpdate) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (carUpdate == null) + throw new ArgumentNullException(nameof(carUpdate)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateCarDefaultImplementation(IUpdateCarApiResponse apiResponseLocalVar, string id, CarUpdate carUpdate) + { + bool suppressDefaultLog = false; + AfterUpdateCar(ref suppressDefaultLog, apiResponseLocalVar, id, carUpdate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateCar(ref bool suppressDefaultLog, IUpdateCarApiResponse apiResponseLocalVar, string id, CarUpdate carUpdate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateCarDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, CarUpdate carUpdate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpdateCar(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, carUpdate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateCar(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, CarUpdate carUpdate); + + /// + /// Update a Car Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Car. + /// Car entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateCarOrDefaultAsync(string id, CarUpdate carUpdate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateCarAsync(id, carUpdate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Update a Car Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Car. + /// Car entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateCarAsync(string id, CarUpdate carUpdate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateCar(id, carUpdate); + + FormatUpdateCar(ref id, carUpdate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/cars/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/cars/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (carUpdate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(carUpdate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpdateCarApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/cars/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpdateCarDefaultImplementation(apiResponseLocalVar, id, carUpdate); + + Events.ExecuteOnUpdateCar(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateCarDefaultImplementation(e, "/cars/{id}", uriBuilderLocalVar.Path, id, carUpdate); + Events.ExecuteOnErrorUpdateCar(e); + throw; + } + } + + /// + /// The + /// + public partial class UpdateCarApiResponse : Timr.Api.Client.ApiResponse, IUpdateCarApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateCarApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateCarApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.Car? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.Car? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/DriveLogApi.cs b/sdk/dotnet/Timr.Api/Api/DriveLogApi.cs new file mode 100644 index 0000000..84b2727 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/DriveLogApi.cs @@ -0,0 +1,2868 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IDriveLogApi : IApi + { + /// + /// The class containing the events + /// + DriveLogApiEvents Events { get; } + + /// + /// Create a Drive Log + /// + /// + /// Creates a Drive Log from the data in the request body. + /// + /// Thrown when fails to make API call + /// Drive Log entity + /// Cancellation Token to cancel the request. + /// <> + Task CreateDriveLogAsync(DriveLogCreate driveLogCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Drive Log + /// + /// + /// Creates a Drive Log from the data in the request body. + /// + /// Drive Log entity + /// Cancellation Token to cancel the request. + /// <?> + Task CreateDriveLogOrDefaultAsync(DriveLogCreate driveLogCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Drive Log + /// + /// + /// Deletes the Drive Log, including its Track. + /// + /// Thrown when fails to make API call + /// ID of the Drive Log. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteDriveLogAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Drive Log + /// + /// + /// Deletes the Drive Log, including its Track. + /// + /// ID of the Drive Log. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteDriveLogOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List deleted Drive Logs + /// + /// + /// Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + /// + /// Thrown when fails to make API call + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchDeletedDriveLogsAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List deleted Drive Logs + /// + /// + /// Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + /// + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchDeletedDriveLogsOrDefaultAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Drive Logs + /// + /// + /// Lists the Drive Logs the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries recorded for these Cars. (optional) + /// Only return entries in these Drive Log Categories. (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return Drive Logs whose route, purpose or visited contains this text. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Only return Drive Logs that have a Track (true) or have none (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchDriveLogsAsync(Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option> cars = default, Option> driveLogCategories = default, Option> statuses = default, Option> users = default, Option details = default, Option changed = default, Option hasTrack = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Drive Logs + /// + /// + /// Lists the Drive Logs the authenticated user or API token can access. + /// + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries recorded for these Cars. (optional) + /// Only return entries in these Drive Log Categories. (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return Drive Logs whose route, purpose or visited contains this text. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Only return Drive Logs that have a Track (true) or have none (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchDriveLogsOrDefaultAsync(Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option> cars = default, Option> driveLogCategories = default, Option> statuses = default, Option> users = default, Option details = default, Option changed = default, Option hasTrack = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Drive Log + /// + /// + /// Returns a single Drive Log by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Drive Log. + /// Cancellation Token to cancel the request. + /// <> + Task GetDriveLogAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Drive Log + /// + /// + /// Returns a single Drive Log by its ID. + /// + /// ID of the Drive Log. + /// Cancellation Token to cancel the request. + /// <?> + Task GetDriveLogOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Drive Log + /// + /// + /// Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Drive Log. + /// Drive Log entity + /// Cancellation Token to cancel the request. + /// <> + Task UpdateDriveLogAsync(string id, DriveLogUpdate driveLogUpdate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Drive Log + /// + /// + /// Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Drive Log. + /// Drive Log entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpdateDriveLogOrDefaultAsync(string id, DriveLogUpdate driveLogUpdate, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateDriveLogApiResponse : Timr.Api.Client.IApiResponse, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IDeleteDriveLogApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchDeletedDriveLogsApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IFetchDriveLogsApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetDriveLogApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IUpdateDriveLogApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest, IForbidden, INotFound, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class DriveLogApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateDriveLog; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateDriveLog; + + internal void ExecuteOnCreateDriveLog(DriveLogApi.CreateDriveLogApiResponse apiResponse) + { + OnCreateDriveLog?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateDriveLog(Exception exception) + { + OnErrorCreateDriveLog?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteDriveLog; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteDriveLog; + + internal void ExecuteOnDeleteDriveLog(DriveLogApi.DeleteDriveLogApiResponse apiResponse) + { + OnDeleteDriveLog?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteDriveLog(Exception exception) + { + OnErrorDeleteDriveLog?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchDeletedDriveLogs; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchDeletedDriveLogs; + + internal void ExecuteOnFetchDeletedDriveLogs(DriveLogApi.FetchDeletedDriveLogsApiResponse apiResponse) + { + OnFetchDeletedDriveLogs?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchDeletedDriveLogs(Exception exception) + { + OnErrorFetchDeletedDriveLogs?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchDriveLogs; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchDriveLogs; + + internal void ExecuteOnFetchDriveLogs(DriveLogApi.FetchDriveLogsApiResponse apiResponse) + { + OnFetchDriveLogs?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchDriveLogs(Exception exception) + { + OnErrorFetchDriveLogs?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetDriveLog; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetDriveLog; + + internal void ExecuteOnGetDriveLog(DriveLogApi.GetDriveLogApiResponse apiResponse) + { + OnGetDriveLog?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetDriveLog(Exception exception) + { + OnErrorGetDriveLog?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpdateDriveLog; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateDriveLog; + + internal void ExecuteOnUpdateDriveLog(DriveLogApi.UpdateDriveLogApiResponse apiResponse) + { + OnUpdateDriveLog?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateDriveLog(Exception exception) + { + OnErrorUpdateDriveLog?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class DriveLogApi : IDriveLogApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public DriveLogApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public DriveLogApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, DriveLogApiEvents driveLogApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = driveLogApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateDriveLog(DriveLogCreate driveLogCreate); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateDriveLog(DriveLogCreate driveLogCreate) + { + if (driveLogCreate == null) + throw new ArgumentNullException(nameof(driveLogCreate)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateDriveLogDefaultImplementation(ICreateDriveLogApiResponse apiResponseLocalVar, DriveLogCreate driveLogCreate) + { + bool suppressDefaultLog = false; + AfterCreateDriveLog(ref suppressDefaultLog, apiResponseLocalVar, driveLogCreate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateDriveLog(ref bool suppressDefaultLog, ICreateDriveLogApiResponse apiResponseLocalVar, DriveLogCreate driveLogCreate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateDriveLogDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, DriveLogCreate driveLogCreate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateDriveLog(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, driveLogCreate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateDriveLog(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, DriveLogCreate driveLogCreate); + + /// + /// Create a Drive Log Creates a Drive Log from the data in the request body. + /// + /// Drive Log entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateDriveLogOrDefaultAsync(DriveLogCreate driveLogCreate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateDriveLogAsync(driveLogCreate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Drive Log Creates a Drive Log from the data in the request body. + /// + /// Thrown when fails to make API call + /// Drive Log entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateDriveLogAsync(DriveLogCreate driveLogCreate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateDriveLog(driveLogCreate); + + FormatCreateDriveLog(driveLogCreate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs"); + + httpRequestMessageLocalVar.Content = (driveLogCreate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(driveLogCreate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateDriveLogApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateDriveLogDefaultImplementation(apiResponseLocalVar, driveLogCreate); + + Events.ExecuteOnCreateDriveLog(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateDriveLogDefaultImplementation(e, "/drive-logs", uriBuilderLocalVar.Path, driveLogCreate); + Events.ExecuteOnErrorCreateDriveLog(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateDriveLogApiResponse : Timr.Api.Client.ApiResponse, ICreateDriveLogApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateDriveLogApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateDriveLogApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.DriveLog? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.DriveLog? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatDeleteDriveLog(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteDriveLog(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteDriveLogDefaultImplementation(IDeleteDriveLogApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterDeleteDriveLog(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteDriveLog(ref bool suppressDefaultLog, IDeleteDriveLogApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteDriveLogDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteDriveLog(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteDriveLog(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Delete a Drive Log Deletes the Drive Log, including its Track. + /// + /// ID of the Drive Log. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteDriveLogOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteDriveLogAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Drive Log Deletes the Drive Log, including its Track. + /// + /// Thrown when fails to make API call + /// ID of the Drive Log. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteDriveLogAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteDriveLog(id); + + FormatDeleteDriveLog(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteDriveLogApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteDriveLogDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnDeleteDriveLog(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteDriveLogDefaultImplementation(e, "/drive-logs/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorDeleteDriveLog(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteDriveLogApiResponse : Timr.Api.Client.ApiResponse, IDeleteDriveLogApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteDriveLogApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteDriveLogApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchDeletedDriveLogs(ref Option lastModifiedAfter, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFetchDeletedDriveLogs(Option pageToken) + { + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchDeletedDriveLogsDefaultImplementation(IFetchDeletedDriveLogsApiResponse apiResponseLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchDeletedDriveLogs(ref suppressDefaultLog, apiResponseLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchDeletedDriveLogs(ref bool suppressDefaultLog, IFetchDeletedDriveLogsApiResponse apiResponseLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchDeletedDriveLogsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchDeletedDriveLogs(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchDeletedDriveLogs(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List deleted Drive Logs Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + /// + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDeletedDriveLogsOrDefaultAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchDeletedDriveLogsAsync(lastModifiedAfter, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List deleted Drive Logs Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + /// + /// Thrown when fails to make API call + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDeletedDriveLogsAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchDeletedDriveLogs(pageToken); + + FormatFetchDeletedDriveLogs(ref lastModifiedAfter, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs:deleted" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs:deleted"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (lastModifiedAfter.IsSet) + parseQueryStringLocalVar["last_modified_after"] = ClientUtils.ParameterToString(lastModifiedAfter.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchDeletedDriveLogsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs:deleted", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchDeletedDriveLogsDefaultImplementation(apiResponseLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchDeletedDriveLogs(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchDeletedDriveLogsDefaultImplementation(e, "/drive-logs:deleted", uriBuilderLocalVar.Path, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchDeletedDriveLogs(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchDeletedDriveLogsApiResponse : Timr.Api.Client.ApiResponse, IFetchDeletedDriveLogsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDeletedDriveLogsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDeletedDriveLogsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.DeletedEntryPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.DeletedEntryPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchDriveLogs(ref Option startFrom, ref Option startTo, ref Option lastModifiedAfter, Option> cars, Option> driveLogCategories, Option> statuses, Option> users, ref Option details, ref Option changed, ref Option hasTrack, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + private void ValidateFetchDriveLogs(Option> cars, Option> driveLogCategories, Option> statuses, Option> users, Option details, Option pageToken) + { + if (cars.IsSet && cars.Value == null) + throw new ArgumentNullException(nameof(cars)); + + if (driveLogCategories.IsSet && driveLogCategories.Value == null) + throw new ArgumentNullException(nameof(driveLogCategories)); + + if (statuses.IsSet && statuses.Value == null) + throw new ArgumentNullException(nameof(statuses)); + + if (users.IsSet && users.Value == null) + throw new ArgumentNullException(nameof(users)); + + if (details.IsSet && details.Value == null) + throw new ArgumentNullException(nameof(details)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchDriveLogsDefaultImplementation(IFetchDriveLogsApiResponse apiResponseLocalVar, Option startFrom, Option startTo, Option lastModifiedAfter, Option> cars, Option> driveLogCategories, Option> statuses, Option> users, Option details, Option changed, Option hasTrack, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchDriveLogs(ref suppressDefaultLog, apiResponseLocalVar, startFrom, startTo, lastModifiedAfter, cars, driveLogCategories, statuses, users, details, changed, hasTrack, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchDriveLogs(ref bool suppressDefaultLog, IFetchDriveLogsApiResponse apiResponseLocalVar, Option startFrom, Option startTo, Option lastModifiedAfter, Option> cars, Option> driveLogCategories, Option> statuses, Option> users, Option details, Option changed, Option hasTrack, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchDriveLogsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option startFrom, Option startTo, Option lastModifiedAfter, Option> cars, Option> driveLogCategories, Option> statuses, Option> users, Option details, Option changed, Option hasTrack, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchDriveLogs(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, startFrom, startTo, lastModifiedAfter, cars, driveLogCategories, statuses, users, details, changed, hasTrack, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchDriveLogs(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option startFrom, Option startTo, Option lastModifiedAfter, Option> cars, Option> driveLogCategories, Option> statuses, Option> users, Option details, Option changed, Option hasTrack, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Drive Logs Lists the Drive Logs the authenticated user or API token can access. + /// + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries recorded for these Cars. (optional) + /// Only return entries in these Drive Log Categories. (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return Drive Logs whose route, purpose or visited contains this text. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Only return Drive Logs that have a Track (true) or have none (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDriveLogsOrDefaultAsync(Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option> cars = default, Option> driveLogCategories = default, Option> statuses = default, Option> users = default, Option details = default, Option changed = default, Option hasTrack = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchDriveLogsAsync(startFrom, startTo, lastModifiedAfter, cars, driveLogCategories, statuses, users, details, changed, hasTrack, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Drive Logs Lists the Drive Logs the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries recorded for these Cars. (optional) + /// Only return entries in these Drive Log Categories. (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return Drive Logs whose route, purpose or visited contains this text. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Only return Drive Logs that have a Track (true) or have none (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDriveLogsAsync(Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option> cars = default, Option> driveLogCategories = default, Option> statuses = default, Option> users = default, Option details = default, Option changed = default, Option hasTrack = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchDriveLogs(cars, driveLogCategories, statuses, users, details, pageToken); + + FormatFetchDriveLogs(ref startFrom, ref startTo, ref lastModifiedAfter, cars, driveLogCategories, statuses, users, ref details, ref changed, ref hasTrack, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (startFrom.IsSet) + parseQueryStringLocalVar["start_from"] = ClientUtils.ParameterToString(startFrom.Value); + + if (startTo.IsSet) + parseQueryStringLocalVar["start_to"] = ClientUtils.ParameterToString(startTo.Value); + + if (lastModifiedAfter.IsSet) + parseQueryStringLocalVar["last_modified_after"] = ClientUtils.ParameterToString(lastModifiedAfter.Value); + + if (cars.IsSet) + parseQueryStringLocalVar["cars"] = ClientUtils.ParameterToString(cars.Value); + + if (driveLogCategories.IsSet) + parseQueryStringLocalVar["drive_log_categories"] = ClientUtils.ParameterToString(driveLogCategories.Value); + + if (statuses.IsSet) + parseQueryStringLocalVar["statuses"] = ClientUtils.ParameterToString(statuses.Value); + + if (users.IsSet) + parseQueryStringLocalVar["users"] = ClientUtils.ParameterToString(users.Value); + + if (details.IsSet) + parseQueryStringLocalVar["details"] = ClientUtils.ParameterToString(details.Value); + + if (changed.IsSet) + parseQueryStringLocalVar["changed"] = ClientUtils.ParameterToString(changed.Value); + + if (hasTrack.IsSet) + parseQueryStringLocalVar["has_track"] = ClientUtils.ParameterToString(hasTrack.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchDriveLogsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchDriveLogsDefaultImplementation(apiResponseLocalVar, startFrom, startTo, lastModifiedAfter, cars, driveLogCategories, statuses, users, details, changed, hasTrack, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchDriveLogs(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchDriveLogsDefaultImplementation(e, "/drive-logs", uriBuilderLocalVar.Path, startFrom, startTo, lastModifiedAfter, cars, driveLogCategories, statuses, users, details, changed, hasTrack, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchDriveLogs(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchDriveLogsApiResponse : Timr.Api.Client.ApiResponse, IFetchDriveLogsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDriveLogsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDriveLogsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.DriveLogsPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.DriveLogsPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetDriveLog(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetDriveLog(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetDriveLogDefaultImplementation(IGetDriveLogApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetDriveLog(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetDriveLog(ref bool suppressDefaultLog, IGetDriveLogApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetDriveLogDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetDriveLog(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetDriveLog(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Drive Log Returns a single Drive Log by its ID. + /// + /// ID of the Drive Log. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetDriveLogOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetDriveLogAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Drive Log Returns a single Drive Log by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Drive Log. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetDriveLogAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetDriveLog(id); + + FormatGetDriveLog(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetDriveLogApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetDriveLogDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetDriveLog(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetDriveLogDefaultImplementation(e, "/drive-logs/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetDriveLog(e); + throw; + } + } + + /// + /// The + /// + public partial class GetDriveLogApiResponse : Timr.Api.Client.ApiResponse, IGetDriveLogApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetDriveLogApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetDriveLogApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.DriveLog? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.DriveLog? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpdateDriveLog(ref string id, DriveLogUpdate driveLogUpdate); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateDriveLog(string id, DriveLogUpdate driveLogUpdate) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (driveLogUpdate == null) + throw new ArgumentNullException(nameof(driveLogUpdate)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateDriveLogDefaultImplementation(IUpdateDriveLogApiResponse apiResponseLocalVar, string id, DriveLogUpdate driveLogUpdate) + { + bool suppressDefaultLog = false; + AfterUpdateDriveLog(ref suppressDefaultLog, apiResponseLocalVar, id, driveLogUpdate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateDriveLog(ref bool suppressDefaultLog, IUpdateDriveLogApiResponse apiResponseLocalVar, string id, DriveLogUpdate driveLogUpdate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateDriveLogDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, DriveLogUpdate driveLogUpdate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpdateDriveLog(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, driveLogUpdate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateDriveLog(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, DriveLogUpdate driveLogUpdate); + + /// + /// Update a Drive Log Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Drive Log. + /// Drive Log entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateDriveLogOrDefaultAsync(string id, DriveLogUpdate driveLogUpdate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateDriveLogAsync(id, driveLogUpdate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Update a Drive Log Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Drive Log. + /// Drive Log entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateDriveLogAsync(string id, DriveLogUpdate driveLogUpdate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateDriveLog(id, driveLogUpdate); + + FormatUpdateDriveLog(ref id, driveLogUpdate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (driveLogUpdate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(driveLogUpdate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpdateDriveLogApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpdateDriveLogDefaultImplementation(apiResponseLocalVar, id, driveLogUpdate); + + Events.ExecuteOnUpdateDriveLog(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateDriveLogDefaultImplementation(e, "/drive-logs/{id}", uriBuilderLocalVar.Path, id, driveLogUpdate); + Events.ExecuteOnErrorUpdateDriveLog(e); + throw; + } + } + + /// + /// The + /// + public partial class UpdateDriveLogApiResponse : Timr.Api.Client.ApiResponse, IUpdateDriveLogApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateDriveLogApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateDriveLogApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.DriveLog? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.DriveLog? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/DriveLogCategoryApi.cs b/sdk/dotnet/Timr.Api/Api/DriveLogCategoryApi.cs new file mode 100644 index 0000000..76baeed --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/DriveLogCategoryApi.cs @@ -0,0 +1,896 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IDriveLogCategoryApi : IApi + { + /// + /// The class containing the events + /// + DriveLogCategoryApiEvents Events { get; } + + /// + /// List Drive Log Categories + /// + /// + /// Lists the Drive Log Categories the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchDriveLogCategoriesAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Drive Log Categories + /// + /// + /// Lists the Drive Log Categories the authenticated user or API token can access. + /// + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchDriveLogCategoriesOrDefaultAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Drive Log Category + /// + /// + /// Returns a single Drive Log Category by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Drive Log Category. + /// Cancellation Token to cancel the request. + /// <> + Task GetDriveLogCategoryAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Drive Log Category + /// + /// + /// Returns a single Drive Log Category by its ID. + /// + /// ID of the Drive Log Category. + /// Cancellation Token to cancel the request. + /// <?> + Task GetDriveLogCategoryOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface IFetchDriveLogCategoriesApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetDriveLogCategoryApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class DriveLogCategoryApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchDriveLogCategories; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchDriveLogCategories; + + internal void ExecuteOnFetchDriveLogCategories(DriveLogCategoryApi.FetchDriveLogCategoriesApiResponse apiResponse) + { + OnFetchDriveLogCategories?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchDriveLogCategories(Exception exception) + { + OnErrorFetchDriveLogCategories?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetDriveLogCategory; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetDriveLogCategory; + + internal void ExecuteOnGetDriveLogCategory(DriveLogCategoryApi.GetDriveLogCategoryApiResponse apiResponse) + { + OnGetDriveLogCategory?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetDriveLogCategory(Exception exception) + { + OnErrorGetDriveLogCategory?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class DriveLogCategoryApi : IDriveLogCategoryApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public DriveLogCategoryApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public DriveLogCategoryApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, DriveLogCategoryApiEvents driveLogCategoryApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = driveLogCategoryApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatFetchDriveLogCategories(ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFetchDriveLogCategories(Option pageToken) + { + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + private void AfterFetchDriveLogCategoriesDefaultImplementation(IFetchDriveLogCategoriesApiResponse apiResponseLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchDriveLogCategories(ref suppressDefaultLog, apiResponseLocalVar, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchDriveLogCategories(ref bool suppressDefaultLog, IFetchDriveLogCategoriesApiResponse apiResponseLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchDriveLogCategoriesDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchDriveLogCategories(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchDriveLogCategories(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Drive Log Categories Lists the Drive Log Categories the authenticated user or API token can access. + /// + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDriveLogCategoriesOrDefaultAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchDriveLogCategoriesAsync(pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Drive Log Categories Lists the Drive Log Categories the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDriveLogCategoriesAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchDriveLogCategories(pageToken); + + FormatFetchDriveLogCategories(ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-log-categories" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-log-categories"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchDriveLogCategoriesApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-log-categories", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchDriveLogCategoriesDefaultImplementation(apiResponseLocalVar, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchDriveLogCategories(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchDriveLogCategoriesDefaultImplementation(e, "/drive-log-categories", uriBuilderLocalVar.Path, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchDriveLogCategories(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchDriveLogCategoriesApiResponse : Timr.Api.Client.ApiResponse, IFetchDriveLogCategoriesApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDriveLogCategoriesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDriveLogCategoriesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.DriveLogCategoriesPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.DriveLogCategoriesPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetDriveLogCategory(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetDriveLogCategory(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetDriveLogCategoryDefaultImplementation(IGetDriveLogCategoryApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetDriveLogCategory(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetDriveLogCategory(ref bool suppressDefaultLog, IGetDriveLogCategoryApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetDriveLogCategoryDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetDriveLogCategory(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetDriveLogCategory(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Drive Log Category Returns a single Drive Log Category by its ID. + /// + /// ID of the Drive Log Category. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetDriveLogCategoryOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetDriveLogCategoryAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Drive Log Category Returns a single Drive Log Category by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Drive Log Category. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetDriveLogCategoryAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetDriveLogCategory(id); + + FormatGetDriveLogCategory(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-log-categories/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-log-categories/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetDriveLogCategoryApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-log-categories/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetDriveLogCategoryDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetDriveLogCategory(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetDriveLogCategoryDefaultImplementation(e, "/drive-log-categories/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetDriveLogCategory(e); + throw; + } + } + + /// + /// The + /// + public partial class GetDriveLogCategoryApiResponse : Timr.Api.Client.ApiResponse, IGetDriveLogCategoryApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetDriveLogCategoryApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetDriveLogCategoryApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.DriveLogCategory? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.DriveLogCategory? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/HolidayCalendarApi.cs b/sdk/dotnet/Timr.Api/Api/HolidayCalendarApi.cs new file mode 100644 index 0000000..b88a743 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/HolidayCalendarApi.cs @@ -0,0 +1,1395 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IHolidayCalendarApi : IApi + { + /// + /// The class containing the events + /// + HolidayCalendarApiEvents Events { get; } + + /// + /// List Holiday Calendars + /// + /// + /// Lists the Holiday Calendars the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchHolidayCalendarsAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Holiday Calendars + /// + /// + /// Lists the Holiday Calendars the authenticated user or API token can access. + /// + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchHolidayCalendarsOrDefaultAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Holidays + /// + /// + /// Lists the Holidays in the Holiday Calendar. + /// + /// Thrown when fails to make API call + /// ID of the Holiday Calendar. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchHolidaysAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Holidays + /// + /// + /// Lists the Holidays in the Holiday Calendar. + /// + /// ID of the Holiday Calendar. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchHolidaysOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Holiday Calendar + /// + /// + /// Returns a single Holiday Calendar by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Holiday Calendar. + /// Cancellation Token to cancel the request. + /// <> + Task GetHolidayCalendarAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Holiday Calendar + /// + /// + /// Returns a single Holiday Calendar by its ID. + /// + /// ID of the Holiday Calendar. + /// Cancellation Token to cancel the request. + /// <?> + Task GetHolidayCalendarOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface IFetchHolidayCalendarsApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IFetchHolidaysApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IGetHolidayCalendarApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class HolidayCalendarApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchHolidayCalendars; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchHolidayCalendars; + + internal void ExecuteOnFetchHolidayCalendars(HolidayCalendarApi.FetchHolidayCalendarsApiResponse apiResponse) + { + OnFetchHolidayCalendars?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchHolidayCalendars(Exception exception) + { + OnErrorFetchHolidayCalendars?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchHolidays; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchHolidays; + + internal void ExecuteOnFetchHolidays(HolidayCalendarApi.FetchHolidaysApiResponse apiResponse) + { + OnFetchHolidays?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchHolidays(Exception exception) + { + OnErrorFetchHolidays?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetHolidayCalendar; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetHolidayCalendar; + + internal void ExecuteOnGetHolidayCalendar(HolidayCalendarApi.GetHolidayCalendarApiResponse apiResponse) + { + OnGetHolidayCalendar?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetHolidayCalendar(Exception exception) + { + OnErrorGetHolidayCalendar?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class HolidayCalendarApi : IHolidayCalendarApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public HolidayCalendarApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public HolidayCalendarApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, HolidayCalendarApiEvents holidayCalendarApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = holidayCalendarApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatFetchHolidayCalendars(ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFetchHolidayCalendars(Option pageToken) + { + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + private void AfterFetchHolidayCalendarsDefaultImplementation(IFetchHolidayCalendarsApiResponse apiResponseLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchHolidayCalendars(ref suppressDefaultLog, apiResponseLocalVar, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchHolidayCalendars(ref bool suppressDefaultLog, IFetchHolidayCalendarsApiResponse apiResponseLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchHolidayCalendarsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchHolidayCalendars(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchHolidayCalendars(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Holiday Calendars Lists the Holiday Calendars the authenticated user or API token can access. + /// + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchHolidayCalendarsOrDefaultAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchHolidayCalendarsAsync(pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Holiday Calendars Lists the Holiday Calendars the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchHolidayCalendarsAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchHolidayCalendars(pageToken); + + FormatFetchHolidayCalendars(ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/holiday-calendars" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/holiday-calendars"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchHolidayCalendarsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/holiday-calendars", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchHolidayCalendarsDefaultImplementation(apiResponseLocalVar, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchHolidayCalendars(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchHolidayCalendarsDefaultImplementation(e, "/holiday-calendars", uriBuilderLocalVar.Path, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchHolidayCalendars(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchHolidayCalendarsApiResponse : Timr.Api.Client.ApiResponse, IFetchHolidayCalendarsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchHolidayCalendarsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchHolidayCalendarsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.HolidayCalendarsPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.HolidayCalendarsPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchHolidays(ref string id, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchHolidays(string id, Option pageToken) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchHolidaysDefaultImplementation(IFetchHolidaysApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchHolidays(ref suppressDefaultLog, apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchHolidays(ref bool suppressDefaultLog, IFetchHolidaysApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchHolidaysDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchHolidays(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchHolidays(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Holidays Lists the Holidays in the Holiday Calendar. + /// + /// ID of the Holiday Calendar. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchHolidaysOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchHolidaysAsync(id, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Holidays Lists the Holidays in the Holiday Calendar. + /// + /// Thrown when fails to make API call + /// ID of the Holiday Calendar. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchHolidaysAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchHolidays(id, pageToken); + + FormatFetchHolidays(ref id, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/holiday-calendars/{id}/holidays" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/holiday-calendars/{id}/holidays"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchHolidaysApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/holiday-calendars/{id}/holidays", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchHolidaysDefaultImplementation(apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchHolidays(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchHolidaysDefaultImplementation(e, "/holiday-calendars/{id}/holidays", uriBuilderLocalVar.Path, id, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchHolidays(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchHolidaysApiResponse : Timr.Api.Client.ApiResponse, IFetchHolidaysApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchHolidaysApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchHolidaysApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.HolidaysPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.HolidaysPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetHolidayCalendar(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetHolidayCalendar(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetHolidayCalendarDefaultImplementation(IGetHolidayCalendarApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetHolidayCalendar(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetHolidayCalendar(ref bool suppressDefaultLog, IGetHolidayCalendarApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetHolidayCalendarDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetHolidayCalendar(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetHolidayCalendar(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Holiday Calendar Returns a single Holiday Calendar by its ID. + /// + /// ID of the Holiday Calendar. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetHolidayCalendarOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetHolidayCalendarAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Holiday Calendar Returns a single Holiday Calendar by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Holiday Calendar. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetHolidayCalendarAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetHolidayCalendar(id); + + FormatGetHolidayCalendar(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/holiday-calendars/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/holiday-calendars/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetHolidayCalendarApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/holiday-calendars/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetHolidayCalendarDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetHolidayCalendar(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetHolidayCalendarDefaultImplementation(e, "/holiday-calendars/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetHolidayCalendar(e); + throw; + } + } + + /// + /// The + /// + public partial class GetHolidayCalendarApiResponse : Timr.Api.Client.ApiResponse, IGetHolidayCalendarApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetHolidayCalendarApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetHolidayCalendarApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.HolidayCalendarPartial? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.HolidayCalendarPartial? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/IApi.cs b/sdk/dotnet/Timr.Api/Api/IApi.cs new file mode 100644 index 0000000..32ea8a0 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/IApi.cs @@ -0,0 +1,25 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System.Net.Http; + +namespace Timr.Api.Api +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/ProjectTimeApi.cs b/sdk/dotnet/Timr.Api/Api/ProjectTimeApi.cs new file mode 100644 index 0000000..5c299e0 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/ProjectTimeApi.cs @@ -0,0 +1,2864 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IProjectTimeApi : IApi + { + /// + /// The class containing the events + /// + ProjectTimeApiEvents Events { get; } + + /// + /// Create a Project Time + /// + /// + /// Creates a Project Time from the data in the request body. + /// + /// Thrown when fails to make API call + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <> + Task CreateProjectTimeAsync(ProjectTimeCreate projectTimeCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Project Time + /// + /// + /// Creates a Project Time from the data in the request body. + /// + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <?> + Task CreateProjectTimeOrDefaultAsync(ProjectTimeCreate projectTimeCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Project Time + /// + /// + /// Deletes the Project Time. + /// + /// Thrown when fails to make API call + /// ID of the Project Time. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteProjectTimeAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Project Time + /// + /// + /// Deletes the Project Time. + /// + /// ID of the Project Time. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteProjectTimeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List deleted Project Times + /// + /// + /// Lists Project Times that were deleted, so a client holding a local copy can reconcile. + /// + /// Thrown when fails to make API call + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchDeletedProjectTimesAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List deleted Project Times + /// + /// + /// Lists Project Times that were deleted, so a client holding a local copy can reconcile. + /// + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchDeletedProjectTimesOrDefaultAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Project Times + /// + /// + /// Lists the Project Times the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return entries whose notes contain this text. (optional) + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries recorded on the Task with this ID. (optional) + /// Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchProjectTimesAsync(Option notes = default, Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option task = default, Option traverseTaskTree = default, Option billable = default, Option> statuses = default, Option> users = default, Option changed = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Project Times + /// + /// + /// Lists the Project Times the authenticated user or API token can access. + /// + /// Only return entries whose notes contain this text. (optional) + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries recorded on the Task with this ID. (optional) + /// Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchProjectTimesOrDefaultAsync(Option notes = default, Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option task = default, Option traverseTaskTree = default, Option billable = default, Option> statuses = default, Option> users = default, Option changed = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Project Time + /// + /// + /// Returns a single Project Time by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Project Time. + /// Cancellation Token to cancel the request. + /// <> + Task GetProjectTimeAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Project Time + /// + /// + /// Returns a single Project Time by its ID. + /// + /// ID of the Project Time. + /// Cancellation Token to cancel the request. + /// <?> + Task GetProjectTimeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Project Time + /// + /// + /// Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Project Time. + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <> + Task UpdateProjectTimeAsync(string id, ProjectTimeUpdate projectTimeUpdate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Project Time + /// + /// + /// Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Project Time. + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpdateProjectTimeOrDefaultAsync(string id, ProjectTimeUpdate projectTimeUpdate, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateProjectTimeApiResponse : Timr.Api.Client.IApiResponse, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IDeleteProjectTimeApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchDeletedProjectTimesApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IFetchProjectTimesApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetProjectTimeApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IUpdateProjectTimeApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest, IForbidden, INotFound, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class ProjectTimeApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateProjectTime; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateProjectTime; + + internal void ExecuteOnCreateProjectTime(ProjectTimeApi.CreateProjectTimeApiResponse apiResponse) + { + OnCreateProjectTime?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateProjectTime(Exception exception) + { + OnErrorCreateProjectTime?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteProjectTime; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteProjectTime; + + internal void ExecuteOnDeleteProjectTime(ProjectTimeApi.DeleteProjectTimeApiResponse apiResponse) + { + OnDeleteProjectTime?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteProjectTime(Exception exception) + { + OnErrorDeleteProjectTime?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchDeletedProjectTimes; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchDeletedProjectTimes; + + internal void ExecuteOnFetchDeletedProjectTimes(ProjectTimeApi.FetchDeletedProjectTimesApiResponse apiResponse) + { + OnFetchDeletedProjectTimes?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchDeletedProjectTimes(Exception exception) + { + OnErrorFetchDeletedProjectTimes?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchProjectTimes; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchProjectTimes; + + internal void ExecuteOnFetchProjectTimes(ProjectTimeApi.FetchProjectTimesApiResponse apiResponse) + { + OnFetchProjectTimes?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchProjectTimes(Exception exception) + { + OnErrorFetchProjectTimes?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetProjectTime; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetProjectTime; + + internal void ExecuteOnGetProjectTime(ProjectTimeApi.GetProjectTimeApiResponse apiResponse) + { + OnGetProjectTime?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetProjectTime(Exception exception) + { + OnErrorGetProjectTime?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpdateProjectTime; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateProjectTime; + + internal void ExecuteOnUpdateProjectTime(ProjectTimeApi.UpdateProjectTimeApiResponse apiResponse) + { + OnUpdateProjectTime?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateProjectTime(Exception exception) + { + OnErrorUpdateProjectTime?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class ProjectTimeApi : IProjectTimeApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public ProjectTimeApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ProjectTimeApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, ProjectTimeApiEvents projectTimeApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = projectTimeApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateProjectTime(ProjectTimeCreate projectTimeCreate); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateProjectTime(ProjectTimeCreate projectTimeCreate) + { + if (projectTimeCreate == null) + throw new ArgumentNullException(nameof(projectTimeCreate)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateProjectTimeDefaultImplementation(ICreateProjectTimeApiResponse apiResponseLocalVar, ProjectTimeCreate projectTimeCreate) + { + bool suppressDefaultLog = false; + AfterCreateProjectTime(ref suppressDefaultLog, apiResponseLocalVar, projectTimeCreate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateProjectTime(ref bool suppressDefaultLog, ICreateProjectTimeApiResponse apiResponseLocalVar, ProjectTimeCreate projectTimeCreate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateProjectTimeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, ProjectTimeCreate projectTimeCreate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateProjectTime(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, projectTimeCreate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateProjectTime(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, ProjectTimeCreate projectTimeCreate); + + /// + /// Create a Project Time Creates a Project Time from the data in the request body. + /// + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateProjectTimeOrDefaultAsync(ProjectTimeCreate projectTimeCreate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateProjectTimeAsync(projectTimeCreate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Project Time Creates a Project Time from the data in the request body. + /// + /// Thrown when fails to make API call + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateProjectTimeAsync(ProjectTimeCreate projectTimeCreate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateProjectTime(projectTimeCreate); + + FormatCreateProjectTime(projectTimeCreate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/project-times" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/project-times"); + + httpRequestMessageLocalVar.Content = (projectTimeCreate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(projectTimeCreate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateProjectTimeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/project-times", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateProjectTimeDefaultImplementation(apiResponseLocalVar, projectTimeCreate); + + Events.ExecuteOnCreateProjectTime(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateProjectTimeDefaultImplementation(e, "/project-times", uriBuilderLocalVar.Path, projectTimeCreate); + Events.ExecuteOnErrorCreateProjectTime(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateProjectTimeApiResponse : Timr.Api.Client.ApiResponse, ICreateProjectTimeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateProjectTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateProjectTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.ProjectTime? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.ProjectTime? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatDeleteProjectTime(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteProjectTime(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteProjectTimeDefaultImplementation(IDeleteProjectTimeApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterDeleteProjectTime(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteProjectTime(ref bool suppressDefaultLog, IDeleteProjectTimeApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteProjectTimeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteProjectTime(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteProjectTime(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Delete a Project Time Deletes the Project Time. + /// + /// ID of the Project Time. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteProjectTimeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteProjectTimeAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Project Time Deletes the Project Time. + /// + /// Thrown when fails to make API call + /// ID of the Project Time. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteProjectTimeAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteProjectTime(id); + + FormatDeleteProjectTime(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/project-times/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/project-times/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteProjectTimeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/project-times/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteProjectTimeDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnDeleteProjectTime(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteProjectTimeDefaultImplementation(e, "/project-times/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorDeleteProjectTime(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteProjectTimeApiResponse : Timr.Api.Client.ApiResponse, IDeleteProjectTimeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteProjectTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteProjectTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchDeletedProjectTimes(ref Option lastModifiedAfter, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFetchDeletedProjectTimes(Option pageToken) + { + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchDeletedProjectTimesDefaultImplementation(IFetchDeletedProjectTimesApiResponse apiResponseLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchDeletedProjectTimes(ref suppressDefaultLog, apiResponseLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchDeletedProjectTimes(ref bool suppressDefaultLog, IFetchDeletedProjectTimesApiResponse apiResponseLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchDeletedProjectTimesDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchDeletedProjectTimes(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchDeletedProjectTimes(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List deleted Project Times Lists Project Times that were deleted, so a client holding a local copy can reconcile. + /// + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDeletedProjectTimesOrDefaultAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchDeletedProjectTimesAsync(lastModifiedAfter, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List deleted Project Times Lists Project Times that were deleted, so a client holding a local copy can reconcile. + /// + /// Thrown when fails to make API call + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDeletedProjectTimesAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchDeletedProjectTimes(pageToken); + + FormatFetchDeletedProjectTimes(ref lastModifiedAfter, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/project-times:deleted" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/project-times:deleted"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (lastModifiedAfter.IsSet) + parseQueryStringLocalVar["last_modified_after"] = ClientUtils.ParameterToString(lastModifiedAfter.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchDeletedProjectTimesApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/project-times:deleted", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchDeletedProjectTimesDefaultImplementation(apiResponseLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchDeletedProjectTimes(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchDeletedProjectTimesDefaultImplementation(e, "/project-times:deleted", uriBuilderLocalVar.Path, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchDeletedProjectTimes(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchDeletedProjectTimesApiResponse : Timr.Api.Client.ApiResponse, IFetchDeletedProjectTimesApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDeletedProjectTimesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDeletedProjectTimesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.DeletedEntryWithMetadataPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.DeletedEntryWithMetadataPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchProjectTimes(ref Option notes, ref Option startFrom, ref Option startTo, ref Option lastModifiedAfter, ref Option task, ref Option traverseTaskTree, ref Option billable, Option> statuses, Option> users, ref Option changed, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + private void ValidateFetchProjectTimes(Option notes, Option task, Option> statuses, Option> users, Option pageToken) + { + if (notes.IsSet && notes.Value == null) + throw new ArgumentNullException(nameof(notes)); + + if (task.IsSet && task.Value == null) + throw new ArgumentNullException(nameof(task)); + + if (statuses.IsSet && statuses.Value == null) + throw new ArgumentNullException(nameof(statuses)); + + if (users.IsSet && users.Value == null) + throw new ArgumentNullException(nameof(users)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchProjectTimesDefaultImplementation(IFetchProjectTimesApiResponse apiResponseLocalVar, Option notes, Option startFrom, Option startTo, Option lastModifiedAfter, Option task, Option traverseTaskTree, Option billable, Option> statuses, Option> users, Option changed, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchProjectTimes(ref suppressDefaultLog, apiResponseLocalVar, notes, startFrom, startTo, lastModifiedAfter, task, traverseTaskTree, billable, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchProjectTimes(ref bool suppressDefaultLog, IFetchProjectTimesApiResponse apiResponseLocalVar, Option notes, Option startFrom, Option startTo, Option lastModifiedAfter, Option task, Option traverseTaskTree, Option billable, Option> statuses, Option> users, Option changed, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchProjectTimesDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option notes, Option startFrom, Option startTo, Option lastModifiedAfter, Option task, Option traverseTaskTree, Option billable, Option> statuses, Option> users, Option changed, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchProjectTimes(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, notes, startFrom, startTo, lastModifiedAfter, task, traverseTaskTree, billable, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchProjectTimes(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option notes, Option startFrom, Option startTo, Option lastModifiedAfter, Option task, Option traverseTaskTree, Option billable, Option> statuses, Option> users, Option changed, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Project Times Lists the Project Times the authenticated user or API token can access. + /// + /// Only return entries whose notes contain this text. (optional) + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries recorded on the Task with this ID. (optional) + /// Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchProjectTimesOrDefaultAsync(Option notes = default, Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option task = default, Option traverseTaskTree = default, Option billable = default, Option> statuses = default, Option> users = default, Option changed = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchProjectTimesAsync(notes, startFrom, startTo, lastModifiedAfter, task, traverseTaskTree, billable, statuses, users, changed, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Project Times Lists the Project Times the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return entries whose notes contain this text. (optional) + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries recorded on the Task with this ID. (optional) + /// Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchProjectTimesAsync(Option notes = default, Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option task = default, Option traverseTaskTree = default, Option billable = default, Option> statuses = default, Option> users = default, Option changed = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchProjectTimes(notes, task, statuses, users, pageToken); + + FormatFetchProjectTimes(ref notes, ref startFrom, ref startTo, ref lastModifiedAfter, ref task, ref traverseTaskTree, ref billable, statuses, users, ref changed, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/project-times" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/project-times"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (notes.IsSet) + parseQueryStringLocalVar["notes"] = ClientUtils.ParameterToString(notes.Value); + + if (startFrom.IsSet) + parseQueryStringLocalVar["start_from"] = ClientUtils.ParameterToString(startFrom.Value); + + if (startTo.IsSet) + parseQueryStringLocalVar["start_to"] = ClientUtils.ParameterToString(startTo.Value); + + if (lastModifiedAfter.IsSet) + parseQueryStringLocalVar["last_modified_after"] = ClientUtils.ParameterToString(lastModifiedAfter.Value); + + if (task.IsSet) + parseQueryStringLocalVar["task"] = ClientUtils.ParameterToString(task.Value); + + if (traverseTaskTree.IsSet) + parseQueryStringLocalVar["traverse_task_tree"] = ClientUtils.ParameterToString(traverseTaskTree.Value); + + if (billable.IsSet) + parseQueryStringLocalVar["billable"] = ClientUtils.ParameterToString(billable.Value); + + if (statuses.IsSet) + parseQueryStringLocalVar["statuses"] = ClientUtils.ParameterToString(statuses.Value); + + if (users.IsSet) + parseQueryStringLocalVar["users"] = ClientUtils.ParameterToString(users.Value); + + if (changed.IsSet) + parseQueryStringLocalVar["changed"] = ClientUtils.ParameterToString(changed.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchProjectTimesApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/project-times", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchProjectTimesDefaultImplementation(apiResponseLocalVar, notes, startFrom, startTo, lastModifiedAfter, task, traverseTaskTree, billable, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchProjectTimes(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchProjectTimesDefaultImplementation(e, "/project-times", uriBuilderLocalVar.Path, notes, startFrom, startTo, lastModifiedAfter, task, traverseTaskTree, billable, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchProjectTimes(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchProjectTimesApiResponse : Timr.Api.Client.ApiResponse, IFetchProjectTimesApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchProjectTimesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchProjectTimesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.ProjectTimesPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.ProjectTimesPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetProjectTime(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetProjectTime(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetProjectTimeDefaultImplementation(IGetProjectTimeApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetProjectTime(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetProjectTime(ref bool suppressDefaultLog, IGetProjectTimeApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetProjectTimeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetProjectTime(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetProjectTime(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Project Time Returns a single Project Time by its ID. + /// + /// ID of the Project Time. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetProjectTimeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetProjectTimeAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Project Time Returns a single Project Time by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Project Time. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetProjectTimeAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetProjectTime(id); + + FormatGetProjectTime(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/project-times/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/project-times/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetProjectTimeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/project-times/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetProjectTimeDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetProjectTime(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetProjectTimeDefaultImplementation(e, "/project-times/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetProjectTime(e); + throw; + } + } + + /// + /// The + /// + public partial class GetProjectTimeApiResponse : Timr.Api.Client.ApiResponse, IGetProjectTimeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetProjectTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetProjectTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.ProjectTime? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.ProjectTime? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpdateProjectTime(ref string id, ProjectTimeUpdate projectTimeUpdate); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateProjectTime(string id, ProjectTimeUpdate projectTimeUpdate) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (projectTimeUpdate == null) + throw new ArgumentNullException(nameof(projectTimeUpdate)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateProjectTimeDefaultImplementation(IUpdateProjectTimeApiResponse apiResponseLocalVar, string id, ProjectTimeUpdate projectTimeUpdate) + { + bool suppressDefaultLog = false; + AfterUpdateProjectTime(ref suppressDefaultLog, apiResponseLocalVar, id, projectTimeUpdate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateProjectTime(ref bool suppressDefaultLog, IUpdateProjectTimeApiResponse apiResponseLocalVar, string id, ProjectTimeUpdate projectTimeUpdate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateProjectTimeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, ProjectTimeUpdate projectTimeUpdate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpdateProjectTime(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, projectTimeUpdate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateProjectTime(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, ProjectTimeUpdate projectTimeUpdate); + + /// + /// Update a Project Time Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Project Time. + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateProjectTimeOrDefaultAsync(string id, ProjectTimeUpdate projectTimeUpdate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateProjectTimeAsync(id, projectTimeUpdate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Update a Project Time Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Project Time. + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateProjectTimeAsync(string id, ProjectTimeUpdate projectTimeUpdate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateProjectTime(id, projectTimeUpdate); + + FormatUpdateProjectTime(ref id, projectTimeUpdate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/project-times/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/project-times/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (projectTimeUpdate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(projectTimeUpdate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpdateProjectTimeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/project-times/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpdateProjectTimeDefaultImplementation(apiResponseLocalVar, id, projectTimeUpdate); + + Events.ExecuteOnUpdateProjectTime(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateProjectTimeDefaultImplementation(e, "/project-times/{id}", uriBuilderLocalVar.Path, id, projectTimeUpdate); + Events.ExecuteOnErrorUpdateProjectTime(e); + throw; + } + } + + /// + /// The + /// + public partial class UpdateProjectTimeApiResponse : Timr.Api.Client.ApiResponse, IUpdateProjectTimeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateProjectTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateProjectTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.ProjectTime? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.ProjectTime? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/TaskApi.cs b/sdk/dotnet/Timr.Api/Api/TaskApi.cs new file mode 100644 index 0000000..f2d0387 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/TaskApi.cs @@ -0,0 +1,2474 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface ITaskApi : IApi + { + /// + /// The class containing the events + /// + TaskApiEvents Events { get; } + + /// + /// Create a Task + /// + /// + /// Creates a Task from the data in the request body. + /// + /// Thrown when fails to make API call + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <> + Task CreateTaskAsync(TaskCreate taskCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Task + /// + /// + /// Creates a Task from the data in the request body. + /// + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <?> + Task CreateTaskOrDefaultAsync(TaskCreate taskCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Tasks + /// + /// + /// Lists the Tasks the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Tasks whose parent is the Task with this ID. (optional) + /// Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + /// Only return Users whose name contains this text. (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return Tasks that are active on this day. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchTasksAsync(Option parentTaskId = default, Option traverseTaskTree = default, Option name = default, Option bookable = default, Option billable = default, Option activeAt = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Tasks + /// + /// + /// Lists the Tasks the authenticated user or API token can access. + /// + /// Only return Tasks whose parent is the Task with this ID. (optional) + /// Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + /// Only return Users whose name contains this text. (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return Tasks that are active on this day. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchTasksOrDefaultAsync(Option parentTaskId = default, Option traverseTaskTree = default, Option name = default, Option bookable = default, Option billable = default, Option activeAt = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List a User's Tasks + /// + /// + /// Lists the Tasks the User is assigned to and may record on. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Only return Tasks whose parent is the Task with this ID. (optional) + /// Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + /// Only return Users whose name contains this text. (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return Tasks that are active on this day. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchUserTasksAsync(string id, Option parentTaskId = default, Option traverseTaskTree = default, Option name = default, Option bookable = default, Option billable = default, Option activeAt = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List a User's Tasks + /// + /// + /// Lists the Tasks the User is assigned to and may record on. + /// + /// ID of the User. + /// Only return Tasks whose parent is the Task with this ID. (optional) + /// Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + /// Only return Users whose name contains this text. (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return Tasks that are active on this day. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchUserTasksOrDefaultAsync(string id, Option parentTaskId = default, Option traverseTaskTree = default, Option name = default, Option bookable = default, Option billable = default, Option activeAt = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Task + /// + /// + /// Returns a single Task by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Cancellation Token to cancel the request. + /// <> + Task GetTaskAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Task + /// + /// + /// Returns a single Task by its ID. + /// + /// ID of the Task. + /// Cancellation Token to cancel the request. + /// <?> + Task GetTaskOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Task + /// + /// + /// Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Task entity + /// Cancellation Token to cancel the request. + /// <> + Task UpdateTaskAsync(string id, TaskUpdate taskUpdate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Task + /// + /// + /// Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Task. + /// Task entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpdateTaskOrDefaultAsync(string id, TaskUpdate taskUpdate, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateTaskApiResponse : Timr.Api.Client.IApiResponse, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IFetchTasksApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IFetchUserTasksApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetTaskApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IUpdateTaskApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest, IForbidden, INotFound, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class TaskApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateTask; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateTask; + + internal void ExecuteOnCreateTask(TaskApi.CreateTaskApiResponse apiResponse) + { + OnCreateTask?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTask(Exception exception) + { + OnErrorCreateTask?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchTasks; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchTasks; + + internal void ExecuteOnFetchTasks(TaskApi.FetchTasksApiResponse apiResponse) + { + OnFetchTasks?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchTasks(Exception exception) + { + OnErrorFetchTasks?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchUserTasks; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchUserTasks; + + internal void ExecuteOnFetchUserTasks(TaskApi.FetchUserTasksApiResponse apiResponse) + { + OnFetchUserTasks?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchUserTasks(Exception exception) + { + OnErrorFetchUserTasks?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetTask; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetTask; + + internal void ExecuteOnGetTask(TaskApi.GetTaskApiResponse apiResponse) + { + OnGetTask?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTask(Exception exception) + { + OnErrorGetTask?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpdateTask; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateTask; + + internal void ExecuteOnUpdateTask(TaskApi.UpdateTaskApiResponse apiResponse) + { + OnUpdateTask?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTask(Exception exception) + { + OnErrorUpdateTask?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class TaskApi : ITaskApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public TaskApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public TaskApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TaskApiEvents taskApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = taskApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateTask(TaskCreate taskCreate); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateTask(TaskCreate taskCreate) + { + if (taskCreate == null) + throw new ArgumentNullException(nameof(taskCreate)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateTaskDefaultImplementation(ICreateTaskApiResponse apiResponseLocalVar, TaskCreate taskCreate) + { + bool suppressDefaultLog = false; + AfterCreateTask(ref suppressDefaultLog, apiResponseLocalVar, taskCreate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateTask(ref bool suppressDefaultLog, ICreateTaskApiResponse apiResponseLocalVar, TaskCreate taskCreate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateTaskDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, TaskCreate taskCreate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateTask(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskCreate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateTask(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, TaskCreate taskCreate); + + /// + /// Create a Task Creates a Task from the data in the request body. + /// + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTaskOrDefaultAsync(TaskCreate taskCreate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateTaskAsync(taskCreate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Task Creates a Task from the data in the request body. + /// + /// Thrown when fails to make API call + /// Project Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTaskAsync(TaskCreate taskCreate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateTask(taskCreate); + + FormatCreateTask(taskCreate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks"); + + httpRequestMessageLocalVar.Content = (taskCreate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(taskCreate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateTaskApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateTaskDefaultImplementation(apiResponseLocalVar, taskCreate); + + Events.ExecuteOnCreateTask(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateTaskDefaultImplementation(e, "/tasks", uriBuilderLocalVar.Path, taskCreate); + Events.ExecuteOnErrorCreateTask(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateTaskApiResponse : Timr.Api.Client.ApiResponse, ICreateTaskApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTaskApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTaskApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.Task? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.Task? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchTasks(ref Option parentTaskId, ref Option traverseTaskTree, ref Option name, ref Option bookable, ref Option billable, Option activeAt, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + private void ValidateFetchTasks(Option parentTaskId, Option name, Option pageToken) + { + if (parentTaskId.IsSet && parentTaskId.Value == null) + throw new ArgumentNullException(nameof(parentTaskId)); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchTasksDefaultImplementation(IFetchTasksApiResponse apiResponseLocalVar, Option parentTaskId, Option traverseTaskTree, Option name, Option bookable, Option billable, Option activeAt, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchTasks(ref suppressDefaultLog, apiResponseLocalVar, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchTasks(ref bool suppressDefaultLog, IFetchTasksApiResponse apiResponseLocalVar, Option parentTaskId, Option traverseTaskTree, Option name, Option bookable, Option billable, Option activeAt, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchTasksDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option parentTaskId, Option traverseTaskTree, Option name, Option bookable, Option billable, Option activeAt, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchTasks(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchTasks(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option parentTaskId, Option traverseTaskTree, Option name, Option bookable, Option billable, Option activeAt, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Tasks Lists the Tasks the authenticated user or API token can access. + /// + /// Only return Tasks whose parent is the Task with this ID. (optional) + /// Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + /// Only return Users whose name contains this text. (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return Tasks that are active on this day. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTasksOrDefaultAsync(Option parentTaskId = default, Option traverseTaskTree = default, Option name = default, Option bookable = default, Option billable = default, Option activeAt = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchTasksAsync(parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Tasks Lists the Tasks the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Tasks whose parent is the Task with this ID. (optional) + /// Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + /// Only return Users whose name contains this text. (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return Tasks that are active on this day. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTasksAsync(Option parentTaskId = default, Option traverseTaskTree = default, Option name = default, Option bookable = default, Option billable = default, Option activeAt = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchTasks(parentTaskId, name, pageToken); + + FormatFetchTasks(ref parentTaskId, ref traverseTaskTree, ref name, ref bookable, ref billable, activeAt, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (parentTaskId.IsSet) + parseQueryStringLocalVar["parent_task_id"] = ClientUtils.ParameterToString(parentTaskId.Value); + + if (traverseTaskTree.IsSet) + parseQueryStringLocalVar["traverse_task_tree"] = ClientUtils.ParameterToString(traverseTaskTree.Value); + + if (name.IsSet) + parseQueryStringLocalVar["name"] = ClientUtils.ParameterToString(name.Value); + + if (bookable.IsSet) + parseQueryStringLocalVar["bookable"] = ClientUtils.ParameterToString(bookable.Value); + + if (billable.IsSet) + parseQueryStringLocalVar["billable"] = ClientUtils.ParameterToString(billable.Value); + + if (activeAt.IsSet) + parseQueryStringLocalVar["active_at"] = ClientUtils.ParameterToString(activeAt.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchTasksApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchTasksDefaultImplementation(apiResponseLocalVar, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchTasks(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchTasksDefaultImplementation(e, "/tasks", uriBuilderLocalVar.Path, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchTasks(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchTasksApiResponse : Timr.Api.Client.ApiResponse, IFetchTasksApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTasksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTasksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TasksPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TasksPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchUserTasks(ref string id, ref Option parentTaskId, ref Option traverseTaskTree, ref Option name, ref Option bookable, ref Option billable, Option activeAt, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + private void ValidateFetchUserTasks(string id, Option parentTaskId, Option name, Option pageToken) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (parentTaskId.IsSet && parentTaskId.Value == null) + throw new ArgumentNullException(nameof(parentTaskId)); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchUserTasksDefaultImplementation(IFetchUserTasksApiResponse apiResponseLocalVar, string id, Option parentTaskId, Option traverseTaskTree, Option name, Option bookable, Option billable, Option activeAt, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchUserTasks(ref suppressDefaultLog, apiResponseLocalVar, id, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchUserTasks(ref bool suppressDefaultLog, IFetchUserTasksApiResponse apiResponseLocalVar, string id, Option parentTaskId, Option traverseTaskTree, Option name, Option bookable, Option billable, Option activeAt, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchUserTasksDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option parentTaskId, Option traverseTaskTree, Option name, Option bookable, Option billable, Option activeAt, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchUserTasks(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchUserTasks(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option parentTaskId, Option traverseTaskTree, Option name, Option bookable, Option billable, Option activeAt, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List a User's Tasks Lists the Tasks the User is assigned to and may record on. + /// + /// ID of the User. + /// Only return Tasks whose parent is the Task with this ID. (optional) + /// Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + /// Only return Users whose name contains this text. (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return Tasks that are active on this day. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchUserTasksOrDefaultAsync(string id, Option parentTaskId = default, Option traverseTaskTree = default, Option name = default, Option bookable = default, Option billable = default, Option activeAt = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchUserTasksAsync(id, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List a User's Tasks Lists the Tasks the User is assigned to and may record on. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Only return Tasks whose parent is the Task with this ID. (optional) + /// Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + /// Only return Users whose name contains this text. (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return entries that are billable (true) or not billable (false). (optional) + /// Only return Tasks that are active on this day. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchUserTasksAsync(string id, Option parentTaskId = default, Option traverseTaskTree = default, Option name = default, Option bookable = default, Option billable = default, Option activeAt = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchUserTasks(id, parentTaskId, name, pageToken); + + FormatFetchUserTasks(ref id, ref parentTaskId, ref traverseTaskTree, ref name, ref bookable, ref billable, activeAt, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users/{id}/tasks" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users/{id}/tasks"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (parentTaskId.IsSet) + parseQueryStringLocalVar["parent_task_id"] = ClientUtils.ParameterToString(parentTaskId.Value); + + if (traverseTaskTree.IsSet) + parseQueryStringLocalVar["traverse_task_tree"] = ClientUtils.ParameterToString(traverseTaskTree.Value); + + if (name.IsSet) + parseQueryStringLocalVar["name"] = ClientUtils.ParameterToString(name.Value); + + if (bookable.IsSet) + parseQueryStringLocalVar["bookable"] = ClientUtils.ParameterToString(bookable.Value); + + if (billable.IsSet) + parseQueryStringLocalVar["billable"] = ClientUtils.ParameterToString(billable.Value); + + if (activeAt.IsSet) + parseQueryStringLocalVar["active_at"] = ClientUtils.ParameterToString(activeAt.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchUserTasksApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users/{id}/tasks", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchUserTasksDefaultImplementation(apiResponseLocalVar, id, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchUserTasks(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchUserTasksDefaultImplementation(e, "/users/{id}/tasks", uriBuilderLocalVar.Path, id, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchUserTasks(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchUserTasksApiResponse : Timr.Api.Client.ApiResponse, IFetchUserTasksApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchUserTasksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchUserTasksApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TasksReducedPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TasksReducedPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetTask(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetTask(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetTaskDefaultImplementation(IGetTaskApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetTask(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetTask(ref bool suppressDefaultLog, IGetTaskApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetTaskDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetTask(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetTask(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Task Returns a single Task by its ID. + /// + /// ID of the Task. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTaskOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetTaskAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Task Returns a single Task by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTaskAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetTask(id); + + FormatGetTask(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetTaskApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetTaskDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetTask(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetTaskDefaultImplementation(e, "/tasks/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetTask(e); + throw; + } + } + + /// + /// The + /// + public partial class GetTaskApiResponse : Timr.Api.Client.ApiResponse, IGetTaskApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTaskApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTaskApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.Task? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.Task? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpdateTask(ref string id, TaskUpdate taskUpdate); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateTask(string id, TaskUpdate taskUpdate) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (taskUpdate == null) + throw new ArgumentNullException(nameof(taskUpdate)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateTaskDefaultImplementation(IUpdateTaskApiResponse apiResponseLocalVar, string id, TaskUpdate taskUpdate) + { + bool suppressDefaultLog = false; + AfterUpdateTask(ref suppressDefaultLog, apiResponseLocalVar, id, taskUpdate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateTask(ref bool suppressDefaultLog, IUpdateTaskApiResponse apiResponseLocalVar, string id, TaskUpdate taskUpdate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateTaskDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, TaskUpdate taskUpdate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpdateTask(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, taskUpdate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateTask(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, TaskUpdate taskUpdate); + + /// + /// Update a Task Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Task. + /// Task entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateTaskOrDefaultAsync(string id, TaskUpdate taskUpdate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateTaskAsync(id, taskUpdate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Update a Task Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Task entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateTaskAsync(string id, TaskUpdate taskUpdate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateTask(id, taskUpdate); + + FormatUpdateTask(ref id, taskUpdate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (taskUpdate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(taskUpdate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpdateTaskApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpdateTaskDefaultImplementation(apiResponseLocalVar, id, taskUpdate); + + Events.ExecuteOnUpdateTask(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateTaskDefaultImplementation(e, "/tasks/{id}", uriBuilderLocalVar.Path, id, taskUpdate); + Events.ExecuteOnErrorUpdateTask(e); + throw; + } + } + + /// + /// The + /// + public partial class UpdateTaskApiResponse : Timr.Api.Client.ApiResponse, IUpdateTaskApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateTaskApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateTaskApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.Task? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.Task? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/TaskToLeaderAssignmentApi.cs b/sdk/dotnet/Timr.Api/Api/TaskToLeaderAssignmentApi.cs new file mode 100644 index 0000000..073124f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/TaskToLeaderAssignmentApi.cs @@ -0,0 +1,1897 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface ITaskToLeaderAssignmentApi : IApi + { + /// + /// The class containing the events + /// + TaskToLeaderAssignmentApiEvents Events { get; } + + /// + /// Create a Task to Leader Assignment + /// + /// + /// Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task CreateTaskToLeaderAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Task to Leader Assignment + /// + /// + /// Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task CreateTaskToLeaderAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Task to Leader Assignment + /// + /// + /// Removes the User's leader assignment to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteTaskToLeaderAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Task to Leader Assignment + /// + /// + /// Removes the User's leader assignment to the Task. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteTaskToLeaderAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Task to Leader Assignments + /// + /// + /// Lists the Users assigned to the Task as leaders. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchTaskToLeaderAssignmentsAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Task to Leader Assignments + /// + /// + /// Lists the Users assigned to the Task as leaders. + /// + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchTaskToLeaderAssignmentsOrDefaultAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Task to Leader Assignment + /// + /// + /// Returns the leader assignment of a single User to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task GetTaskToLeaderAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Task to Leader Assignment + /// + /// + /// Returns the leader assignment of a single User to the Task. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task GetTaskToLeaderAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateTaskToLeaderAssignmentApiResponse : Timr.Api.Client.IApiResponse, IOk, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IDeleteTaskToLeaderAssignmentApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchTaskToLeaderAssignmentsApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IGetTaskToLeaderAssignmentApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class TaskToLeaderAssignmentApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateTaskToLeaderAssignment; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateTaskToLeaderAssignment; + + internal void ExecuteOnCreateTaskToLeaderAssignment(TaskToLeaderAssignmentApi.CreateTaskToLeaderAssignmentApiResponse apiResponse) + { + OnCreateTaskToLeaderAssignment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTaskToLeaderAssignment(Exception exception) + { + OnErrorCreateTaskToLeaderAssignment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteTaskToLeaderAssignment; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteTaskToLeaderAssignment; + + internal void ExecuteOnDeleteTaskToLeaderAssignment(TaskToLeaderAssignmentApi.DeleteTaskToLeaderAssignmentApiResponse apiResponse) + { + OnDeleteTaskToLeaderAssignment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteTaskToLeaderAssignment(Exception exception) + { + OnErrorDeleteTaskToLeaderAssignment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchTaskToLeaderAssignments; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchTaskToLeaderAssignments; + + internal void ExecuteOnFetchTaskToLeaderAssignments(TaskToLeaderAssignmentApi.FetchTaskToLeaderAssignmentsApiResponse apiResponse) + { + OnFetchTaskToLeaderAssignments?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchTaskToLeaderAssignments(Exception exception) + { + OnErrorFetchTaskToLeaderAssignments?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetTaskToLeaderAssignment; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetTaskToLeaderAssignment; + + internal void ExecuteOnGetTaskToLeaderAssignment(TaskToLeaderAssignmentApi.GetTaskToLeaderAssignmentApiResponse apiResponse) + { + OnGetTaskToLeaderAssignment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTaskToLeaderAssignment(Exception exception) + { + OnErrorGetTaskToLeaderAssignment?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class TaskToLeaderAssignmentApi : ITaskToLeaderAssignmentApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public TaskToLeaderAssignmentApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public TaskToLeaderAssignmentApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TaskToLeaderAssignmentApiEvents taskToLeaderAssignmentApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = taskToLeaderAssignmentApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateTaskToLeaderAssignment(ref string taskId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateCreateTaskToLeaderAssignment(string taskId, string userId) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterCreateTaskToLeaderAssignmentDefaultImplementation(ICreateTaskToLeaderAssignmentApiResponse apiResponseLocalVar, string taskId, string userId) + { + bool suppressDefaultLog = false; + AfterCreateTaskToLeaderAssignment(ref suppressDefaultLog, apiResponseLocalVar, taskId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterCreateTaskToLeaderAssignment(ref bool suppressDefaultLog, ICreateTaskToLeaderAssignmentApiResponse apiResponseLocalVar, string taskId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorCreateTaskToLeaderAssignmentDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateTaskToLeaderAssignment(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateTaskToLeaderAssignment(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId); + + /// + /// Create a Task to Leader Assignment Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTaskToLeaderAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateTaskToLeaderAssignmentAsync(taskId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Task to Leader Assignment Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTaskToLeaderAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateTaskToLeaderAssignment(taskId, userId); + + FormatCreateTaskToLeaderAssignment(ref taskId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/leaders/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/leaders/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateTaskToLeaderAssignmentApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/leaders/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateTaskToLeaderAssignmentDefaultImplementation(apiResponseLocalVar, taskId, userId); + + Events.ExecuteOnCreateTaskToLeaderAssignment(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateTaskToLeaderAssignmentDefaultImplementation(e, "/tasks/{task_id}/leaders/{user_id}", uriBuilderLocalVar.Path, taskId, userId); + Events.ExecuteOnErrorCreateTaskToLeaderAssignment(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateTaskToLeaderAssignmentApiResponse : Timr.Api.Client.ApiResponse, ICreateTaskToLeaderAssignmentApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTaskToLeaderAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTaskToLeaderAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TaskToLeaderAssignment? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TaskToLeaderAssignment? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.TaskToLeaderAssignment? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.TaskToLeaderAssignment? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatDeleteTaskToLeaderAssignment(ref string taskId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateDeleteTaskToLeaderAssignment(string taskId, string userId) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterDeleteTaskToLeaderAssignmentDefaultImplementation(IDeleteTaskToLeaderAssignmentApiResponse apiResponseLocalVar, string taskId, string userId) + { + bool suppressDefaultLog = false; + AfterDeleteTaskToLeaderAssignment(ref suppressDefaultLog, apiResponseLocalVar, taskId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterDeleteTaskToLeaderAssignment(ref bool suppressDefaultLog, IDeleteTaskToLeaderAssignmentApiResponse apiResponseLocalVar, string taskId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorDeleteTaskToLeaderAssignmentDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteTaskToLeaderAssignment(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteTaskToLeaderAssignment(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId); + + /// + /// Delete a Task to Leader Assignment Removes the User's leader assignment to the Task. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTaskToLeaderAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteTaskToLeaderAssignmentAsync(taskId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Task to Leader Assignment Removes the User's leader assignment to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTaskToLeaderAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteTaskToLeaderAssignment(taskId, userId); + + FormatDeleteTaskToLeaderAssignment(ref taskId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/leaders/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/leaders/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteTaskToLeaderAssignmentApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/leaders/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteTaskToLeaderAssignmentDefaultImplementation(apiResponseLocalVar, taskId, userId); + + Events.ExecuteOnDeleteTaskToLeaderAssignment(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteTaskToLeaderAssignmentDefaultImplementation(e, "/tasks/{task_id}/leaders/{user_id}", uriBuilderLocalVar.Path, taskId, userId); + Events.ExecuteOnErrorDeleteTaskToLeaderAssignment(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteTaskToLeaderAssignmentApiResponse : Timr.Api.Client.ApiResponse, IDeleteTaskToLeaderAssignmentApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTaskToLeaderAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTaskToLeaderAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchTaskToLeaderAssignments(ref string taskId, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchTaskToLeaderAssignments(string taskId, Option pageToken) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchTaskToLeaderAssignmentsDefaultImplementation(IFetchTaskToLeaderAssignmentsApiResponse apiResponseLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchTaskToLeaderAssignments(ref suppressDefaultLog, apiResponseLocalVar, taskId, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchTaskToLeaderAssignments(ref bool suppressDefaultLog, IFetchTaskToLeaderAssignmentsApiResponse apiResponseLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchTaskToLeaderAssignmentsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchTaskToLeaderAssignments(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchTaskToLeaderAssignments(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Task to Leader Assignments Lists the Users assigned to the Task as leaders. + /// + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTaskToLeaderAssignmentsOrDefaultAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchTaskToLeaderAssignmentsAsync(taskId, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Task to Leader Assignments Lists the Users assigned to the Task as leaders. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTaskToLeaderAssignmentsAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchTaskToLeaderAssignments(taskId, pageToken); + + FormatFetchTaskToLeaderAssignments(ref taskId, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/leaders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/leaders"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchTaskToLeaderAssignmentsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/leaders", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchTaskToLeaderAssignmentsDefaultImplementation(apiResponseLocalVar, taskId, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchTaskToLeaderAssignments(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchTaskToLeaderAssignmentsDefaultImplementation(e, "/tasks/{task_id}/leaders", uriBuilderLocalVar.Path, taskId, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchTaskToLeaderAssignments(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchTaskToLeaderAssignmentsApiResponse : Timr.Api.Client.ApiResponse, IFetchTaskToLeaderAssignmentsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTaskToLeaderAssignmentsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTaskToLeaderAssignmentsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TaskToLeaderAssignmentsPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TaskToLeaderAssignmentsPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetTaskToLeaderAssignment(ref string taskId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateGetTaskToLeaderAssignment(string taskId, string userId) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterGetTaskToLeaderAssignmentDefaultImplementation(IGetTaskToLeaderAssignmentApiResponse apiResponseLocalVar, string taskId, string userId) + { + bool suppressDefaultLog = false; + AfterGetTaskToLeaderAssignment(ref suppressDefaultLog, apiResponseLocalVar, taskId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterGetTaskToLeaderAssignment(ref bool suppressDefaultLog, IGetTaskToLeaderAssignmentApiResponse apiResponseLocalVar, string taskId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorGetTaskToLeaderAssignmentDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetTaskToLeaderAssignment(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorGetTaskToLeaderAssignment(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId); + + /// + /// Get a Task to Leader Assignment Returns the leader assignment of a single User to the Task. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTaskToLeaderAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetTaskToLeaderAssignmentAsync(taskId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Task to Leader Assignment Returns the leader assignment of a single User to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTaskToLeaderAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetTaskToLeaderAssignment(taskId, userId); + + FormatGetTaskToLeaderAssignment(ref taskId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/leaders/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/leaders/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetTaskToLeaderAssignmentApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/leaders/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetTaskToLeaderAssignmentDefaultImplementation(apiResponseLocalVar, taskId, userId); + + Events.ExecuteOnGetTaskToLeaderAssignment(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetTaskToLeaderAssignmentDefaultImplementation(e, "/tasks/{task_id}/leaders/{user_id}", uriBuilderLocalVar.Path, taskId, userId); + Events.ExecuteOnErrorGetTaskToLeaderAssignment(e); + throw; + } + } + + /// + /// The + /// + public partial class GetTaskToLeaderAssignmentApiResponse : Timr.Api.Client.ApiResponse, IGetTaskToLeaderAssignmentApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTaskToLeaderAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTaskToLeaderAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TaskToLeaderAssignment? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TaskToLeaderAssignment? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/TaskToTeamAssignmentApi.cs b/sdk/dotnet/Timr.Api/Api/TaskToTeamAssignmentApi.cs new file mode 100644 index 0000000..3ddbbc1 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/TaskToTeamAssignmentApi.cs @@ -0,0 +1,1897 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface ITaskToTeamAssignmentApi : IApi + { + /// + /// The class containing the events + /// + TaskToTeamAssignmentApiEvents Events { get; } + + /// + /// Create a Task to Team Assignment + /// + /// + /// Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + Task CreateTaskToTeamAssignmentAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Task to Team Assignment + /// + /// + /// Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + /// + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <?> + Task CreateTaskToTeamAssignmentOrDefaultAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Task to Team Assignment + /// + /// + /// Removes the Team's assignment to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteTaskToTeamAssignmentAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Task to Team Assignment + /// + /// + /// Removes the Team's assignment to the Task. + /// + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteTaskToTeamAssignmentOrDefaultAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Task to Team Assignments + /// + /// + /// Lists the Teams assigned to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchTaskToTeamAssignmentsAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Task to Team Assignments + /// + /// + /// Lists the Teams assigned to the Task. + /// + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchTaskToTeamAssignmentsOrDefaultAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Task to Team Assignment + /// + /// + /// Returns the assignment of a single Team to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + Task GetTaskToTeamAssignmentAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Task to Team Assignment + /// + /// + /// Returns the assignment of a single Team to the Task. + /// + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <?> + Task GetTaskToTeamAssignmentOrDefaultAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateTaskToTeamAssignmentApiResponse : Timr.Api.Client.IApiResponse, IOk, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IDeleteTaskToTeamAssignmentApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchTaskToTeamAssignmentsApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IGetTaskToTeamAssignmentApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class TaskToTeamAssignmentApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateTaskToTeamAssignment; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateTaskToTeamAssignment; + + internal void ExecuteOnCreateTaskToTeamAssignment(TaskToTeamAssignmentApi.CreateTaskToTeamAssignmentApiResponse apiResponse) + { + OnCreateTaskToTeamAssignment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTaskToTeamAssignment(Exception exception) + { + OnErrorCreateTaskToTeamAssignment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteTaskToTeamAssignment; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteTaskToTeamAssignment; + + internal void ExecuteOnDeleteTaskToTeamAssignment(TaskToTeamAssignmentApi.DeleteTaskToTeamAssignmentApiResponse apiResponse) + { + OnDeleteTaskToTeamAssignment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteTaskToTeamAssignment(Exception exception) + { + OnErrorDeleteTaskToTeamAssignment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchTaskToTeamAssignments; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchTaskToTeamAssignments; + + internal void ExecuteOnFetchTaskToTeamAssignments(TaskToTeamAssignmentApi.FetchTaskToTeamAssignmentsApiResponse apiResponse) + { + OnFetchTaskToTeamAssignments?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchTaskToTeamAssignments(Exception exception) + { + OnErrorFetchTaskToTeamAssignments?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetTaskToTeamAssignment; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetTaskToTeamAssignment; + + internal void ExecuteOnGetTaskToTeamAssignment(TaskToTeamAssignmentApi.GetTaskToTeamAssignmentApiResponse apiResponse) + { + OnGetTaskToTeamAssignment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTaskToTeamAssignment(Exception exception) + { + OnErrorGetTaskToTeamAssignment?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class TaskToTeamAssignmentApi : ITaskToTeamAssignmentApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public TaskToTeamAssignmentApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public TaskToTeamAssignmentApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TaskToTeamAssignmentApiEvents taskToTeamAssignmentApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = taskToTeamAssignmentApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateTaskToTeamAssignment(ref string taskId, ref string teamId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateCreateTaskToTeamAssignment(string taskId, string teamId) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (teamId == null) + throw new ArgumentNullException(nameof(teamId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterCreateTaskToTeamAssignmentDefaultImplementation(ICreateTaskToTeamAssignmentApiResponse apiResponseLocalVar, string taskId, string teamId) + { + bool suppressDefaultLog = false; + AfterCreateTaskToTeamAssignment(ref suppressDefaultLog, apiResponseLocalVar, taskId, teamId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterCreateTaskToTeamAssignment(ref bool suppressDefaultLog, ICreateTaskToTeamAssignmentApiResponse apiResponseLocalVar, string taskId, string teamId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorCreateTaskToTeamAssignmentDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string teamId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateTaskToTeamAssignment(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, teamId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateTaskToTeamAssignment(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string teamId); + + /// + /// Create a Task to Team Assignment Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + /// + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTaskToTeamAssignmentOrDefaultAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateTaskToTeamAssignmentAsync(taskId, teamId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Task to Team Assignment Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTaskToTeamAssignmentAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateTaskToTeamAssignment(taskId, teamId); + + FormatCreateTaskToTeamAssignment(ref taskId, ref teamId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/teams/{team_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/teams/{team_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bteam_id%7D", Uri.EscapeDataString(teamId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateTaskToTeamAssignmentApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/teams/{team_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateTaskToTeamAssignmentDefaultImplementation(apiResponseLocalVar, taskId, teamId); + + Events.ExecuteOnCreateTaskToTeamAssignment(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateTaskToTeamAssignmentDefaultImplementation(e, "/tasks/{task_id}/teams/{team_id}", uriBuilderLocalVar.Path, taskId, teamId); + Events.ExecuteOnErrorCreateTaskToTeamAssignment(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateTaskToTeamAssignmentApiResponse : Timr.Api.Client.ApiResponse, ICreateTaskToTeamAssignmentApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTaskToTeamAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTaskToTeamAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TaskToTeamAssignment? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TaskToTeamAssignment? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.TaskToTeamAssignment? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.TaskToTeamAssignment? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatDeleteTaskToTeamAssignment(ref string taskId, ref string teamId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateDeleteTaskToTeamAssignment(string taskId, string teamId) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (teamId == null) + throw new ArgumentNullException(nameof(teamId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterDeleteTaskToTeamAssignmentDefaultImplementation(IDeleteTaskToTeamAssignmentApiResponse apiResponseLocalVar, string taskId, string teamId) + { + bool suppressDefaultLog = false; + AfterDeleteTaskToTeamAssignment(ref suppressDefaultLog, apiResponseLocalVar, taskId, teamId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterDeleteTaskToTeamAssignment(ref bool suppressDefaultLog, IDeleteTaskToTeamAssignmentApiResponse apiResponseLocalVar, string taskId, string teamId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorDeleteTaskToTeamAssignmentDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string teamId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteTaskToTeamAssignment(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, teamId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteTaskToTeamAssignment(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string teamId); + + /// + /// Delete a Task to Team Assignment Removes the Team's assignment to the Task. + /// + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTaskToTeamAssignmentOrDefaultAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteTaskToTeamAssignmentAsync(taskId, teamId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Task to Team Assignment Removes the Team's assignment to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTaskToTeamAssignmentAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteTaskToTeamAssignment(taskId, teamId); + + FormatDeleteTaskToTeamAssignment(ref taskId, ref teamId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/teams/{team_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/teams/{team_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bteam_id%7D", Uri.EscapeDataString(teamId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteTaskToTeamAssignmentApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/teams/{team_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteTaskToTeamAssignmentDefaultImplementation(apiResponseLocalVar, taskId, teamId); + + Events.ExecuteOnDeleteTaskToTeamAssignment(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteTaskToTeamAssignmentDefaultImplementation(e, "/tasks/{task_id}/teams/{team_id}", uriBuilderLocalVar.Path, taskId, teamId); + Events.ExecuteOnErrorDeleteTaskToTeamAssignment(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteTaskToTeamAssignmentApiResponse : Timr.Api.Client.ApiResponse, IDeleteTaskToTeamAssignmentApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTaskToTeamAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTaskToTeamAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchTaskToTeamAssignments(ref string taskId, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchTaskToTeamAssignments(string taskId, Option pageToken) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchTaskToTeamAssignmentsDefaultImplementation(IFetchTaskToTeamAssignmentsApiResponse apiResponseLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchTaskToTeamAssignments(ref suppressDefaultLog, apiResponseLocalVar, taskId, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchTaskToTeamAssignments(ref bool suppressDefaultLog, IFetchTaskToTeamAssignmentsApiResponse apiResponseLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchTaskToTeamAssignmentsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchTaskToTeamAssignments(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchTaskToTeamAssignments(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Task to Team Assignments Lists the Teams assigned to the Task. + /// + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTaskToTeamAssignmentsOrDefaultAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchTaskToTeamAssignmentsAsync(taskId, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Task to Team Assignments Lists the Teams assigned to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTaskToTeamAssignmentsAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchTaskToTeamAssignments(taskId, pageToken); + + FormatFetchTaskToTeamAssignments(ref taskId, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/teams" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/teams"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchTaskToTeamAssignmentsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/teams", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchTaskToTeamAssignmentsDefaultImplementation(apiResponseLocalVar, taskId, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchTaskToTeamAssignments(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchTaskToTeamAssignmentsDefaultImplementation(e, "/tasks/{task_id}/teams", uriBuilderLocalVar.Path, taskId, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchTaskToTeamAssignments(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchTaskToTeamAssignmentsApiResponse : Timr.Api.Client.ApiResponse, IFetchTaskToTeamAssignmentsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTaskToTeamAssignmentsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTaskToTeamAssignmentsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TaskToTeamAssignmentsPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TaskToTeamAssignmentsPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetTaskToTeamAssignment(ref string taskId, ref string teamId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateGetTaskToTeamAssignment(string taskId, string teamId) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (teamId == null) + throw new ArgumentNullException(nameof(teamId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterGetTaskToTeamAssignmentDefaultImplementation(IGetTaskToTeamAssignmentApiResponse apiResponseLocalVar, string taskId, string teamId) + { + bool suppressDefaultLog = false; + AfterGetTaskToTeamAssignment(ref suppressDefaultLog, apiResponseLocalVar, taskId, teamId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterGetTaskToTeamAssignment(ref bool suppressDefaultLog, IGetTaskToTeamAssignmentApiResponse apiResponseLocalVar, string taskId, string teamId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorGetTaskToTeamAssignmentDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string teamId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetTaskToTeamAssignment(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, teamId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorGetTaskToTeamAssignment(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string teamId); + + /// + /// Get a Task to Team Assignment Returns the assignment of a single Team to the Task. + /// + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTaskToTeamAssignmentOrDefaultAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetTaskToTeamAssignmentAsync(taskId, teamId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Task to Team Assignment Returns the assignment of a single Team to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTaskToTeamAssignmentAsync(string taskId, string teamId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetTaskToTeamAssignment(taskId, teamId); + + FormatGetTaskToTeamAssignment(ref taskId, ref teamId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/teams/{team_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/teams/{team_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bteam_id%7D", Uri.EscapeDataString(teamId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetTaskToTeamAssignmentApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/teams/{team_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetTaskToTeamAssignmentDefaultImplementation(apiResponseLocalVar, taskId, teamId); + + Events.ExecuteOnGetTaskToTeamAssignment(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetTaskToTeamAssignmentDefaultImplementation(e, "/tasks/{task_id}/teams/{team_id}", uriBuilderLocalVar.Path, taskId, teamId); + Events.ExecuteOnErrorGetTaskToTeamAssignment(e); + throw; + } + } + + /// + /// The + /// + public partial class GetTaskToTeamAssignmentApiResponse : Timr.Api.Client.ApiResponse, IGetTaskToTeamAssignmentApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTaskToTeamAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTaskToTeamAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TaskToTeamAssignment? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TaskToTeamAssignment? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/TaskToUserAssignmentApi.cs b/sdk/dotnet/Timr.Api/Api/TaskToUserAssignmentApi.cs new file mode 100644 index 0000000..0e7a9c6 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/TaskToUserAssignmentApi.cs @@ -0,0 +1,1922 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface ITaskToUserAssignmentApi : IApi + { + /// + /// The class containing the events + /// + TaskToUserAssignmentApiEvents Events { get; } + + /// + /// Delete a Task to User Assignment + /// + /// + /// Removes the User's assignment to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteTaskToUserAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Task to User Assignment + /// + /// + /// Removes the User's assignment to the Task. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteTaskToUserAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Task to User Assignments + /// + /// + /// Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchTaskToUserAssignmentsAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Task to User Assignments + /// + /// + /// Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + /// + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchTaskToUserAssignmentsOrDefaultAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Task to User Assignment + /// + /// + /// Returns the assignment of a single User to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task GetTaskToUserAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Task to User Assignment + /// + /// + /// Returns the assignment of a single User to the Task. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task GetTaskToUserAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create or update a Task to User Assignment + /// + /// + /// Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Task to User Assignment entity + /// Cancellation Token to cancel the request. + /// <> + Task UpsertTaskToUserAssignmentAsync(string taskId, string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create or update a Task to User Assignment + /// + /// + /// Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + /// + /// ID of the Task. + /// ID of the User. + /// Task to User Assignment entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpsertTaskToUserAssignmentOrDefaultAsync(string taskId, string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface IDeleteTaskToUserAssignmentApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchTaskToUserAssignmentsApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IGetTaskToUserAssignmentApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IUpsertTaskToUserAssignmentApiResponse : Timr.Api.Client.IApiResponse, IOk, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class TaskToUserAssignmentApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteTaskToUserAssignment; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteTaskToUserAssignment; + + internal void ExecuteOnDeleteTaskToUserAssignment(TaskToUserAssignmentApi.DeleteTaskToUserAssignmentApiResponse apiResponse) + { + OnDeleteTaskToUserAssignment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteTaskToUserAssignment(Exception exception) + { + OnErrorDeleteTaskToUserAssignment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchTaskToUserAssignments; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchTaskToUserAssignments; + + internal void ExecuteOnFetchTaskToUserAssignments(TaskToUserAssignmentApi.FetchTaskToUserAssignmentsApiResponse apiResponse) + { + OnFetchTaskToUserAssignments?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchTaskToUserAssignments(Exception exception) + { + OnErrorFetchTaskToUserAssignments?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetTaskToUserAssignment; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetTaskToUserAssignment; + + internal void ExecuteOnGetTaskToUserAssignment(TaskToUserAssignmentApi.GetTaskToUserAssignmentApiResponse apiResponse) + { + OnGetTaskToUserAssignment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTaskToUserAssignment(Exception exception) + { + OnErrorGetTaskToUserAssignment?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpsertTaskToUserAssignment; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpsertTaskToUserAssignment; + + internal void ExecuteOnUpsertTaskToUserAssignment(TaskToUserAssignmentApi.UpsertTaskToUserAssignmentApiResponse apiResponse) + { + OnUpsertTaskToUserAssignment?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpsertTaskToUserAssignment(Exception exception) + { + OnErrorUpsertTaskToUserAssignment?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class TaskToUserAssignmentApi : ITaskToUserAssignmentApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public TaskToUserAssignmentApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public TaskToUserAssignmentApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TaskToUserAssignmentApiEvents taskToUserAssignmentApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = taskToUserAssignmentApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatDeleteTaskToUserAssignment(ref string taskId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateDeleteTaskToUserAssignment(string taskId, string userId) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterDeleteTaskToUserAssignmentDefaultImplementation(IDeleteTaskToUserAssignmentApiResponse apiResponseLocalVar, string taskId, string userId) + { + bool suppressDefaultLog = false; + AfterDeleteTaskToUserAssignment(ref suppressDefaultLog, apiResponseLocalVar, taskId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterDeleteTaskToUserAssignment(ref bool suppressDefaultLog, IDeleteTaskToUserAssignmentApiResponse apiResponseLocalVar, string taskId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorDeleteTaskToUserAssignmentDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteTaskToUserAssignment(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteTaskToUserAssignment(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId); + + /// + /// Delete a Task to User Assignment Removes the User's assignment to the Task. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTaskToUserAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteTaskToUserAssignmentAsync(taskId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Task to User Assignment Removes the User's assignment to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTaskToUserAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteTaskToUserAssignment(taskId, userId); + + FormatDeleteTaskToUserAssignment(ref taskId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/users/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/users/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteTaskToUserAssignmentApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/users/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteTaskToUserAssignmentDefaultImplementation(apiResponseLocalVar, taskId, userId); + + Events.ExecuteOnDeleteTaskToUserAssignment(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteTaskToUserAssignmentDefaultImplementation(e, "/tasks/{task_id}/users/{user_id}", uriBuilderLocalVar.Path, taskId, userId); + Events.ExecuteOnErrorDeleteTaskToUserAssignment(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteTaskToUserAssignmentApiResponse : Timr.Api.Client.ApiResponse, IDeleteTaskToUserAssignmentApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTaskToUserAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTaskToUserAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchTaskToUserAssignments(ref string taskId, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchTaskToUserAssignments(string taskId, Option pageToken) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchTaskToUserAssignmentsDefaultImplementation(IFetchTaskToUserAssignmentsApiResponse apiResponseLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchTaskToUserAssignments(ref suppressDefaultLog, apiResponseLocalVar, taskId, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchTaskToUserAssignments(ref bool suppressDefaultLog, IFetchTaskToUserAssignmentsApiResponse apiResponseLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchTaskToUserAssignmentsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchTaskToUserAssignments(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchTaskToUserAssignments(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Task to User Assignments Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + /// + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTaskToUserAssignmentsOrDefaultAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchTaskToUserAssignmentsAsync(taskId, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Task to User Assignments Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTaskToUserAssignmentsAsync(string taskId, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchTaskToUserAssignments(taskId, pageToken); + + FormatFetchTaskToUserAssignments(ref taskId, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/users" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/users"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchTaskToUserAssignmentsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/users", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchTaskToUserAssignmentsDefaultImplementation(apiResponseLocalVar, taskId, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchTaskToUserAssignments(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchTaskToUserAssignmentsDefaultImplementation(e, "/tasks/{task_id}/users", uriBuilderLocalVar.Path, taskId, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchTaskToUserAssignments(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchTaskToUserAssignmentsApiResponse : Timr.Api.Client.ApiResponse, IFetchTaskToUserAssignmentsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTaskToUserAssignmentsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTaskToUserAssignmentsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TaskToUserAssignmentsPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TaskToUserAssignmentsPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetTaskToUserAssignment(ref string taskId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateGetTaskToUserAssignment(string taskId, string userId) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterGetTaskToUserAssignmentDefaultImplementation(IGetTaskToUserAssignmentApiResponse apiResponseLocalVar, string taskId, string userId) + { + bool suppressDefaultLog = false; + AfterGetTaskToUserAssignment(ref suppressDefaultLog, apiResponseLocalVar, taskId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterGetTaskToUserAssignment(ref bool suppressDefaultLog, IGetTaskToUserAssignmentApiResponse apiResponseLocalVar, string taskId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorGetTaskToUserAssignmentDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetTaskToUserAssignment(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorGetTaskToUserAssignment(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId); + + /// + /// Get a Task to User Assignment Returns the assignment of a single User to the Task. + /// + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTaskToUserAssignmentOrDefaultAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetTaskToUserAssignmentAsync(taskId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Task to User Assignment Returns the assignment of a single User to the Task. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTaskToUserAssignmentAsync(string taskId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetTaskToUserAssignment(taskId, userId); + + FormatGetTaskToUserAssignment(ref taskId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/users/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/users/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetTaskToUserAssignmentApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/users/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetTaskToUserAssignmentDefaultImplementation(apiResponseLocalVar, taskId, userId); + + Events.ExecuteOnGetTaskToUserAssignment(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetTaskToUserAssignmentDefaultImplementation(e, "/tasks/{task_id}/users/{user_id}", uriBuilderLocalVar.Path, taskId, userId); + Events.ExecuteOnErrorGetTaskToUserAssignment(e); + throw; + } + } + + /// + /// The + /// + public partial class GetTaskToUserAssignmentApiResponse : Timr.Api.Client.ApiResponse, IGetTaskToUserAssignmentApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTaskToUserAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTaskToUserAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TaskToUserAssignment? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TaskToUserAssignment? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpsertTaskToUserAssignment(ref string taskId, ref string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + private void ValidateUpsertTaskToUserAssignment(string taskId, string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert) + { + if (taskId == null) + throw new ArgumentNullException(nameof(taskId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + + if (taskToUserAssignmentUpsert == null) + throw new ArgumentNullException(nameof(taskToUserAssignmentUpsert)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + private void AfterUpsertTaskToUserAssignmentDefaultImplementation(IUpsertTaskToUserAssignmentApiResponse apiResponseLocalVar, string taskId, string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert) + { + bool suppressDefaultLog = false; + AfterUpsertTaskToUserAssignment(ref suppressDefaultLog, apiResponseLocalVar, taskId, userId, taskToUserAssignmentUpsert); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + partial void AfterUpsertTaskToUserAssignment(ref bool suppressDefaultLog, IUpsertTaskToUserAssignmentApiResponse apiResponseLocalVar, string taskId, string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + private void OnErrorUpsertTaskToUserAssignmentDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpsertTaskToUserAssignment(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, taskId, userId, taskToUserAssignmentUpsert); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpsertTaskToUserAssignment(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string taskId, string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert); + + /// + /// Create or update a Task to User Assignment Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + /// + /// ID of the Task. + /// ID of the User. + /// Task to User Assignment entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpsertTaskToUserAssignmentOrDefaultAsync(string taskId, string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpsertTaskToUserAssignmentAsync(taskId, userId, taskToUserAssignmentUpsert, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create or update a Task to User Assignment Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// ID of the User. + /// Task to User Assignment entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpsertTaskToUserAssignmentAsync(string taskId, string userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpsertTaskToUserAssignment(taskId, userId, taskToUserAssignmentUpsert); + + FormatUpsertTaskToUserAssignment(ref taskId, ref userId, taskToUserAssignmentUpsert); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{task_id}/users/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{task_id}/users/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Btask_id%7D", Uri.EscapeDataString(taskId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + httpRequestMessageLocalVar.Content = (taskToUserAssignmentUpsert as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(taskToUserAssignmentUpsert, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpsertTaskToUserAssignmentApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{task_id}/users/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpsertTaskToUserAssignmentDefaultImplementation(apiResponseLocalVar, taskId, userId, taskToUserAssignmentUpsert); + + Events.ExecuteOnUpsertTaskToUserAssignment(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpsertTaskToUserAssignmentDefaultImplementation(e, "/tasks/{task_id}/users/{user_id}", uriBuilderLocalVar.Path, taskId, userId, taskToUserAssignmentUpsert); + Events.ExecuteOnErrorUpsertTaskToUserAssignment(e); + throw; + } + } + + /// + /// The + /// + public partial class UpsertTaskToUserAssignmentApiResponse : Timr.Api.Client.ApiResponse, IUpsertTaskToUserAssignmentApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpsertTaskToUserAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpsertTaskToUserAssignmentApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TaskToUserAssignment? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TaskToUserAssignment? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.TaskToUserAssignment? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.TaskToUserAssignment? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/TeamApi.cs b/sdk/dotnet/Timr.Api/Api/TeamApi.cs new file mode 100644 index 0000000..33718e6 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/TeamApi.cs @@ -0,0 +1,5860 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface ITeamApi : IApi + { + /// + /// The class containing the events + /// + TeamApiEvents Events { get; } + + /// + /// Add a Team Leader + /// + /// + /// Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task AddTeamLeaderAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Add a Team Leader + /// + /// + /// Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task AddTeamLeaderOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Add a Team Member + /// + /// + /// Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task AddTeamMemberAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Add a Team Member + /// + /// + /// Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task AddTeamMemberOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Team + /// + /// + /// Creates a Team from the data in the request body. + /// + /// Thrown when fails to make API call + /// Team entity + /// Cancellation Token to cancel the request. + /// <> + Task CreateTeamAsync(TeamCreate teamCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Team + /// + /// + /// Creates a Team from the data in the request body. + /// + /// Team entity + /// Cancellation Token to cancel the request. + /// <?> + Task CreateTeamOrDefaultAsync(TeamCreate teamCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Team + /// + /// + /// Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteTeamAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Team + /// + /// + /// Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + /// + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteTeamOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Team Leaders + /// + /// + /// Lists the Users who lead the Team. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchTeamLeadersAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Team Leaders + /// + /// + /// Lists the Users who lead the Team. + /// + /// ID of the Team. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchTeamLeadersOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Team Members + /// + /// + /// Lists the Users who are members of the Team. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchTeamMembersAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Team Members + /// + /// + /// Lists the Users who are members of the Team. + /// + /// ID of the Team. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchTeamMembersOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Teams + /// + /// + /// Lists the Teams the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchTeamsAsync(Option name = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Teams + /// + /// + /// Lists the Teams the authenticated user or API token can access. + /// + /// Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchTeamsOrDefaultAsync(Option name = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Team + /// + /// + /// Returns a single Team by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + Task GetTeamAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Team + /// + /// + /// Returns a single Team by its ID. + /// + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <?> + Task GetTeamOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Team Leader + /// + /// + /// Returns the leadership of a single User in the Team. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task GetTeamLeaderAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Team Leader + /// + /// + /// Returns the leadership of a single User in the Team. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task GetTeamLeaderOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Team Member + /// + /// + /// Returns the membership of a single User in the Team. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task GetTeamMemberAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Team Member + /// + /// + /// Returns the membership of a single User in the Team. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task GetTeamMemberOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Remove a Team Leader + /// + /// + /// Removes the User's leadership of the Team. The User itself is not deleted. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task RemoveTeamLeaderAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Remove a Team Leader + /// + /// + /// Removes the User's leadership of the Team. The User itself is not deleted. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task RemoveTeamLeaderOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Remove a Team Member + /// + /// + /// Removes the User's membership in the Team. The User itself is not deleted. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task RemoveTeamMemberAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Remove a Team Member + /// + /// + /// Removes the User's membership in the Team. The User itself is not deleted. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task RemoveTeamMemberOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Team + /// + /// + /// Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Team entity + /// Cancellation Token to cancel the request. + /// <> + Task UpdateTeamAsync(string id, TeamUpdate teamUpdate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Team + /// + /// + /// Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Team. + /// Team entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpdateTeamOrDefaultAsync(string id, TeamUpdate teamUpdate, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface IAddTeamLeaderApiResponse : Timr.Api.Client.IApiResponse, IOk, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IAddTeamMemberApiResponse : Timr.Api.Client.IApiResponse, IOk, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface ICreateTeamApiResponse : Timr.Api.Client.IApiResponse, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IDeleteTeamApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchTeamLeadersApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IFetchTeamMembersApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IFetchTeamsApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetTeamApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IGetTeamLeaderApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IGetTeamMemberApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IRemoveTeamLeaderApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IRemoveTeamMemberApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IUpdateTeamApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest, IForbidden, INotFound, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class TeamApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnAddTeamLeader; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorAddTeamLeader; + + internal void ExecuteOnAddTeamLeader(TeamApi.AddTeamLeaderApiResponse apiResponse) + { + OnAddTeamLeader?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAddTeamLeader(Exception exception) + { + OnErrorAddTeamLeader?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnAddTeamMember; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorAddTeamMember; + + internal void ExecuteOnAddTeamMember(TeamApi.AddTeamMemberApiResponse apiResponse) + { + OnAddTeamMember?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorAddTeamMember(Exception exception) + { + OnErrorAddTeamMember?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateTeam; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateTeam; + + internal void ExecuteOnCreateTeam(TeamApi.CreateTeamApiResponse apiResponse) + { + OnCreateTeam?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTeam(Exception exception) + { + OnErrorCreateTeam?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteTeam; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteTeam; + + internal void ExecuteOnDeleteTeam(TeamApi.DeleteTeamApiResponse apiResponse) + { + OnDeleteTeam?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteTeam(Exception exception) + { + OnErrorDeleteTeam?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchTeamLeaders; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchTeamLeaders; + + internal void ExecuteOnFetchTeamLeaders(TeamApi.FetchTeamLeadersApiResponse apiResponse) + { + OnFetchTeamLeaders?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchTeamLeaders(Exception exception) + { + OnErrorFetchTeamLeaders?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchTeamMembers; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchTeamMembers; + + internal void ExecuteOnFetchTeamMembers(TeamApi.FetchTeamMembersApiResponse apiResponse) + { + OnFetchTeamMembers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchTeamMembers(Exception exception) + { + OnErrorFetchTeamMembers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchTeams; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchTeams; + + internal void ExecuteOnFetchTeams(TeamApi.FetchTeamsApiResponse apiResponse) + { + OnFetchTeams?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchTeams(Exception exception) + { + OnErrorFetchTeams?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetTeam; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetTeam; + + internal void ExecuteOnGetTeam(TeamApi.GetTeamApiResponse apiResponse) + { + OnGetTeam?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTeam(Exception exception) + { + OnErrorGetTeam?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetTeamLeader; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetTeamLeader; + + internal void ExecuteOnGetTeamLeader(TeamApi.GetTeamLeaderApiResponse apiResponse) + { + OnGetTeamLeader?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTeamLeader(Exception exception) + { + OnErrorGetTeamLeader?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetTeamMember; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetTeamMember; + + internal void ExecuteOnGetTeamMember(TeamApi.GetTeamMemberApiResponse apiResponse) + { + OnGetTeamMember?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTeamMember(Exception exception) + { + OnErrorGetTeamMember?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnRemoveTeamLeader; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorRemoveTeamLeader; + + internal void ExecuteOnRemoveTeamLeader(TeamApi.RemoveTeamLeaderApiResponse apiResponse) + { + OnRemoveTeamLeader?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRemoveTeamLeader(Exception exception) + { + OnErrorRemoveTeamLeader?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnRemoveTeamMember; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorRemoveTeamMember; + + internal void ExecuteOnRemoveTeamMember(TeamApi.RemoveTeamMemberApiResponse apiResponse) + { + OnRemoveTeamMember?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorRemoveTeamMember(Exception exception) + { + OnErrorRemoveTeamMember?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpdateTeam; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateTeam; + + internal void ExecuteOnUpdateTeam(TeamApi.UpdateTeamApiResponse apiResponse) + { + OnUpdateTeam?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTeam(Exception exception) + { + OnErrorUpdateTeam?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class TeamApi : ITeamApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public TeamApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public TeamApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TeamApiEvents teamApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = teamApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatAddTeamLeader(ref string teamId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateAddTeamLeader(string teamId, string userId) + { + if (teamId == null) + throw new ArgumentNullException(nameof(teamId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterAddTeamLeaderDefaultImplementation(IAddTeamLeaderApiResponse apiResponseLocalVar, string teamId, string userId) + { + bool suppressDefaultLog = false; + AfterAddTeamLeader(ref suppressDefaultLog, apiResponseLocalVar, teamId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterAddTeamLeader(ref bool suppressDefaultLog, IAddTeamLeaderApiResponse apiResponseLocalVar, string teamId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorAddTeamLeaderDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorAddTeamLeader(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, teamId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorAddTeamLeader(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId); + + /// + /// Add a Team Leader Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task AddTeamLeaderOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await AddTeamLeaderAsync(teamId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Add a Team Leader Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task AddTeamLeaderAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateAddTeamLeader(teamId, userId); + + FormatAddTeamLeader(ref teamId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{team_id}/leaders/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{team_id}/leaders/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bteam_id%7D", Uri.EscapeDataString(teamId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + AddTeamLeaderApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{team_id}/leaders/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterAddTeamLeaderDefaultImplementation(apiResponseLocalVar, teamId, userId); + + Events.ExecuteOnAddTeamLeader(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorAddTeamLeaderDefaultImplementation(e, "/teams/{team_id}/leaders/{user_id}", uriBuilderLocalVar.Path, teamId, userId); + Events.ExecuteOnErrorAddTeamLeader(e); + throw; + } + } + + /// + /// The + /// + public partial class AddTeamLeaderApiResponse : Timr.Api.Client.ApiResponse, IAddTeamLeaderApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public AddTeamLeaderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public AddTeamLeaderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.UserPartial? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.UserPartial? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.UserPartial? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.UserPartial? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatAddTeamMember(ref string teamId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateAddTeamMember(string teamId, string userId) + { + if (teamId == null) + throw new ArgumentNullException(nameof(teamId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterAddTeamMemberDefaultImplementation(IAddTeamMemberApiResponse apiResponseLocalVar, string teamId, string userId) + { + bool suppressDefaultLog = false; + AfterAddTeamMember(ref suppressDefaultLog, apiResponseLocalVar, teamId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterAddTeamMember(ref bool suppressDefaultLog, IAddTeamMemberApiResponse apiResponseLocalVar, string teamId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorAddTeamMemberDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorAddTeamMember(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, teamId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorAddTeamMember(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId); + + /// + /// Add a Team Member Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task AddTeamMemberOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await AddTeamMemberAsync(teamId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Add a Team Member Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task AddTeamMemberAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateAddTeamMember(teamId, userId); + + FormatAddTeamMember(ref teamId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{team_id}/members/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{team_id}/members/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bteam_id%7D", Uri.EscapeDataString(teamId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + AddTeamMemberApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{team_id}/members/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterAddTeamMemberDefaultImplementation(apiResponseLocalVar, teamId, userId); + + Events.ExecuteOnAddTeamMember(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorAddTeamMemberDefaultImplementation(e, "/teams/{team_id}/members/{user_id}", uriBuilderLocalVar.Path, teamId, userId); + Events.ExecuteOnErrorAddTeamMember(e); + throw; + } + } + + /// + /// The + /// + public partial class AddTeamMemberApiResponse : Timr.Api.Client.ApiResponse, IAddTeamMemberApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public AddTeamMemberApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public AddTeamMemberApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.UserPartial? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.UserPartial? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.UserPartial? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.UserPartial? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatCreateTeam(TeamCreate teamCreate); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateTeam(TeamCreate teamCreate) + { + if (teamCreate == null) + throw new ArgumentNullException(nameof(teamCreate)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateTeamDefaultImplementation(ICreateTeamApiResponse apiResponseLocalVar, TeamCreate teamCreate) + { + bool suppressDefaultLog = false; + AfterCreateTeam(ref suppressDefaultLog, apiResponseLocalVar, teamCreate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateTeam(ref bool suppressDefaultLog, ICreateTeamApiResponse apiResponseLocalVar, TeamCreate teamCreate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateTeamDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, TeamCreate teamCreate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateTeam(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, teamCreate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateTeam(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, TeamCreate teamCreate); + + /// + /// Create a Team Creates a Team from the data in the request body. + /// + /// Team entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTeamOrDefaultAsync(TeamCreate teamCreate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateTeamAsync(teamCreate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Team Creates a Team from the data in the request body. + /// + /// Thrown when fails to make API call + /// Team entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTeamAsync(TeamCreate teamCreate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateTeam(teamCreate); + + FormatCreateTeam(teamCreate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams"); + + httpRequestMessageLocalVar.Content = (teamCreate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(teamCreate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateTeamApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateTeamDefaultImplementation(apiResponseLocalVar, teamCreate); + + Events.ExecuteOnCreateTeam(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateTeamDefaultImplementation(e, "/teams", uriBuilderLocalVar.Path, teamCreate); + Events.ExecuteOnErrorCreateTeam(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateTeamApiResponse : Timr.Api.Client.ApiResponse, ICreateTeamApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTeamApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTeamApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.Team? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.Team? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatDeleteTeam(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteTeam(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteTeamDefaultImplementation(IDeleteTeamApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterDeleteTeam(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteTeam(ref bool suppressDefaultLog, IDeleteTeamApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteTeamDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteTeam(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteTeam(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Delete a Team Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + /// + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTeamOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteTeamAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Team Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTeamAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteTeam(id); + + FormatDeleteTeam(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteTeamApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteTeamDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnDeleteTeam(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteTeamDefaultImplementation(e, "/teams/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorDeleteTeam(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteTeamApiResponse : Timr.Api.Client.ApiResponse, IDeleteTeamApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTeamApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTeamApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchTeamLeaders(ref string id, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchTeamLeaders(string id, Option pageToken) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchTeamLeadersDefaultImplementation(IFetchTeamLeadersApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchTeamLeaders(ref suppressDefaultLog, apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchTeamLeaders(ref bool suppressDefaultLog, IFetchTeamLeadersApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchTeamLeadersDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchTeamLeaders(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchTeamLeaders(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Team Leaders Lists the Users who lead the Team. + /// + /// ID of the Team. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTeamLeadersOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchTeamLeadersAsync(id, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Team Leaders Lists the Users who lead the Team. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTeamLeadersAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchTeamLeaders(id, pageToken); + + FormatFetchTeamLeaders(ref id, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{id}/leaders" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{id}/leaders"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchTeamLeadersApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{id}/leaders", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchTeamLeadersDefaultImplementation(apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchTeamLeaders(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchTeamLeadersDefaultImplementation(e, "/teams/{id}/leaders", uriBuilderLocalVar.Path, id, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchTeamLeaders(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchTeamLeadersApiResponse : Timr.Api.Client.ApiResponse, IFetchTeamLeadersApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTeamLeadersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTeamLeadersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.UsersPartialPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.UsersPartialPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchTeamMembers(ref string id, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchTeamMembers(string id, Option pageToken) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchTeamMembersDefaultImplementation(IFetchTeamMembersApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchTeamMembers(ref suppressDefaultLog, apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchTeamMembers(ref bool suppressDefaultLog, IFetchTeamMembersApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchTeamMembersDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchTeamMembers(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchTeamMembers(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Team Members Lists the Users who are members of the Team. + /// + /// ID of the Team. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTeamMembersOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchTeamMembersAsync(id, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Team Members Lists the Users who are members of the Team. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTeamMembersAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchTeamMembers(id, pageToken); + + FormatFetchTeamMembers(ref id, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{id}/members" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{id}/members"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchTeamMembersApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{id}/members", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchTeamMembersDefaultImplementation(apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchTeamMembers(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchTeamMembersDefaultImplementation(e, "/teams/{id}/members", uriBuilderLocalVar.Path, id, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchTeamMembers(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchTeamMembersApiResponse : Timr.Api.Client.ApiResponse, IFetchTeamMembersApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTeamMembersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTeamMembersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.UsersPartialPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.UsersPartialPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchTeams(ref Option name, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchTeams(Option name, Option pageToken) + { + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchTeamsDefaultImplementation(IFetchTeamsApiResponse apiResponseLocalVar, Option name, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchTeams(ref suppressDefaultLog, apiResponseLocalVar, name, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchTeams(ref bool suppressDefaultLog, IFetchTeamsApiResponse apiResponseLocalVar, Option name, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchTeamsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option name, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchTeams(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, name, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchTeams(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option name, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Teams Lists the Teams the authenticated user or API token can access. + /// + /// Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTeamsOrDefaultAsync(Option name = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchTeamsAsync(name, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Teams Lists the Teams the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchTeamsAsync(Option name = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchTeams(name, pageToken); + + FormatFetchTeams(ref name, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (name.IsSet) + parseQueryStringLocalVar["name"] = ClientUtils.ParameterToString(name.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchTeamsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchTeamsDefaultImplementation(apiResponseLocalVar, name, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchTeams(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchTeamsDefaultImplementation(e, "/teams", uriBuilderLocalVar.Path, name, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchTeams(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchTeamsApiResponse : Timr.Api.Client.ApiResponse, IFetchTeamsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTeamsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchTeamsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TeamsPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TeamsPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetTeam(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetTeam(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetTeamDefaultImplementation(IGetTeamApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetTeam(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetTeam(ref bool suppressDefaultLog, IGetTeamApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetTeamDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetTeam(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetTeam(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Team Returns a single Team by its ID. + /// + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTeamOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetTeamAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Team Returns a single Team by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTeamAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetTeam(id); + + FormatGetTeam(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetTeamApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetTeamDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetTeam(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetTeamDefaultImplementation(e, "/teams/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetTeam(e); + throw; + } + } + + /// + /// The + /// + public partial class GetTeamApiResponse : Timr.Api.Client.ApiResponse, IGetTeamApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTeamApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTeamApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.Team? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.Team? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetTeamLeader(ref string teamId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateGetTeamLeader(string teamId, string userId) + { + if (teamId == null) + throw new ArgumentNullException(nameof(teamId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterGetTeamLeaderDefaultImplementation(IGetTeamLeaderApiResponse apiResponseLocalVar, string teamId, string userId) + { + bool suppressDefaultLog = false; + AfterGetTeamLeader(ref suppressDefaultLog, apiResponseLocalVar, teamId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterGetTeamLeader(ref bool suppressDefaultLog, IGetTeamLeaderApiResponse apiResponseLocalVar, string teamId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorGetTeamLeaderDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetTeamLeader(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, teamId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorGetTeamLeader(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId); + + /// + /// Get a Team Leader Returns the leadership of a single User in the Team. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTeamLeaderOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetTeamLeaderAsync(teamId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Team Leader Returns the leadership of a single User in the Team. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTeamLeaderAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetTeamLeader(teamId, userId); + + FormatGetTeamLeader(ref teamId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{team_id}/leaders/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{team_id}/leaders/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bteam_id%7D", Uri.EscapeDataString(teamId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetTeamLeaderApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{team_id}/leaders/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetTeamLeaderDefaultImplementation(apiResponseLocalVar, teamId, userId); + + Events.ExecuteOnGetTeamLeader(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetTeamLeaderDefaultImplementation(e, "/teams/{team_id}/leaders/{user_id}", uriBuilderLocalVar.Path, teamId, userId); + Events.ExecuteOnErrorGetTeamLeader(e); + throw; + } + } + + /// + /// The + /// + public partial class GetTeamLeaderApiResponse : Timr.Api.Client.ApiResponse, IGetTeamLeaderApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTeamLeaderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTeamLeaderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.UserPartial? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.UserPartial? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetTeamMember(ref string teamId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateGetTeamMember(string teamId, string userId) + { + if (teamId == null) + throw new ArgumentNullException(nameof(teamId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterGetTeamMemberDefaultImplementation(IGetTeamMemberApiResponse apiResponseLocalVar, string teamId, string userId) + { + bool suppressDefaultLog = false; + AfterGetTeamMember(ref suppressDefaultLog, apiResponseLocalVar, teamId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterGetTeamMember(ref bool suppressDefaultLog, IGetTeamMemberApiResponse apiResponseLocalVar, string teamId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorGetTeamMemberDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetTeamMember(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, teamId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorGetTeamMember(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId); + + /// + /// Get a Team Member Returns the membership of a single User in the Team. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTeamMemberOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetTeamMemberAsync(teamId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Team Member Returns the membership of a single User in the Team. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTeamMemberAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetTeamMember(teamId, userId); + + FormatGetTeamMember(ref teamId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{team_id}/members/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{team_id}/members/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bteam_id%7D", Uri.EscapeDataString(teamId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetTeamMemberApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{team_id}/members/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetTeamMemberDefaultImplementation(apiResponseLocalVar, teamId, userId); + + Events.ExecuteOnGetTeamMember(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetTeamMemberDefaultImplementation(e, "/teams/{team_id}/members/{user_id}", uriBuilderLocalVar.Path, teamId, userId); + Events.ExecuteOnErrorGetTeamMember(e); + throw; + } + } + + /// + /// The + /// + public partial class GetTeamMemberApiResponse : Timr.Api.Client.ApiResponse, IGetTeamMemberApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTeamMemberApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTeamMemberApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.UserPartial? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.UserPartial? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatRemoveTeamLeader(ref string teamId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateRemoveTeamLeader(string teamId, string userId) + { + if (teamId == null) + throw new ArgumentNullException(nameof(teamId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterRemoveTeamLeaderDefaultImplementation(IRemoveTeamLeaderApiResponse apiResponseLocalVar, string teamId, string userId) + { + bool suppressDefaultLog = false; + AfterRemoveTeamLeader(ref suppressDefaultLog, apiResponseLocalVar, teamId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterRemoveTeamLeader(ref bool suppressDefaultLog, IRemoveTeamLeaderApiResponse apiResponseLocalVar, string teamId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorRemoveTeamLeaderDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorRemoveTeamLeader(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, teamId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorRemoveTeamLeader(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId); + + /// + /// Remove a Team Leader Removes the User's leadership of the Team. The User itself is not deleted. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task RemoveTeamLeaderOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await RemoveTeamLeaderAsync(teamId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Remove a Team Leader Removes the User's leadership of the Team. The User itself is not deleted. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task RemoveTeamLeaderAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateRemoveTeamLeader(teamId, userId); + + FormatRemoveTeamLeader(ref teamId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{team_id}/leaders/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{team_id}/leaders/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bteam_id%7D", Uri.EscapeDataString(teamId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + RemoveTeamLeaderApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{team_id}/leaders/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterRemoveTeamLeaderDefaultImplementation(apiResponseLocalVar, teamId, userId); + + Events.ExecuteOnRemoveTeamLeader(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorRemoveTeamLeaderDefaultImplementation(e, "/teams/{team_id}/leaders/{user_id}", uriBuilderLocalVar.Path, teamId, userId); + Events.ExecuteOnErrorRemoveTeamLeader(e); + throw; + } + } + + /// + /// The + /// + public partial class RemoveTeamLeaderApiResponse : Timr.Api.Client.ApiResponse, IRemoveTeamLeaderApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public RemoveTeamLeaderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public RemoveTeamLeaderApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatRemoveTeamMember(ref string teamId, ref string userId); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateRemoveTeamMember(string teamId, string userId) + { + if (teamId == null) + throw new ArgumentNullException(nameof(teamId)); + + if (userId == null) + throw new ArgumentNullException(nameof(userId)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterRemoveTeamMemberDefaultImplementation(IRemoveTeamMemberApiResponse apiResponseLocalVar, string teamId, string userId) + { + bool suppressDefaultLog = false; + AfterRemoveTeamMember(ref suppressDefaultLog, apiResponseLocalVar, teamId, userId); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterRemoveTeamMember(ref bool suppressDefaultLog, IRemoveTeamMemberApiResponse apiResponseLocalVar, string teamId, string userId); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorRemoveTeamMemberDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId) + { + bool suppressDefaultLogLocalVar = false; + OnErrorRemoveTeamMember(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, teamId, userId); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorRemoveTeamMember(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string teamId, string userId); + + /// + /// Remove a Team Member Removes the User's membership in the Team. The User itself is not deleted. + /// + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task RemoveTeamMemberOrDefaultAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await RemoveTeamMemberAsync(teamId, userId, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Remove a Team Member Removes the User's membership in the Team. The User itself is not deleted. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task RemoveTeamMemberAsync(string teamId, string userId, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateRemoveTeamMember(teamId, userId); + + FormatRemoveTeamMember(ref teamId, ref userId); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{team_id}/members/{user_id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{team_id}/members/{user_id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bteam_id%7D", Uri.EscapeDataString(teamId.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Buser_id%7D", Uri.EscapeDataString(userId.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + RemoveTeamMemberApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{team_id}/members/{user_id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterRemoveTeamMemberDefaultImplementation(apiResponseLocalVar, teamId, userId); + + Events.ExecuteOnRemoveTeamMember(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorRemoveTeamMemberDefaultImplementation(e, "/teams/{team_id}/members/{user_id}", uriBuilderLocalVar.Path, teamId, userId); + Events.ExecuteOnErrorRemoveTeamMember(e); + throw; + } + } + + /// + /// The + /// + public partial class RemoveTeamMemberApiResponse : Timr.Api.Client.ApiResponse, IRemoveTeamMemberApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public RemoveTeamMemberApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public RemoveTeamMemberApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpdateTeam(ref string id, TeamUpdate teamUpdate); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateTeam(string id, TeamUpdate teamUpdate) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (teamUpdate == null) + throw new ArgumentNullException(nameof(teamUpdate)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateTeamDefaultImplementation(IUpdateTeamApiResponse apiResponseLocalVar, string id, TeamUpdate teamUpdate) + { + bool suppressDefaultLog = false; + AfterUpdateTeam(ref suppressDefaultLog, apiResponseLocalVar, id, teamUpdate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateTeam(ref bool suppressDefaultLog, IUpdateTeamApiResponse apiResponseLocalVar, string id, TeamUpdate teamUpdate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateTeamDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, TeamUpdate teamUpdate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpdateTeam(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, teamUpdate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateTeam(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, TeamUpdate teamUpdate); + + /// + /// Update a Team Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Team. + /// Team entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateTeamOrDefaultAsync(string id, TeamUpdate teamUpdate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateTeamAsync(id, teamUpdate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Update a Team Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Team. + /// Team entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateTeamAsync(string id, TeamUpdate teamUpdate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateTeam(id, teamUpdate); + + FormatUpdateTeam(ref id, teamUpdate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/teams/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/teams/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (teamUpdate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(teamUpdate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpdateTeamApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/teams/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpdateTeamDefaultImplementation(apiResponseLocalVar, id, teamUpdate); + + Events.ExecuteOnUpdateTeam(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateTeamDefaultImplementation(e, "/teams/{id}", uriBuilderLocalVar.Path, id, teamUpdate); + Events.ExecuteOnErrorUpdateTeam(e); + throw; + } + } + + /// + /// The + /// + public partial class UpdateTeamApiResponse : Timr.Api.Client.ApiResponse, IUpdateTeamApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateTeamApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateTeamApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.Team? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.Team? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/TimeAccountApi.cs b/sdk/dotnet/Timr.Api/Api/TimeAccountApi.cs new file mode 100644 index 0000000..72fee36 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/TimeAccountApi.cs @@ -0,0 +1,919 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface ITimeAccountApi : IApi + { + /// + /// The class containing the events + /// + TimeAccountApiEvents Events { get; } + + /// + /// Get a User's accounts + /// + /// + /// Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Day to return the balances for. + /// Cancellation Token to cancel the request. + /// <> + Task GetUserAccountsAsync(string id, DateOnly date, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a User's accounts + /// + /// + /// Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + /// + /// ID of the User. + /// Day to return the balances for. + /// Cancellation Token to cancel the request. + /// <?> + Task GetUserAccountsOrDefaultAsync(string id, DateOnly date, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a User's working time accounts + /// + /// + /// Returns the User's working time account balances as of the given day. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Day to return the balances for. + /// Cancellation Token to cancel the request. + /// <> + Task GetUserWorkingTimeAccountsAsync(string id, DateOnly date, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a User's working time accounts + /// + /// + /// Returns the User's working time account balances as of the given day. + /// + /// ID of the User. + /// Day to return the balances for. + /// Cancellation Token to cancel the request. + /// <?> + Task GetUserWorkingTimeAccountsOrDefaultAsync(string id, DateOnly date, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface IGetUserAccountsApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IGetUserWorkingTimeAccountsApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class TimeAccountApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetUserAccounts; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetUserAccounts; + + internal void ExecuteOnGetUserAccounts(TimeAccountApi.GetUserAccountsApiResponse apiResponse) + { + OnGetUserAccounts?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetUserAccounts(Exception exception) + { + OnErrorGetUserAccounts?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetUserWorkingTimeAccounts; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetUserWorkingTimeAccounts; + + internal void ExecuteOnGetUserWorkingTimeAccounts(TimeAccountApi.GetUserWorkingTimeAccountsApiResponse apiResponse) + { + OnGetUserWorkingTimeAccounts?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetUserWorkingTimeAccounts(Exception exception) + { + OnErrorGetUserWorkingTimeAccounts?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class TimeAccountApi : ITimeAccountApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public TimeAccountApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public TimeAccountApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TimeAccountApiEvents timeAccountApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = timeAccountApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatGetUserAccounts(ref string id, ref DateOnly date); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetUserAccounts(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterGetUserAccountsDefaultImplementation(IGetUserAccountsApiResponse apiResponseLocalVar, string id, DateOnly date) + { + bool suppressDefaultLog = false; + AfterGetUserAccounts(ref suppressDefaultLog, apiResponseLocalVar, id, date); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterGetUserAccounts(ref bool suppressDefaultLog, IGetUserAccountsApiResponse apiResponseLocalVar, string id, DateOnly date); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorGetUserAccountsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, DateOnly date) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetUserAccounts(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, date); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorGetUserAccounts(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, DateOnly date); + + /// + /// Get a User's accounts Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + /// + /// ID of the User. + /// Day to return the balances for. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetUserAccountsOrDefaultAsync(string id, DateOnly date, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetUserAccountsAsync(id, date, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a User's accounts Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Day to return the balances for. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetUserAccountsAsync(string id, DateOnly date, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetUserAccounts(id); + + FormatGetUserAccounts(ref id, ref date); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users/{id}/accounts/{date}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users/{id}/accounts/{date}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bdate%7D", Uri.EscapeDataString(date.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetUserAccountsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users/{id}/accounts/{date}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetUserAccountsDefaultImplementation(apiResponseLocalVar, id, date); + + Events.ExecuteOnGetUserAccounts(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetUserAccountsDefaultImplementation(e, "/users/{id}/accounts/{date}", uriBuilderLocalVar.Path, id, date); + Events.ExecuteOnErrorGetUserAccounts(e); + throw; + } + } + + /// + /// The + /// + public partial class GetUserAccountsApiResponse : Timr.Api.Client.ApiResponse, IGetUserAccountsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetUserAccountsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetUserAccountsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.Accounts? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.Accounts? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetUserWorkingTimeAccounts(ref string id, ref DateOnly date); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetUserWorkingTimeAccounts(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterGetUserWorkingTimeAccountsDefaultImplementation(IGetUserWorkingTimeAccountsApiResponse apiResponseLocalVar, string id, DateOnly date) + { + bool suppressDefaultLog = false; + AfterGetUserWorkingTimeAccounts(ref suppressDefaultLog, apiResponseLocalVar, id, date); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterGetUserWorkingTimeAccounts(ref bool suppressDefaultLog, IGetUserWorkingTimeAccountsApiResponse apiResponseLocalVar, string id, DateOnly date); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorGetUserWorkingTimeAccountsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, DateOnly date) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetUserWorkingTimeAccounts(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, date); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorGetUserWorkingTimeAccounts(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, DateOnly date); + + /// + /// Get a User's working time accounts Returns the User's working time account balances as of the given day. + /// + /// ID of the User. + /// Day to return the balances for. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetUserWorkingTimeAccountsOrDefaultAsync(string id, DateOnly date, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetUserWorkingTimeAccountsAsync(id, date, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a User's working time accounts Returns the User's working time account balances as of the given day. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Day to return the balances for. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetUserWorkingTimeAccountsAsync(string id, DateOnly date, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetUserWorkingTimeAccounts(id); + + FormatGetUserWorkingTimeAccounts(ref id, ref date); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users/{id}/working-time-accounts/{date}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users/{id}/working-time-accounts/{date}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bdate%7D", Uri.EscapeDataString(date.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetUserWorkingTimeAccountsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users/{id}/working-time-accounts/{date}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetUserWorkingTimeAccountsDefaultImplementation(apiResponseLocalVar, id, date); + + Events.ExecuteOnGetUserWorkingTimeAccounts(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetUserWorkingTimeAccountsDefaultImplementation(e, "/users/{id}/working-time-accounts/{date}", uriBuilderLocalVar.Path, id, date); + Events.ExecuteOnErrorGetUserWorkingTimeAccounts(e); + throw; + } + } + + /// + /// The + /// + public partial class GetUserWorkingTimeAccountsApiResponse : Timr.Api.Client.ApiResponse, IGetUserWorkingTimeAccountsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetUserWorkingTimeAccountsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetUserWorkingTimeAccountsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.Accounts? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.Accounts? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/TrackApi.cs b/sdk/dotnet/Timr.Api/Api/TrackApi.cs new file mode 100644 index 0000000..a0fedc0 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/TrackApi.cs @@ -0,0 +1,1944 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface ITrackApi : IApi + { + /// + /// The class containing the events + /// + TrackApiEvents Events { get; } + + /// + /// Create a Drive Log's Track + /// + /// + /// Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + /// + /// Thrown when fails to make API call + /// drive log id + /// Working Time Date Span entity + /// Cancellation Token to cancel the request. + /// <> + Task CreateTrackAsync(string id, List waypoint, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Drive Log's Track + /// + /// + /// Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + /// + /// drive log id + /// Working Time Date Span entity + /// Cancellation Token to cancel the request. + /// <?> + Task CreateTrackOrDefaultAsync(string id, List waypoint, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Drive Log's Track + /// + /// + /// Deletes the Drive Log's Track. The Drive Log itself is kept. + /// + /// Thrown when fails to make API call + /// drive log id + /// Cancellation Token to cancel the request. + /// <> + Task DeleteTrackAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Drive Log's Track + /// + /// + /// Deletes the Drive Log's Track. The Drive Log itself is kept. + /// + /// drive log id + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteTrackOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Drive Log's Track + /// + /// + /// Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + /// + /// Thrown when fails to make API call + /// drive log id + /// Cancellation Token to cancel the request. + /// <> + Task GetTrackAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Drive Log's Track + /// + /// + /// Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + /// + /// drive log id + /// Cancellation Token to cancel the request. + /// <?> + Task GetTrackOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Replace a Drive Log's Track + /// + /// + /// Replaces the Drive Log's Track with the waypoints in the request body. + /// + /// Thrown when fails to make API call + /// drive log id + /// working time date span entity + /// Cancellation Token to cancel the request. + /// <> + Task UpdateTrackAsync(string id, List waypoint, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Replace a Drive Log's Track + /// + /// + /// Replaces the Drive Log's Track with the waypoints in the request body. + /// + /// drive log id + /// working time date span entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpdateTrackOrDefaultAsync(string id, List waypoint, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateTrackApiResponse : Timr.Api.Client.IApiResponse, ICreated?>, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IDeleteTrackApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IGetTrackApiResponse : Timr.Api.Client.IApiResponse, IOk?>, IBadRequest, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IUpdateTrackApiResponse : Timr.Api.Client.IApiResponse, IOk?>, IBadRequest, IForbidden, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class TrackApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateTrack; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateTrack; + + internal void ExecuteOnCreateTrack(TrackApi.CreateTrackApiResponse apiResponse) + { + OnCreateTrack?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateTrack(Exception exception) + { + OnErrorCreateTrack?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteTrack; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteTrack; + + internal void ExecuteOnDeleteTrack(TrackApi.DeleteTrackApiResponse apiResponse) + { + OnDeleteTrack?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteTrack(Exception exception) + { + OnErrorDeleteTrack?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetTrack; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetTrack; + + internal void ExecuteOnGetTrack(TrackApi.GetTrackApiResponse apiResponse) + { + OnGetTrack?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetTrack(Exception exception) + { + OnErrorGetTrack?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpdateTrack; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateTrack; + + internal void ExecuteOnUpdateTrack(TrackApi.UpdateTrackApiResponse apiResponse) + { + OnUpdateTrack?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateTrack(Exception exception) + { + OnErrorUpdateTrack?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class TrackApi : ITrackApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public TrackApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public TrackApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, TrackApiEvents trackApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = trackApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateTrack(ref string id, List waypoint); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateCreateTrack(string id, List waypoint) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (waypoint == null) + throw new ArgumentNullException(nameof(waypoint)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterCreateTrackDefaultImplementation(ICreateTrackApiResponse apiResponseLocalVar, string id, List waypoint) + { + bool suppressDefaultLog = false; + AfterCreateTrack(ref suppressDefaultLog, apiResponseLocalVar, id, waypoint); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterCreateTrack(ref bool suppressDefaultLog, ICreateTrackApiResponse apiResponseLocalVar, string id, List waypoint); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorCreateTrackDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, List waypoint) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateTrack(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, waypoint); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateTrack(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, List waypoint); + + /// + /// Create a Drive Log's Track Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + /// + /// drive log id + /// Working Time Date Span entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTrackOrDefaultAsync(string id, List waypoint, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateTrackAsync(id, waypoint, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Drive Log's Track Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + /// + /// Thrown when fails to make API call + /// drive log id + /// Working Time Date Span entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateTrackAsync(string id, List waypoint, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateTrack(id, waypoint); + + FormatCreateTrack(ref id, waypoint); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs/{id}/track" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs/{id}/track"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (waypoint as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(waypoint, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateTrackApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs/{id}/track", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateTrackDefaultImplementation(apiResponseLocalVar, id, waypoint); + + Events.ExecuteOnCreateTrack(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateTrackDefaultImplementation(e, "/drive-logs/{id}/track", uriBuilderLocalVar.Path, id, waypoint); + Events.ExecuteOnErrorCreateTrack(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateTrackApiResponse : Timr.Api.Client.ApiResponse, ICreateTrackApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTrackApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateTrackApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public List? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize>(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out List? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatDeleteTrack(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteTrack(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteTrackDefaultImplementation(IDeleteTrackApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterDeleteTrack(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteTrack(ref bool suppressDefaultLog, IDeleteTrackApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteTrackDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteTrack(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteTrack(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Delete a Drive Log's Track Deletes the Drive Log's Track. The Drive Log itself is kept. + /// + /// drive log id + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTrackOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteTrackAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Drive Log's Track Deletes the Drive Log's Track. The Drive Log itself is kept. + /// + /// Thrown when fails to make API call + /// drive log id + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTrackAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteTrack(id); + + FormatDeleteTrack(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs/{id}/track" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs/{id}/track"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteTrackApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs/{id}/track", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteTrackDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnDeleteTrack(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteTrackDefaultImplementation(e, "/drive-logs/{id}/track", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorDeleteTrack(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteTrackApiResponse : Timr.Api.Client.ApiResponse, IDeleteTrackApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTrackApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTrackApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetTrack(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetTrack(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetTrackDefaultImplementation(IGetTrackApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetTrack(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetTrack(ref bool suppressDefaultLog, IGetTrackApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetTrackDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetTrack(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetTrack(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Drive Log's Track Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + /// + /// drive log id + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTrackOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetTrackAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Drive Log's Track Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + /// + /// Thrown when fails to make API call + /// drive log id + /// Cancellation Token to cancel the request. + /// <> + public async Task GetTrackAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetTrack(id); + + FormatGetTrack(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs/{id}/track" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs/{id}/track"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetTrackApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs/{id}/track", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetTrackDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetTrack(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetTrackDefaultImplementation(e, "/drive-logs/{id}/track", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetTrack(e); + throw; + } + } + + /// + /// The + /// + public partial class GetTrackApiResponse : Timr.Api.Client.ApiResponse, IGetTrackApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTrackApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetTrackApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public List? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize>(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out List? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpdateTrack(ref string id, List waypoint); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateTrack(string id, List waypoint) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (waypoint == null) + throw new ArgumentNullException(nameof(waypoint)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateTrackDefaultImplementation(IUpdateTrackApiResponse apiResponseLocalVar, string id, List waypoint) + { + bool suppressDefaultLog = false; + AfterUpdateTrack(ref suppressDefaultLog, apiResponseLocalVar, id, waypoint); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateTrack(ref bool suppressDefaultLog, IUpdateTrackApiResponse apiResponseLocalVar, string id, List waypoint); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateTrackDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, List waypoint) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpdateTrack(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, waypoint); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateTrack(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, List waypoint); + + /// + /// Replace a Drive Log's Track Replaces the Drive Log's Track with the waypoints in the request body. + /// + /// drive log id + /// working time date span entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateTrackOrDefaultAsync(string id, List waypoint, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateTrackAsync(id, waypoint, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Replace a Drive Log's Track Replaces the Drive Log's Track with the waypoints in the request body. + /// + /// Thrown when fails to make API call + /// drive log id + /// working time date span entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateTrackAsync(string id, List waypoint, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateTrack(id, waypoint); + + FormatUpdateTrack(ref id, waypoint); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/drive-logs/{id}/track" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/drive-logs/{id}/track"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (waypoint as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(waypoint, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Put; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpdateTrackApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/drive-logs/{id}/track", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpdateTrackDefaultImplementation(apiResponseLocalVar, id, waypoint); + + Events.ExecuteOnUpdateTrack(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateTrackDefaultImplementation(e, "/drive-logs/{id}/track", uriBuilderLocalVar.Path, id, waypoint); + Events.ExecuteOnErrorUpdateTrack(e); + throw; + } + } + + /// + /// The + /// + public partial class UpdateTrackApiResponse : Timr.Api.Client.ApiResponse, IUpdateTrackApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateTrackApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateTrackApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public List? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize>(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out List? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/UserApi.cs b/sdk/dotnet/Timr.Api/Api/UserApi.cs new file mode 100644 index 0000000..07dd731 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/UserApi.cs @@ -0,0 +1,3225 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IUserApi : IApi + { + /// + /// The class containing the events + /// + UserApiEvents Events { get; } + + /// + /// Create a User + /// + /// + /// Creates a User from the data in the request body. + /// + /// Thrown when fails to make API call + /// User entity + /// Cancellation Token to cancel the request. + /// <> + Task CreateUserAsync(UserCreate userCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a User + /// + /// + /// Creates a User from the data in the request body. + /// + /// User entity + /// Cancellation Token to cancel the request. + /// <?> + Task CreateUserOrDefaultAsync(UserCreate userCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List a User's Team leaderships + /// + /// + /// Lists the Teams the User leads. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchUserTeamLeadershipsAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List a User's Team leaderships + /// + /// + /// Lists the Teams the User leads. + /// + /// ID of the User. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchUserTeamLeadershipsOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List a User's Team memberships + /// + /// + /// Lists the Teams the User is a member of. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchUserTeamMembershipsAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List a User's Team memberships + /// + /// + /// Lists the Teams the User is a member of. + /// + /// ID of the User. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchUserTeamMembershipsOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Users + /// + /// + /// Lists the Users the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Users whose name contains this text. (optional) + /// Only return Users whose entry date is on or after this day. (optional) + /// Only return Users whose entry date is on or before this day. (optional) + /// Only return Users whose resignation date is on or after this day. (optional) + /// Only return Users whose resignation date is on or before this day. (optional) + /// Only return Users who have resigned (true) or have not resigned (false). (optional) + /// Only return Users with this employee number. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchUsersAsync(Option name = default, Option entryDateFrom = default, Option entryDateTo = default, Option resignDateFrom = default, Option resignDateTo = default, Option resigned = default, Option employeeNumber = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Users + /// + /// + /// Lists the Users the authenticated user or API token can access. + /// + /// Only return Users whose name contains this text. (optional) + /// Only return Users whose entry date is on or after this day. (optional) + /// Only return Users whose entry date is on or before this day. (optional) + /// Only return Users whose resignation date is on or after this day. (optional) + /// Only return Users whose resignation date is on or before this day. (optional) + /// Only return Users who have resigned (true) or have not resigned (false). (optional) + /// Only return Users with this employee number. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchUsersOrDefaultAsync(Option name = default, Option entryDateFrom = default, Option entryDateTo = default, Option resignDateFrom = default, Option resignDateTo = default, Option resigned = default, Option employeeNumber = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a User + /// + /// + /// Returns a single User by its ID. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task GetUserAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a User + /// + /// + /// Returns a single User by its ID. + /// + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task GetUserOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a User's Work Schedule Model + /// + /// + /// Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + Task GetUserWorkScheduleModelAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a User's Work Schedule Model + /// + /// + /// Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + /// + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <?> + Task GetUserWorkScheduleModelOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a User + /// + /// + /// Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// User entity + /// Cancellation Token to cancel the request. + /// <> + Task UpdateUserAsync(string id, UserUpdate userUpdate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a User + /// + /// + /// Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the User. + /// User entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpdateUserOrDefaultAsync(string id, UserUpdate userUpdate, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateUserApiResponse : Timr.Api.Client.IApiResponse, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IFetchUserTeamLeadershipsApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IFetchUserTeamMembershipsApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IFetchUsersApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetUserApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IGetUserWorkScheduleModelApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IUpdateUserApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest, IForbidden, INotFound, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class UserApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateUser; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateUser; + + internal void ExecuteOnCreateUser(UserApi.CreateUserApiResponse apiResponse) + { + OnCreateUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateUser(Exception exception) + { + OnErrorCreateUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchUserTeamLeaderships; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchUserTeamLeaderships; + + internal void ExecuteOnFetchUserTeamLeaderships(UserApi.FetchUserTeamLeadershipsApiResponse apiResponse) + { + OnFetchUserTeamLeaderships?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchUserTeamLeaderships(Exception exception) + { + OnErrorFetchUserTeamLeaderships?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchUserTeamMemberships; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchUserTeamMemberships; + + internal void ExecuteOnFetchUserTeamMemberships(UserApi.FetchUserTeamMembershipsApiResponse apiResponse) + { + OnFetchUserTeamMemberships?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchUserTeamMemberships(Exception exception) + { + OnErrorFetchUserTeamMemberships?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchUsers; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchUsers; + + internal void ExecuteOnFetchUsers(UserApi.FetchUsersApiResponse apiResponse) + { + OnFetchUsers?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchUsers(Exception exception) + { + OnErrorFetchUsers?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetUser; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetUser; + + internal void ExecuteOnGetUser(UserApi.GetUserApiResponse apiResponse) + { + OnGetUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetUser(Exception exception) + { + OnErrorGetUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetUserWorkScheduleModel; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetUserWorkScheduleModel; + + internal void ExecuteOnGetUserWorkScheduleModel(UserApi.GetUserWorkScheduleModelApiResponse apiResponse) + { + OnGetUserWorkScheduleModel?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetUserWorkScheduleModel(Exception exception) + { + OnErrorGetUserWorkScheduleModel?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpdateUser; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateUser; + + internal void ExecuteOnUpdateUser(UserApi.UpdateUserApiResponse apiResponse) + { + OnUpdateUser?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateUser(Exception exception) + { + OnErrorUpdateUser?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class UserApi : IUserApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public UserApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public UserApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, UserApiEvents userApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = userApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateUser(UserCreate userCreate); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateUser(UserCreate userCreate) + { + if (userCreate == null) + throw new ArgumentNullException(nameof(userCreate)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateUserDefaultImplementation(ICreateUserApiResponse apiResponseLocalVar, UserCreate userCreate) + { + bool suppressDefaultLog = false; + AfterCreateUser(ref suppressDefaultLog, apiResponseLocalVar, userCreate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateUser(ref bool suppressDefaultLog, ICreateUserApiResponse apiResponseLocalVar, UserCreate userCreate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateUserDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, UserCreate userCreate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateUser(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, userCreate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateUser(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, UserCreate userCreate); + + /// + /// Create a User Creates a User from the data in the request body. + /// + /// User entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateUserOrDefaultAsync(UserCreate userCreate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateUserAsync(userCreate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a User Creates a User from the data in the request body. + /// + /// Thrown when fails to make API call + /// User entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateUserAsync(UserCreate userCreate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateUser(userCreate); + + FormatCreateUser(userCreate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users"); + + httpRequestMessageLocalVar.Content = (userCreate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(userCreate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateUserApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateUserDefaultImplementation(apiResponseLocalVar, userCreate); + + Events.ExecuteOnCreateUser(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateUserDefaultImplementation(e, "/users", uriBuilderLocalVar.Path, userCreate); + Events.ExecuteOnErrorCreateUser(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateUserApiResponse : Timr.Api.Client.ApiResponse, ICreateUserApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.User? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.User? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchUserTeamLeaderships(ref string id, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchUserTeamLeaderships(string id, Option pageToken) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchUserTeamLeadershipsDefaultImplementation(IFetchUserTeamLeadershipsApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchUserTeamLeaderships(ref suppressDefaultLog, apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchUserTeamLeaderships(ref bool suppressDefaultLog, IFetchUserTeamLeadershipsApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchUserTeamLeadershipsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchUserTeamLeaderships(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchUserTeamLeaderships(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List a User's Team leaderships Lists the Teams the User leads. + /// + /// ID of the User. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchUserTeamLeadershipsOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchUserTeamLeadershipsAsync(id, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List a User's Team leaderships Lists the Teams the User leads. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchUserTeamLeadershipsAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchUserTeamLeaderships(id, pageToken); + + FormatFetchUserTeamLeaderships(ref id, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users/{id}/team-leaderships" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users/{id}/team-leaderships"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchUserTeamLeadershipsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users/{id}/team-leaderships", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchUserTeamLeadershipsDefaultImplementation(apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchUserTeamLeaderships(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchUserTeamLeadershipsDefaultImplementation(e, "/users/{id}/team-leaderships", uriBuilderLocalVar.Path, id, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchUserTeamLeaderships(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchUserTeamLeadershipsApiResponse : Timr.Api.Client.ApiResponse, IFetchUserTeamLeadershipsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchUserTeamLeadershipsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchUserTeamLeadershipsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TeamsPartialPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TeamsPartialPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchUserTeamMemberships(ref string id, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateFetchUserTeamMemberships(string id, Option pageToken) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchUserTeamMembershipsDefaultImplementation(IFetchUserTeamMembershipsApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchUserTeamMemberships(ref suppressDefaultLog, apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchUserTeamMemberships(ref bool suppressDefaultLog, IFetchUserTeamMembershipsApiResponse apiResponseLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchUserTeamMembershipsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchUserTeamMemberships(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchUserTeamMemberships(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List a User's Team memberships Lists the Teams the User is a member of. + /// + /// ID of the User. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchUserTeamMembershipsOrDefaultAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchUserTeamMembershipsAsync(id, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List a User's Team memberships Lists the Teams the User is a member of. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchUserTeamMembershipsAsync(string id, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchUserTeamMemberships(id, pageToken); + + FormatFetchUserTeamMemberships(ref id, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users/{id}/team-memberships" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users/{id}/team-memberships"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchUserTeamMembershipsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users/{id}/team-memberships", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchUserTeamMembershipsDefaultImplementation(apiResponseLocalVar, id, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchUserTeamMemberships(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchUserTeamMembershipsDefaultImplementation(e, "/users/{id}/team-memberships", uriBuilderLocalVar.Path, id, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchUserTeamMemberships(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchUserTeamMembershipsApiResponse : Timr.Api.Client.ApiResponse, IFetchUserTeamMembershipsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchUserTeamMembershipsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchUserTeamMembershipsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.TeamsPartialPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.TeamsPartialPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchUsers(ref Option name, ref Option entryDateFrom, ref Option entryDateTo, ref Option resignDateFrom, ref Option resignDateTo, ref Option resigned, ref Option employeeNumber, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + private void ValidateFetchUsers(Option name, Option employeeNumber, Option pageToken) + { + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name)); + + if (employeeNumber.IsSet && employeeNumber.Value == null) + throw new ArgumentNullException(nameof(employeeNumber)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchUsersDefaultImplementation(IFetchUsersApiResponse apiResponseLocalVar, Option name, Option entryDateFrom, Option entryDateTo, Option resignDateFrom, Option resignDateTo, Option resigned, Option employeeNumber, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchUsers(ref suppressDefaultLog, apiResponseLocalVar, name, entryDateFrom, entryDateTo, resignDateFrom, resignDateTo, resigned, employeeNumber, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchUsers(ref bool suppressDefaultLog, IFetchUsersApiResponse apiResponseLocalVar, Option name, Option entryDateFrom, Option entryDateTo, Option resignDateFrom, Option resignDateTo, Option resigned, Option employeeNumber, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchUsersDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option name, Option entryDateFrom, Option entryDateTo, Option resignDateFrom, Option resignDateTo, Option resigned, Option employeeNumber, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchUsers(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, name, entryDateFrom, entryDateTo, resignDateFrom, resignDateTo, resigned, employeeNumber, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchUsers(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option name, Option entryDateFrom, Option entryDateTo, Option resignDateFrom, Option resignDateTo, Option resigned, Option employeeNumber, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Users Lists the Users the authenticated user or API token can access. + /// + /// Only return Users whose name contains this text. (optional) + /// Only return Users whose entry date is on or after this day. (optional) + /// Only return Users whose entry date is on or before this day. (optional) + /// Only return Users whose resignation date is on or after this day. (optional) + /// Only return Users whose resignation date is on or before this day. (optional) + /// Only return Users who have resigned (true) or have not resigned (false). (optional) + /// Only return Users with this employee number. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchUsersOrDefaultAsync(Option name = default, Option entryDateFrom = default, Option entryDateTo = default, Option resignDateFrom = default, Option resignDateTo = default, Option resigned = default, Option employeeNumber = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchUsersAsync(name, entryDateFrom, entryDateTo, resignDateFrom, resignDateTo, resigned, employeeNumber, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Users Lists the Users the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Users whose name contains this text. (optional) + /// Only return Users whose entry date is on or after this day. (optional) + /// Only return Users whose entry date is on or before this day. (optional) + /// Only return Users whose resignation date is on or after this day. (optional) + /// Only return Users whose resignation date is on or before this day. (optional) + /// Only return Users who have resigned (true) or have not resigned (false). (optional) + /// Only return Users with this employee number. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchUsersAsync(Option name = default, Option entryDateFrom = default, Option entryDateTo = default, Option resignDateFrom = default, Option resignDateTo = default, Option resigned = default, Option employeeNumber = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchUsers(name, employeeNumber, pageToken); + + FormatFetchUsers(ref name, ref entryDateFrom, ref entryDateTo, ref resignDateFrom, ref resignDateTo, ref resigned, ref employeeNumber, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (name.IsSet) + parseQueryStringLocalVar["name"] = ClientUtils.ParameterToString(name.Value); + + if (entryDateFrom.IsSet) + parseQueryStringLocalVar["entry_date_from"] = ClientUtils.ParameterToString(entryDateFrom.Value); + + if (entryDateTo.IsSet) + parseQueryStringLocalVar["entry_date_to"] = ClientUtils.ParameterToString(entryDateTo.Value); + + if (resignDateFrom.IsSet) + parseQueryStringLocalVar["resign_date_from"] = ClientUtils.ParameterToString(resignDateFrom.Value); + + if (resignDateTo.IsSet) + parseQueryStringLocalVar["resign_date_to"] = ClientUtils.ParameterToString(resignDateTo.Value); + + if (resigned.IsSet) + parseQueryStringLocalVar["resigned"] = ClientUtils.ParameterToString(resigned.Value); + + if (employeeNumber.IsSet) + parseQueryStringLocalVar["employee_number"] = ClientUtils.ParameterToString(employeeNumber.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchUsersApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchUsersDefaultImplementation(apiResponseLocalVar, name, entryDateFrom, entryDateTo, resignDateFrom, resignDateTo, resigned, employeeNumber, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchUsers(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchUsersDefaultImplementation(e, "/users", uriBuilderLocalVar.Path, name, entryDateFrom, entryDateTo, resignDateFrom, resignDateTo, resigned, employeeNumber, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchUsers(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchUsersApiResponse : Timr.Api.Client.ApiResponse, IFetchUsersApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchUsersApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.UsersPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.UsersPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetUser(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetUser(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetUserDefaultImplementation(IGetUserApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetUser(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetUser(ref bool suppressDefaultLog, IGetUserApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetUserDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetUser(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetUser(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a User Returns a single User by its ID. + /// + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetUserOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetUserAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a User Returns a single User by its ID. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetUserAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetUser(id); + + FormatGetUser(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetUserApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetUserDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetUser(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetUserDefaultImplementation(e, "/users/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetUser(e); + throw; + } + } + + /// + /// The + /// + public partial class GetUserApiResponse : Timr.Api.Client.ApiResponse, IGetUserApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.User? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.User? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetUserWorkScheduleModel(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetUserWorkScheduleModel(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetUserWorkScheduleModelDefaultImplementation(IGetUserWorkScheduleModelApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetUserWorkScheduleModel(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetUserWorkScheduleModel(ref bool suppressDefaultLog, IGetUserWorkScheduleModelApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetUserWorkScheduleModelDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetUserWorkScheduleModel(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetUserWorkScheduleModel(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a User's Work Schedule Model Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + /// + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetUserWorkScheduleModelOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetUserWorkScheduleModelAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a User's Work Schedule Model Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetUserWorkScheduleModelAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetUserWorkScheduleModel(id); + + FormatGetUserWorkScheduleModel(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users/{id}/work-schedule-model" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users/{id}/work-schedule-model"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetUserWorkScheduleModelApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users/{id}/work-schedule-model", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetUserWorkScheduleModelDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetUserWorkScheduleModel(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetUserWorkScheduleModelDefaultImplementation(e, "/users/{id}/work-schedule-model", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetUserWorkScheduleModel(e); + throw; + } + } + + /// + /// The + /// + public partial class GetUserWorkScheduleModelApiResponse : Timr.Api.Client.ApiResponse, IGetUserWorkScheduleModelApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetUserWorkScheduleModelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetUserWorkScheduleModelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkScheduleModel? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkScheduleModel? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpdateUser(ref string id, UserUpdate userUpdate); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateUser(string id, UserUpdate userUpdate) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (userUpdate == null) + throw new ArgumentNullException(nameof(userUpdate)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateUserDefaultImplementation(IUpdateUserApiResponse apiResponseLocalVar, string id, UserUpdate userUpdate) + { + bool suppressDefaultLog = false; + AfterUpdateUser(ref suppressDefaultLog, apiResponseLocalVar, id, userUpdate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateUser(ref bool suppressDefaultLog, IUpdateUserApiResponse apiResponseLocalVar, string id, UserUpdate userUpdate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateUserDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, UserUpdate userUpdate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpdateUser(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, userUpdate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateUser(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, UserUpdate userUpdate); + + /// + /// Update a User Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the User. + /// User entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateUserOrDefaultAsync(string id, UserUpdate userUpdate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateUserAsync(id, userUpdate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Update a User Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the User. + /// User entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateUserAsync(string id, UserUpdate userUpdate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateUser(id, userUpdate); + + FormatUpdateUser(ref id, userUpdate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/users/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/users/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (userUpdate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(userUpdate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpdateUserApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/users/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpdateUserDefaultImplementation(apiResponseLocalVar, id, userUpdate); + + Events.ExecuteOnUpdateUser(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateUserDefaultImplementation(e, "/users/{id}", uriBuilderLocalVar.Path, id, userUpdate); + Events.ExecuteOnErrorUpdateUser(e); + throw; + } + } + + /// + /// The + /// + public partial class UpdateUserApiResponse : Timr.Api.Client.ApiResponse, IUpdateUserApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateUserApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.User? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.User? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/WorkScheduleModelApi.cs b/sdk/dotnet/Timr.Api/Api/WorkScheduleModelApi.cs new file mode 100644 index 0000000..c051d66 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/WorkScheduleModelApi.cs @@ -0,0 +1,1310 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IWorkScheduleModelApi : IApi + { + /// + /// The class containing the events + /// + WorkScheduleModelApiEvents Events { get; } + + /// + /// Delete a Work Schedule Model + /// + /// + /// Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + /// + /// Thrown when fails to make API call + /// ID of the Work Schedule Model. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteWorkScheduleModelAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Work Schedule Model + /// + /// + /// Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + /// + /// ID of the Work Schedule Model. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteWorkScheduleModelOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Work Schedule Models + /// + /// + /// Lists the Work Schedule Models the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchWorkScheduleModelsAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Work Schedule Models + /// + /// + /// Lists the Work Schedule Models the authenticated user or API token can access. + /// + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchWorkScheduleModelsOrDefaultAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Work Schedule Model + /// + /// + /// Returns a single Work Schedule Model by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Work Schedule Model. + /// Cancellation Token to cancel the request. + /// <> + Task GetWorkScheduleModelAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Work Schedule Model + /// + /// + /// Returns a single Work Schedule Model by its ID. + /// + /// ID of the Work Schedule Model. + /// Cancellation Token to cancel the request. + /// <?> + Task GetWorkScheduleModelOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface IDeleteWorkScheduleModelApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchWorkScheduleModelsApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetWorkScheduleModelApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class WorkScheduleModelApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteWorkScheduleModel; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteWorkScheduleModel; + + internal void ExecuteOnDeleteWorkScheduleModel(WorkScheduleModelApi.DeleteWorkScheduleModelApiResponse apiResponse) + { + OnDeleteWorkScheduleModel?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteWorkScheduleModel(Exception exception) + { + OnErrorDeleteWorkScheduleModel?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchWorkScheduleModels; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchWorkScheduleModels; + + internal void ExecuteOnFetchWorkScheduleModels(WorkScheduleModelApi.FetchWorkScheduleModelsApiResponse apiResponse) + { + OnFetchWorkScheduleModels?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchWorkScheduleModels(Exception exception) + { + OnErrorFetchWorkScheduleModels?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetWorkScheduleModel; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetWorkScheduleModel; + + internal void ExecuteOnGetWorkScheduleModel(WorkScheduleModelApi.GetWorkScheduleModelApiResponse apiResponse) + { + OnGetWorkScheduleModel?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetWorkScheduleModel(Exception exception) + { + OnErrorGetWorkScheduleModel?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class WorkScheduleModelApi : IWorkScheduleModelApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public WorkScheduleModelApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public WorkScheduleModelApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, WorkScheduleModelApiEvents workScheduleModelApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = workScheduleModelApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatDeleteWorkScheduleModel(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteWorkScheduleModel(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteWorkScheduleModelDefaultImplementation(IDeleteWorkScheduleModelApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterDeleteWorkScheduleModel(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteWorkScheduleModel(ref bool suppressDefaultLog, IDeleteWorkScheduleModelApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteWorkScheduleModelDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteWorkScheduleModel(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteWorkScheduleModel(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Delete a Work Schedule Model Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + /// + /// ID of the Work Schedule Model. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteWorkScheduleModelOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteWorkScheduleModelAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Work Schedule Model Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + /// + /// Thrown when fails to make API call + /// ID of the Work Schedule Model. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteWorkScheduleModelAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteWorkScheduleModel(id); + + FormatDeleteWorkScheduleModel(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/work-schedule-models/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/work-schedule-models/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteWorkScheduleModelApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/work-schedule-models/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteWorkScheduleModelDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnDeleteWorkScheduleModel(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteWorkScheduleModelDefaultImplementation(e, "/work-schedule-models/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorDeleteWorkScheduleModel(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteWorkScheduleModelApiResponse : Timr.Api.Client.ApiResponse, IDeleteWorkScheduleModelApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteWorkScheduleModelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteWorkScheduleModelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchWorkScheduleModels(ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFetchWorkScheduleModels(Option pageToken) + { + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + private void AfterFetchWorkScheduleModelsDefaultImplementation(IFetchWorkScheduleModelsApiResponse apiResponseLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchWorkScheduleModels(ref suppressDefaultLog, apiResponseLocalVar, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchWorkScheduleModels(ref bool suppressDefaultLog, IFetchWorkScheduleModelsApiResponse apiResponseLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchWorkScheduleModelsDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchWorkScheduleModels(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchWorkScheduleModels(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Work Schedule Models Lists the Work Schedule Models the authenticated user or API token can access. + /// + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchWorkScheduleModelsOrDefaultAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchWorkScheduleModelsAsync(pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Work Schedule Models Lists the Work Schedule Models the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchWorkScheduleModelsAsync(Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchWorkScheduleModels(pageToken); + + FormatFetchWorkScheduleModels(ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/work-schedule-models" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/work-schedule-models"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchWorkScheduleModelsApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/work-schedule-models", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchWorkScheduleModelsDefaultImplementation(apiResponseLocalVar, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchWorkScheduleModels(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchWorkScheduleModelsDefaultImplementation(e, "/work-schedule-models", uriBuilderLocalVar.Path, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchWorkScheduleModels(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchWorkScheduleModelsApiResponse : Timr.Api.Client.ApiResponse, IFetchWorkScheduleModelsApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchWorkScheduleModelsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchWorkScheduleModelsApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkScheduleModelsPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkScheduleModelsPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetWorkScheduleModel(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetWorkScheduleModel(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetWorkScheduleModelDefaultImplementation(IGetWorkScheduleModelApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetWorkScheduleModel(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetWorkScheduleModel(ref bool suppressDefaultLog, IGetWorkScheduleModelApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetWorkScheduleModelDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetWorkScheduleModel(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetWorkScheduleModel(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Work Schedule Model Returns a single Work Schedule Model by its ID. + /// + /// ID of the Work Schedule Model. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetWorkScheduleModelOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetWorkScheduleModelAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Work Schedule Model Returns a single Work Schedule Model by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Work Schedule Model. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetWorkScheduleModelAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetWorkScheduleModel(id); + + FormatGetWorkScheduleModel(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/work-schedule-models/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/work-schedule-models/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetWorkScheduleModelApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/work-schedule-models/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetWorkScheduleModelDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetWorkScheduleModel(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetWorkScheduleModelDefaultImplementation(e, "/work-schedule-models/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetWorkScheduleModel(e); + throw; + } + } + + /// + /// The + /// + public partial class GetWorkScheduleModelApiResponse : Timr.Api.Client.ApiResponse, IGetWorkScheduleModelApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetWorkScheduleModelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetWorkScheduleModelApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkScheduleModel? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkScheduleModel? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/WorkingTimeApi.cs b/sdk/dotnet/Timr.Api/Api/WorkingTimeApi.cs new file mode 100644 index 0000000..f3bf3dd --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/WorkingTimeApi.cs @@ -0,0 +1,2869 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IWorkingTimeApi : IApi + { + /// + /// The class containing the events + /// + WorkingTimeApiEvents Events { get; } + + /// + /// Create a Working Time + /// + /// + /// Creates a Working Time from the data in the request body. + /// + /// Thrown when fails to make API call + /// Working Time entity + /// Cancellation Token to cancel the request. + /// <> + Task CreateWorkingTimeAsync(WorkingTimeCreate workingTimeCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Working Time + /// + /// + /// Creates a Working Time from the data in the request body. + /// + /// Working Time entity + /// Cancellation Token to cancel the request. + /// <?> + Task CreateWorkingTimeOrDefaultAsync(WorkingTimeCreate workingTimeCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Working Time + /// + /// + /// Deletes the Working Time. + /// + /// Thrown when fails to make API call + /// ID of the Working Time. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteWorkingTimeAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Working Time + /// + /// + /// Deletes the Working Time. + /// + /// ID of the Working Time. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteWorkingTimeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List deleted Working Times + /// + /// + /// Lists Working Times that were deleted, so a client holding a local copy can reconcile. + /// + /// Thrown when fails to make API call + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchDeletedWorkingTimesAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List deleted Working Times + /// + /// + /// Lists Working Times that were deleted, so a client holding a local copy can reconcile. + /// + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchDeletedWorkingTimesOrDefaultAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Working Times + /// + /// + /// Lists the Working Times the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return entries whose notes contain this text. (optional) + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries of these Working Time Types. (optional) + /// Only return entries whose Working Time Type is in one of these categories. (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchWorkingTimesAsync(Option notes = default, Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option> workingTimeTypes = default, Option> workingTimeTypeCategories = default, Option> statuses = default, Option> users = default, Option changed = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Working Times + /// + /// + /// Lists the Working Times the authenticated user or API token can access. + /// + /// Only return entries whose notes contain this text. (optional) + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries of these Working Time Types. (optional) + /// Only return entries whose Working Time Type is in one of these categories. (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchWorkingTimesOrDefaultAsync(Option notes = default, Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option> workingTimeTypes = default, Option> workingTimeTypeCategories = default, Option> statuses = default, Option> users = default, Option changed = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Working Time + /// + /// + /// Returns a single Working Time by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Working Time. + /// Cancellation Token to cancel the request. + /// <> + Task GetWorkingTimeAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Working Time + /// + /// + /// Returns a single Working Time by its ID. + /// + /// ID of the Working Time. + /// Cancellation Token to cancel the request. + /// <?> + Task GetWorkingTimeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Working Time + /// + /// + /// Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Working Time. + /// Working Time entity + /// Cancellation Token to cancel the request. + /// <> + Task UpdateWorkingTimeAsync(string id, WorkingTimeUpdate workingTimeUpdate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Working Time + /// + /// + /// Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Working Time. + /// Working Time entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpdateWorkingTimeOrDefaultAsync(string id, WorkingTimeUpdate workingTimeUpdate, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateWorkingTimeApiResponse : Timr.Api.Client.IApiResponse, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IDeleteWorkingTimeApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchDeletedWorkingTimesApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IFetchWorkingTimesApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetWorkingTimeApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IUpdateWorkingTimeApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest, IForbidden, INotFound, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 302 Found + /// + /// + bool IsFound { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class WorkingTimeApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateWorkingTime; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateWorkingTime; + + internal void ExecuteOnCreateWorkingTime(WorkingTimeApi.CreateWorkingTimeApiResponse apiResponse) + { + OnCreateWorkingTime?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateWorkingTime(Exception exception) + { + OnErrorCreateWorkingTime?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteWorkingTime; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteWorkingTime; + + internal void ExecuteOnDeleteWorkingTime(WorkingTimeApi.DeleteWorkingTimeApiResponse apiResponse) + { + OnDeleteWorkingTime?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteWorkingTime(Exception exception) + { + OnErrorDeleteWorkingTime?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchDeletedWorkingTimes; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchDeletedWorkingTimes; + + internal void ExecuteOnFetchDeletedWorkingTimes(WorkingTimeApi.FetchDeletedWorkingTimesApiResponse apiResponse) + { + OnFetchDeletedWorkingTimes?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchDeletedWorkingTimes(Exception exception) + { + OnErrorFetchDeletedWorkingTimes?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchWorkingTimes; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchWorkingTimes; + + internal void ExecuteOnFetchWorkingTimes(WorkingTimeApi.FetchWorkingTimesApiResponse apiResponse) + { + OnFetchWorkingTimes?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchWorkingTimes(Exception exception) + { + OnErrorFetchWorkingTimes?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetWorkingTime; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetWorkingTime; + + internal void ExecuteOnGetWorkingTime(WorkingTimeApi.GetWorkingTimeApiResponse apiResponse) + { + OnGetWorkingTime?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetWorkingTime(Exception exception) + { + OnErrorGetWorkingTime?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpdateWorkingTime; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateWorkingTime; + + internal void ExecuteOnUpdateWorkingTime(WorkingTimeApi.UpdateWorkingTimeApiResponse apiResponse) + { + OnUpdateWorkingTime?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateWorkingTime(Exception exception) + { + OnErrorUpdateWorkingTime?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class WorkingTimeApi : IWorkingTimeApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public WorkingTimeApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public WorkingTimeApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, WorkingTimeApiEvents workingTimeApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = workingTimeApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateWorkingTime(WorkingTimeCreate workingTimeCreate); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateWorkingTime(WorkingTimeCreate workingTimeCreate) + { + if (workingTimeCreate == null) + throw new ArgumentNullException(nameof(workingTimeCreate)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateWorkingTimeDefaultImplementation(ICreateWorkingTimeApiResponse apiResponseLocalVar, WorkingTimeCreate workingTimeCreate) + { + bool suppressDefaultLog = false; + AfterCreateWorkingTime(ref suppressDefaultLog, apiResponseLocalVar, workingTimeCreate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateWorkingTime(ref bool suppressDefaultLog, ICreateWorkingTimeApiResponse apiResponseLocalVar, WorkingTimeCreate workingTimeCreate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateWorkingTimeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, WorkingTimeCreate workingTimeCreate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateWorkingTime(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, workingTimeCreate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateWorkingTime(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, WorkingTimeCreate workingTimeCreate); + + /// + /// Create a Working Time Creates a Working Time from the data in the request body. + /// + /// Working Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateWorkingTimeOrDefaultAsync(WorkingTimeCreate workingTimeCreate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateWorkingTimeAsync(workingTimeCreate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Working Time Creates a Working Time from the data in the request body. + /// + /// Thrown when fails to make API call + /// Working Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateWorkingTimeAsync(WorkingTimeCreate workingTimeCreate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateWorkingTime(workingTimeCreate); + + FormatCreateWorkingTime(workingTimeCreate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-times" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-times"); + + httpRequestMessageLocalVar.Content = (workingTimeCreate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(workingTimeCreate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateWorkingTimeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-times", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateWorkingTimeDefaultImplementation(apiResponseLocalVar, workingTimeCreate); + + Events.ExecuteOnCreateWorkingTime(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateWorkingTimeDefaultImplementation(e, "/working-times", uriBuilderLocalVar.Path, workingTimeCreate); + Events.ExecuteOnErrorCreateWorkingTime(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateWorkingTimeApiResponse : Timr.Api.Client.ApiResponse, ICreateWorkingTimeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateWorkingTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateWorkingTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.WorkingTime? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.WorkingTime? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatDeleteWorkingTime(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteWorkingTime(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteWorkingTimeDefaultImplementation(IDeleteWorkingTimeApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterDeleteWorkingTime(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteWorkingTime(ref bool suppressDefaultLog, IDeleteWorkingTimeApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteWorkingTimeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteWorkingTime(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteWorkingTime(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Delete a Working Time Deletes the Working Time. + /// + /// ID of the Working Time. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteWorkingTimeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteWorkingTimeAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Working Time Deletes the Working Time. + /// + /// Thrown when fails to make API call + /// ID of the Working Time. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteWorkingTimeAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteWorkingTime(id); + + FormatDeleteWorkingTime(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-times/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-times/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteWorkingTimeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-times/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteWorkingTimeDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnDeleteWorkingTime(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteWorkingTimeDefaultImplementation(e, "/working-times/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorDeleteWorkingTime(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteWorkingTimeApiResponse : Timr.Api.Client.ApiResponse, IDeleteWorkingTimeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteWorkingTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteWorkingTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchDeletedWorkingTimes(ref Option lastModifiedAfter, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFetchDeletedWorkingTimes(Option pageToken) + { + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchDeletedWorkingTimesDefaultImplementation(IFetchDeletedWorkingTimesApiResponse apiResponseLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchDeletedWorkingTimes(ref suppressDefaultLog, apiResponseLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchDeletedWorkingTimes(ref bool suppressDefaultLog, IFetchDeletedWorkingTimesApiResponse apiResponseLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchDeletedWorkingTimesDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchDeletedWorkingTimes(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchDeletedWorkingTimes(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List deleted Working Times Lists Working Times that were deleted, so a client holding a local copy can reconcile. + /// + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDeletedWorkingTimesOrDefaultAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchDeletedWorkingTimesAsync(lastModifiedAfter, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List deleted Working Times Lists Working Times that were deleted, so a client holding a local copy can reconcile. + /// + /// Thrown when fails to make API call + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDeletedWorkingTimesAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchDeletedWorkingTimes(pageToken); + + FormatFetchDeletedWorkingTimes(ref lastModifiedAfter, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-times:deleted" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-times:deleted"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (lastModifiedAfter.IsSet) + parseQueryStringLocalVar["last_modified_after"] = ClientUtils.ParameterToString(lastModifiedAfter.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchDeletedWorkingTimesApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-times:deleted", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchDeletedWorkingTimesDefaultImplementation(apiResponseLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchDeletedWorkingTimes(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchDeletedWorkingTimesDefaultImplementation(e, "/working-times:deleted", uriBuilderLocalVar.Path, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchDeletedWorkingTimes(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchDeletedWorkingTimesApiResponse : Timr.Api.Client.ApiResponse, IFetchDeletedWorkingTimesApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDeletedWorkingTimesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDeletedWorkingTimesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.DeletedEntryWithMetadataPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.DeletedEntryWithMetadataPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchWorkingTimes(ref Option notes, ref Option startFrom, ref Option startTo, ref Option lastModifiedAfter, Option> workingTimeTypes, Option> workingTimeTypeCategories, Option> statuses, Option> users, ref Option changed, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + private void ValidateFetchWorkingTimes(Option notes, Option> workingTimeTypes, Option> workingTimeTypeCategories, Option> statuses, Option> users, Option pageToken) + { + if (notes.IsSet && notes.Value == null) + throw new ArgumentNullException(nameof(notes)); + + if (workingTimeTypes.IsSet && workingTimeTypes.Value == null) + throw new ArgumentNullException(nameof(workingTimeTypes)); + + if (workingTimeTypeCategories.IsSet && workingTimeTypeCategories.Value == null) + throw new ArgumentNullException(nameof(workingTimeTypeCategories)); + + if (statuses.IsSet && statuses.Value == null) + throw new ArgumentNullException(nameof(statuses)); + + if (users.IsSet && users.Value == null) + throw new ArgumentNullException(nameof(users)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchWorkingTimesDefaultImplementation(IFetchWorkingTimesApiResponse apiResponseLocalVar, Option notes, Option startFrom, Option startTo, Option lastModifiedAfter, Option> workingTimeTypes, Option> workingTimeTypeCategories, Option> statuses, Option> users, Option changed, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchWorkingTimes(ref suppressDefaultLog, apiResponseLocalVar, notes, startFrom, startTo, lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchWorkingTimes(ref bool suppressDefaultLog, IFetchWorkingTimesApiResponse apiResponseLocalVar, Option notes, Option startFrom, Option startTo, Option lastModifiedAfter, Option> workingTimeTypes, Option> workingTimeTypeCategories, Option> statuses, Option> users, Option changed, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchWorkingTimesDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option notes, Option startFrom, Option startTo, Option lastModifiedAfter, Option> workingTimeTypes, Option> workingTimeTypeCategories, Option> statuses, Option> users, Option changed, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchWorkingTimes(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, notes, startFrom, startTo, lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchWorkingTimes(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option notes, Option startFrom, Option startTo, Option lastModifiedAfter, Option> workingTimeTypes, Option> workingTimeTypeCategories, Option> statuses, Option> users, Option changed, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Working Times Lists the Working Times the authenticated user or API token can access. + /// + /// Only return entries whose notes contain this text. (optional) + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries of these Working Time Types. (optional) + /// Only return entries whose Working Time Type is in one of these categories. (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchWorkingTimesOrDefaultAsync(Option notes = default, Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option> workingTimeTypes = default, Option> workingTimeTypeCategories = default, Option> statuses = default, Option> users = default, Option changed = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchWorkingTimesAsync(notes, startFrom, startTo, lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, changed, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Working Times Lists the Working Times the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return entries whose notes contain this text. (optional) + /// Only return entries starting on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries of these Working Time Types. (optional) + /// Only return entries whose Working Time Type is in one of these categories. (optional) + /// Only return entries in one of these statuses. (optional) + /// Only return entries belonging to these users. (optional) + /// Only return entries that were changed by the user (true) or left unchanged (false). (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchWorkingTimesAsync(Option notes = default, Option startFrom = default, Option startTo = default, Option lastModifiedAfter = default, Option> workingTimeTypes = default, Option> workingTimeTypeCategories = default, Option> statuses = default, Option> users = default, Option changed = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchWorkingTimes(notes, workingTimeTypes, workingTimeTypeCategories, statuses, users, pageToken); + + FormatFetchWorkingTimes(ref notes, ref startFrom, ref startTo, ref lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, ref changed, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-times" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-times"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (notes.IsSet) + parseQueryStringLocalVar["notes"] = ClientUtils.ParameterToString(notes.Value); + + if (startFrom.IsSet) + parseQueryStringLocalVar["start_from"] = ClientUtils.ParameterToString(startFrom.Value); + + if (startTo.IsSet) + parseQueryStringLocalVar["start_to"] = ClientUtils.ParameterToString(startTo.Value); + + if (lastModifiedAfter.IsSet) + parseQueryStringLocalVar["last_modified_after"] = ClientUtils.ParameterToString(lastModifiedAfter.Value); + + if (workingTimeTypes.IsSet) + parseQueryStringLocalVar["working_time_types"] = ClientUtils.ParameterToString(workingTimeTypes.Value); + + if (workingTimeTypeCategories.IsSet) + parseQueryStringLocalVar["working_time_type_categories"] = ClientUtils.ParameterToString(workingTimeTypeCategories.Value); + + if (statuses.IsSet) + parseQueryStringLocalVar["statuses"] = ClientUtils.ParameterToString(statuses.Value); + + if (users.IsSet) + parseQueryStringLocalVar["users"] = ClientUtils.ParameterToString(users.Value); + + if (changed.IsSet) + parseQueryStringLocalVar["changed"] = ClientUtils.ParameterToString(changed.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchWorkingTimesApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-times", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchWorkingTimesDefaultImplementation(apiResponseLocalVar, notes, startFrom, startTo, lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchWorkingTimes(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchWorkingTimesDefaultImplementation(e, "/working-times", uriBuilderLocalVar.Path, notes, startFrom, startTo, lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchWorkingTimes(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchWorkingTimesApiResponse : Timr.Api.Client.ApiResponse, IFetchWorkingTimesApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchWorkingTimesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchWorkingTimesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkingTimesPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkingTimesPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetWorkingTime(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetWorkingTime(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetWorkingTimeDefaultImplementation(IGetWorkingTimeApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetWorkingTime(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetWorkingTime(ref bool suppressDefaultLog, IGetWorkingTimeApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetWorkingTimeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetWorkingTime(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetWorkingTime(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Working Time Returns a single Working Time by its ID. + /// + /// ID of the Working Time. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetWorkingTimeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetWorkingTimeAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Working Time Returns a single Working Time by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Working Time. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetWorkingTimeAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetWorkingTime(id); + + FormatGetWorkingTime(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-times/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-times/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetWorkingTimeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-times/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetWorkingTimeDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetWorkingTime(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetWorkingTimeDefaultImplementation(e, "/working-times/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetWorkingTime(e); + throw; + } + } + + /// + /// The + /// + public partial class GetWorkingTimeApiResponse : Timr.Api.Client.ApiResponse, IGetWorkingTimeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetWorkingTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetWorkingTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkingTime? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkingTime? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpdateWorkingTime(ref string id, WorkingTimeUpdate workingTimeUpdate); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateWorkingTime(string id, WorkingTimeUpdate workingTimeUpdate) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (workingTimeUpdate == null) + throw new ArgumentNullException(nameof(workingTimeUpdate)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateWorkingTimeDefaultImplementation(IUpdateWorkingTimeApiResponse apiResponseLocalVar, string id, WorkingTimeUpdate workingTimeUpdate) + { + bool suppressDefaultLog = false; + AfterUpdateWorkingTime(ref suppressDefaultLog, apiResponseLocalVar, id, workingTimeUpdate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateWorkingTime(ref bool suppressDefaultLog, IUpdateWorkingTimeApiResponse apiResponseLocalVar, string id, WorkingTimeUpdate workingTimeUpdate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateWorkingTimeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, WorkingTimeUpdate workingTimeUpdate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpdateWorkingTime(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, workingTimeUpdate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateWorkingTime(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, WorkingTimeUpdate workingTimeUpdate); + + /// + /// Update a Working Time Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// ID of the Working Time. + /// Working Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateWorkingTimeOrDefaultAsync(string id, WorkingTimeUpdate workingTimeUpdate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateWorkingTimeAsync(id, workingTimeUpdate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Update a Working Time Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Working Time. + /// Working Time entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateWorkingTimeAsync(string id, WorkingTimeUpdate workingTimeUpdate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateWorkingTime(id, workingTimeUpdate); + + FormatUpdateWorkingTime(ref id, workingTimeUpdate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-times/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-times/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (workingTimeUpdate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(workingTimeUpdate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpdateWorkingTimeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-times/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpdateWorkingTimeDefaultImplementation(apiResponseLocalVar, id, workingTimeUpdate); + + Events.ExecuteOnUpdateWorkingTime(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateWorkingTimeDefaultImplementation(e, "/working-times/{id}", uriBuilderLocalVar.Path, id, workingTimeUpdate); + Events.ExecuteOnErrorUpdateWorkingTime(e); + throw; + } + } + + /// + /// The + /// + public partial class UpdateWorkingTimeApiResponse : Timr.Api.Client.ApiResponse, IUpdateWorkingTimeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateWorkingTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateWorkingTimeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkingTime? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkingTime? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 302 Found + /// + /// + public bool IsFound => 302 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/WorkingTimeDateSpanApi.cs b/sdk/dotnet/Timr.Api/Api/WorkingTimeDateSpanApi.cs new file mode 100644 index 0000000..4513dd2 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/WorkingTimeDateSpanApi.cs @@ -0,0 +1,2813 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IWorkingTimeDateSpanApi : IApi + { + /// + /// The class containing the events + /// + WorkingTimeDateSpanApiEvents Events { get; } + + /// + /// Create a Working Time Date Span + /// + /// + /// Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + /// + /// Thrown when fails to make API call + /// Working Time Date Span entity + /// Cancellation Token to cancel the request. + /// <> + Task CreateWorkingTimeDateSpanAsync(WorkingTimeDateSpanCreate workingTimeDateSpanCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Create a Working Time Date Span + /// + /// + /// Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + /// + /// Working Time Date Span entity + /// Cancellation Token to cancel the request. + /// <?> + Task CreateWorkingTimeDateSpanOrDefaultAsync(WorkingTimeDateSpanCreate workingTimeDateSpanCreate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Working Time Date Span + /// + /// + /// Deletes the Working Time Date Span together with the Working Times it covers. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Date Span. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteWorkingTimeDateSpanAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Working Time Date Span + /// + /// + /// Deletes the Working Time Date Span together with the Working Times it covers. + /// + /// ID of the Working Time Date Span. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteWorkingTimeDateSpanOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List deleted Working Time Date Spans + /// + /// + /// Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + /// + /// Thrown when fails to make API call + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchDeletedWorkingTimeDateSpansAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List deleted Working Time Date Spans + /// + /// + /// Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + /// + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchDeletedWorkingTimeDateSpansOrDefaultAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Working Time Date Spans + /// + /// + /// Lists the Working Time Date Spans the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Working Time Date Spans that end on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries of these Working Time Types. (optional) + /// Only return entries belonging to these users. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchWorkingTimeDateSpansAsync(Option from = default, Option to = default, Option lastModifiedAfter = default, Option> workingTimeTypes = default, Option> users = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Working Time Date Spans + /// + /// + /// Lists the Working Time Date Spans the authenticated user or API token can access. + /// + /// Only return Working Time Date Spans that end on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries of these Working Time Types. (optional) + /// Only return entries belonging to these users. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchWorkingTimeDateSpansOrDefaultAsync(Option from = default, Option to = default, Option lastModifiedAfter = default, Option> workingTimeTypes = default, Option> users = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Working Time Date Span + /// + /// + /// Returns a single Working Time Date Span by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Date Span. + /// Cancellation Token to cancel the request. + /// <> + Task GetWorkingTimeDateSpanAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Working Time Date Span + /// + /// + /// Returns a single Working Time Date Span by its ID. + /// + /// ID of the Working Time Date Span. + /// Cancellation Token to cancel the request. + /// <?> + Task GetWorkingTimeDateSpanOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Working Time Date Span + /// + /// + /// Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Date Span. + /// working time date span entity + /// Cancellation Token to cancel the request. + /// <> + Task UpdateWorkingTimeDateSpanAsync(string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Update a Working Time Date Span + /// + /// + /// Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + /// + /// ID of the Working Time Date Span. + /// working time date span entity + /// Cancellation Token to cancel the request. + /// <?> + Task UpdateWorkingTimeDateSpanOrDefaultAsync(string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface ICreateWorkingTimeDateSpanApiResponse : Timr.Api.Client.IApiResponse, ICreated, IBadRequest, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 201 Created + /// + /// + bool IsCreated { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// The + /// + public interface IDeleteWorkingTimeDateSpanApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchDeletedWorkingTimeDateSpansApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IFetchWorkingTimeDateSpansApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetWorkingTimeDateSpanApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// The + /// + public interface IUpdateWorkingTimeDateSpanApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest, IForbidden, INotFound, IConflict, IUnprocessableContent + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + bool IsUnprocessableContent { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class WorkingTimeDateSpanApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnCreateWorkingTimeDateSpan; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorCreateWorkingTimeDateSpan; + + internal void ExecuteOnCreateWorkingTimeDateSpan(WorkingTimeDateSpanApi.CreateWorkingTimeDateSpanApiResponse apiResponse) + { + OnCreateWorkingTimeDateSpan?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorCreateWorkingTimeDateSpan(Exception exception) + { + OnErrorCreateWorkingTimeDateSpan?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteWorkingTimeDateSpan; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteWorkingTimeDateSpan; + + internal void ExecuteOnDeleteWorkingTimeDateSpan(WorkingTimeDateSpanApi.DeleteWorkingTimeDateSpanApiResponse apiResponse) + { + OnDeleteWorkingTimeDateSpan?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteWorkingTimeDateSpan(Exception exception) + { + OnErrorDeleteWorkingTimeDateSpan?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchDeletedWorkingTimeDateSpans; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchDeletedWorkingTimeDateSpans; + + internal void ExecuteOnFetchDeletedWorkingTimeDateSpans(WorkingTimeDateSpanApi.FetchDeletedWorkingTimeDateSpansApiResponse apiResponse) + { + OnFetchDeletedWorkingTimeDateSpans?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchDeletedWorkingTimeDateSpans(Exception exception) + { + OnErrorFetchDeletedWorkingTimeDateSpans?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchWorkingTimeDateSpans; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchWorkingTimeDateSpans; + + internal void ExecuteOnFetchWorkingTimeDateSpans(WorkingTimeDateSpanApi.FetchWorkingTimeDateSpansApiResponse apiResponse) + { + OnFetchWorkingTimeDateSpans?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchWorkingTimeDateSpans(Exception exception) + { + OnErrorFetchWorkingTimeDateSpans?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetWorkingTimeDateSpan; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetWorkingTimeDateSpan; + + internal void ExecuteOnGetWorkingTimeDateSpan(WorkingTimeDateSpanApi.GetWorkingTimeDateSpanApiResponse apiResponse) + { + OnGetWorkingTimeDateSpan?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetWorkingTimeDateSpan(Exception exception) + { + OnErrorGetWorkingTimeDateSpan?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnUpdateWorkingTimeDateSpan; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorUpdateWorkingTimeDateSpan; + + internal void ExecuteOnUpdateWorkingTimeDateSpan(WorkingTimeDateSpanApi.UpdateWorkingTimeDateSpanApiResponse apiResponse) + { + OnUpdateWorkingTimeDateSpan?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorUpdateWorkingTimeDateSpan(Exception exception) + { + OnErrorUpdateWorkingTimeDateSpan?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class WorkingTimeDateSpanApi : IWorkingTimeDateSpanApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public WorkingTimeDateSpanApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public WorkingTimeDateSpanApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, WorkingTimeDateSpanApiEvents workingTimeDateSpanApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = workingTimeDateSpanApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatCreateWorkingTimeDateSpan(WorkingTimeDateSpanCreate workingTimeDateSpanCreate); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateCreateWorkingTimeDateSpan(WorkingTimeDateSpanCreate workingTimeDateSpanCreate) + { + if (workingTimeDateSpanCreate == null) + throw new ArgumentNullException(nameof(workingTimeDateSpanCreate)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterCreateWorkingTimeDateSpanDefaultImplementation(ICreateWorkingTimeDateSpanApiResponse apiResponseLocalVar, WorkingTimeDateSpanCreate workingTimeDateSpanCreate) + { + bool suppressDefaultLog = false; + AfterCreateWorkingTimeDateSpan(ref suppressDefaultLog, apiResponseLocalVar, workingTimeDateSpanCreate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterCreateWorkingTimeDateSpan(ref bool suppressDefaultLog, ICreateWorkingTimeDateSpanApiResponse apiResponseLocalVar, WorkingTimeDateSpanCreate workingTimeDateSpanCreate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorCreateWorkingTimeDateSpanDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, WorkingTimeDateSpanCreate workingTimeDateSpanCreate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorCreateWorkingTimeDateSpan(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, workingTimeDateSpanCreate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorCreateWorkingTimeDateSpan(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, WorkingTimeDateSpanCreate workingTimeDateSpanCreate); + + /// + /// Create a Working Time Date Span Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + /// + /// Working Time Date Span entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateWorkingTimeDateSpanOrDefaultAsync(WorkingTimeDateSpanCreate workingTimeDateSpanCreate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await CreateWorkingTimeDateSpanAsync(workingTimeDateSpanCreate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Create a Working Time Date Span Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + /// + /// Thrown when fails to make API call + /// Working Time Date Span entity + /// Cancellation Token to cancel the request. + /// <> + public async Task CreateWorkingTimeDateSpanAsync(WorkingTimeDateSpanCreate workingTimeDateSpanCreate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateCreateWorkingTimeDateSpan(workingTimeDateSpanCreate); + + FormatCreateWorkingTimeDateSpan(workingTimeDateSpanCreate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-time-date-spans" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-time-date-spans"); + + httpRequestMessageLocalVar.Content = (workingTimeDateSpanCreate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(workingTimeDateSpanCreate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + CreateWorkingTimeDateSpanApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-time-date-spans", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterCreateWorkingTimeDateSpanDefaultImplementation(apiResponseLocalVar, workingTimeDateSpanCreate); + + Events.ExecuteOnCreateWorkingTimeDateSpan(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorCreateWorkingTimeDateSpanDefaultImplementation(e, "/working-time-date-spans", uriBuilderLocalVar.Path, workingTimeDateSpanCreate); + Events.ExecuteOnErrorCreateWorkingTimeDateSpan(e); + throw; + } + } + + /// + /// The + /// + public partial class CreateWorkingTimeDateSpanApiResponse : Timr.Api.Client.ApiResponse, ICreateWorkingTimeDateSpanApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateWorkingTimeDateSpanApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public CreateWorkingTimeDateSpanApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 201 Created + /// + /// + public bool IsCreated => 201 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 201 Created + /// + /// + public Timr.Api.Model.WorkingTimeDateSpan? Created() + { + // This logic may be modified with the AsModel.mustache template + return IsCreated + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 201 Created and the deserialized response is not null + /// + /// + /// + public bool TryCreated([NotNullWhen(true)]out Timr.Api.Model.WorkingTimeDateSpan? result) + { + result = null; + + try + { + result = Created(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)201); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatDeleteWorkingTimeDateSpan(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteWorkingTimeDateSpan(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteWorkingTimeDateSpanDefaultImplementation(IDeleteWorkingTimeDateSpanApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterDeleteWorkingTimeDateSpan(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteWorkingTimeDateSpan(ref bool suppressDefaultLog, IDeleteWorkingTimeDateSpanApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteWorkingTimeDateSpanDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteWorkingTimeDateSpan(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteWorkingTimeDateSpan(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Delete a Working Time Date Span Deletes the Working Time Date Span together with the Working Times it covers. + /// + /// ID of the Working Time Date Span. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteWorkingTimeDateSpanOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteWorkingTimeDateSpanAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Working Time Date Span Deletes the Working Time Date Span together with the Working Times it covers. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Date Span. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteWorkingTimeDateSpanAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteWorkingTimeDateSpan(id); + + FormatDeleteWorkingTimeDateSpan(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-time-date-spans/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-time-date-spans/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteWorkingTimeDateSpanApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-time-date-spans/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteWorkingTimeDateSpanDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnDeleteWorkingTimeDateSpan(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteWorkingTimeDateSpanDefaultImplementation(e, "/working-time-date-spans/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorDeleteWorkingTimeDateSpan(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteWorkingTimeDateSpanApiResponse : Timr.Api.Client.ApiResponse, IDeleteWorkingTimeDateSpanApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteWorkingTimeDateSpanApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteWorkingTimeDateSpanApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchDeletedWorkingTimeDateSpans(ref Option lastModifiedAfter, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateFetchDeletedWorkingTimeDateSpans(Option pageToken) + { + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchDeletedWorkingTimeDateSpansDefaultImplementation(IFetchDeletedWorkingTimeDateSpansApiResponse apiResponseLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchDeletedWorkingTimeDateSpans(ref suppressDefaultLog, apiResponseLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchDeletedWorkingTimeDateSpans(ref bool suppressDefaultLog, IFetchDeletedWorkingTimeDateSpansApiResponse apiResponseLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchDeletedWorkingTimeDateSpansDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchDeletedWorkingTimeDateSpans(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchDeletedWorkingTimeDateSpans(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option lastModifiedAfter, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List deleted Working Time Date Spans Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + /// + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDeletedWorkingTimeDateSpansOrDefaultAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchDeletedWorkingTimeDateSpansAsync(lastModifiedAfter, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List deleted Working Time Date Spans Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + /// + /// Thrown when fails to make API call + /// Only return entries modified after this instant. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchDeletedWorkingTimeDateSpansAsync(Option lastModifiedAfter = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchDeletedWorkingTimeDateSpans(pageToken); + + FormatFetchDeletedWorkingTimeDateSpans(ref lastModifiedAfter, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-time-date-spans:deleted" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-time-date-spans:deleted"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (lastModifiedAfter.IsSet) + parseQueryStringLocalVar["last_modified_after"] = ClientUtils.ParameterToString(lastModifiedAfter.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchDeletedWorkingTimeDateSpansApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-time-date-spans:deleted", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchDeletedWorkingTimeDateSpansDefaultImplementation(apiResponseLocalVar, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchDeletedWorkingTimeDateSpans(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchDeletedWorkingTimeDateSpansDefaultImplementation(e, "/working-time-date-spans:deleted", uriBuilderLocalVar.Path, lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchDeletedWorkingTimeDateSpans(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchDeletedWorkingTimeDateSpansApiResponse : Timr.Api.Client.ApiResponse, IFetchDeletedWorkingTimeDateSpansApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDeletedWorkingTimeDateSpansApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchDeletedWorkingTimeDateSpansApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.DeletedEntryWithMetadataPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.DeletedEntryWithMetadataPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchWorkingTimeDateSpans(ref Option from, ref Option to, ref Option lastModifiedAfter, Option> workingTimeTypes, Option> users, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + private void ValidateFetchWorkingTimeDateSpans(Option> workingTimeTypes, Option> users, Option pageToken) + { + if (workingTimeTypes.IsSet && workingTimeTypes.Value == null) + throw new ArgumentNullException(nameof(workingTimeTypes)); + + if (users.IsSet && users.Value == null) + throw new ArgumentNullException(nameof(users)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchWorkingTimeDateSpansDefaultImplementation(IFetchWorkingTimeDateSpansApiResponse apiResponseLocalVar, Option from, Option to, Option lastModifiedAfter, Option> workingTimeTypes, Option> users, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchWorkingTimeDateSpans(ref suppressDefaultLog, apiResponseLocalVar, from, to, lastModifiedAfter, workingTimeTypes, users, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchWorkingTimeDateSpans(ref bool suppressDefaultLog, IFetchWorkingTimeDateSpansApiResponse apiResponseLocalVar, Option from, Option to, Option lastModifiedAfter, Option> workingTimeTypes, Option> users, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchWorkingTimeDateSpansDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option from, Option to, Option lastModifiedAfter, Option> workingTimeTypes, Option> users, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchWorkingTimeDateSpans(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, from, to, lastModifiedAfter, workingTimeTypes, users, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchWorkingTimeDateSpans(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option from, Option to, Option lastModifiedAfter, Option> workingTimeTypes, Option> users, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Working Time Date Spans Lists the Working Time Date Spans the authenticated user or API token can access. + /// + /// Only return Working Time Date Spans that end on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries of these Working Time Types. (optional) + /// Only return entries belonging to these users. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchWorkingTimeDateSpansOrDefaultAsync(Option from = default, Option to = default, Option lastModifiedAfter = default, Option> workingTimeTypes = default, Option> users = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchWorkingTimeDateSpansAsync(from, to, lastModifiedAfter, workingTimeTypes, users, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Working Time Date Spans Lists the Working Time Date Spans the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return Working Time Date Spans that end on or after this day. (optional) + /// Only return entries starting on or before this day. (optional) + /// Only return entries modified after this instant. (optional) + /// Only return entries of these Working Time Types. (optional) + /// Only return entries belonging to these users. (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchWorkingTimeDateSpansAsync(Option from = default, Option to = default, Option lastModifiedAfter = default, Option> workingTimeTypes = default, Option> users = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchWorkingTimeDateSpans(workingTimeTypes, users, pageToken); + + FormatFetchWorkingTimeDateSpans(ref from, ref to, ref lastModifiedAfter, workingTimeTypes, users, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-time-date-spans" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-time-date-spans"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (from.IsSet) + parseQueryStringLocalVar["from"] = ClientUtils.ParameterToString(from.Value); + + if (to.IsSet) + parseQueryStringLocalVar["to"] = ClientUtils.ParameterToString(to.Value); + + if (lastModifiedAfter.IsSet) + parseQueryStringLocalVar["last_modified_after"] = ClientUtils.ParameterToString(lastModifiedAfter.Value); + + if (workingTimeTypes.IsSet) + parseQueryStringLocalVar["working_time_types"] = ClientUtils.ParameterToString(workingTimeTypes.Value); + + if (users.IsSet) + parseQueryStringLocalVar["users"] = ClientUtils.ParameterToString(users.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchWorkingTimeDateSpansApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-time-date-spans", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchWorkingTimeDateSpansDefaultImplementation(apiResponseLocalVar, from, to, lastModifiedAfter, workingTimeTypes, users, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchWorkingTimeDateSpans(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchWorkingTimeDateSpansDefaultImplementation(e, "/working-time-date-spans", uriBuilderLocalVar.Path, from, to, lastModifiedAfter, workingTimeTypes, users, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchWorkingTimeDateSpans(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchWorkingTimeDateSpansApiResponse : Timr.Api.Client.ApiResponse, IFetchWorkingTimeDateSpansApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchWorkingTimeDateSpansApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchWorkingTimeDateSpansApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkingTimeDateSpanPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkingTimeDateSpanPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetWorkingTimeDateSpan(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetWorkingTimeDateSpan(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetWorkingTimeDateSpanDefaultImplementation(IGetWorkingTimeDateSpanApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetWorkingTimeDateSpan(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetWorkingTimeDateSpan(ref bool suppressDefaultLog, IGetWorkingTimeDateSpanApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetWorkingTimeDateSpanDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetWorkingTimeDateSpan(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetWorkingTimeDateSpan(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Working Time Date Span Returns a single Working Time Date Span by its ID. + /// + /// ID of the Working Time Date Span. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetWorkingTimeDateSpanOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetWorkingTimeDateSpanAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Working Time Date Span Returns a single Working Time Date Span by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Date Span. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetWorkingTimeDateSpanAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetWorkingTimeDateSpan(id); + + FormatGetWorkingTimeDateSpan(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-time-date-spans/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-time-date-spans/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetWorkingTimeDateSpanApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-time-date-spans/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetWorkingTimeDateSpanDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetWorkingTimeDateSpan(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetWorkingTimeDateSpanDefaultImplementation(e, "/working-time-date-spans/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetWorkingTimeDateSpan(e); + throw; + } + } + + /// + /// The + /// + public partial class GetWorkingTimeDateSpanApiResponse : Timr.Api.Client.ApiResponse, IGetWorkingTimeDateSpanApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetWorkingTimeDateSpanApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetWorkingTimeDateSpanApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkingTimeDateSpan? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkingTimeDateSpan? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatUpdateWorkingTimeDateSpan(ref string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate); + + /// + /// Validates the request parameters + /// + /// + /// + /// + private void ValidateUpdateWorkingTimeDateSpan(string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + + if (workingTimeDateSpanUpdate == null) + throw new ArgumentNullException(nameof(workingTimeDateSpanUpdate)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + private void AfterUpdateWorkingTimeDateSpanDefaultImplementation(IUpdateWorkingTimeDateSpanApiResponse apiResponseLocalVar, string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate) + { + bool suppressDefaultLog = false; + AfterUpdateWorkingTimeDateSpan(ref suppressDefaultLog, apiResponseLocalVar, id, workingTimeDateSpanUpdate); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + partial void AfterUpdateWorkingTimeDateSpan(ref bool suppressDefaultLog, IUpdateWorkingTimeDateSpanApiResponse apiResponseLocalVar, string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + private void OnErrorUpdateWorkingTimeDateSpanDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate) + { + bool suppressDefaultLogLocalVar = false; + OnErrorUpdateWorkingTimeDateSpan(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id, workingTimeDateSpanUpdate); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorUpdateWorkingTimeDateSpan(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate); + + /// + /// Update a Working Time Date Span Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + /// + /// ID of the Working Time Date Span. + /// working time date span entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateWorkingTimeDateSpanOrDefaultAsync(string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await UpdateWorkingTimeDateSpanAsync(id, workingTimeDateSpanUpdate, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Update a Working Time Date Span Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Date Span. + /// working time date span entity + /// Cancellation Token to cancel the request. + /// <> + public async Task UpdateWorkingTimeDateSpanAsync(string id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateUpdateWorkingTimeDateSpan(id, workingTimeDateSpanUpdate); + + FormatUpdateWorkingTimeDateSpan(ref id, workingTimeDateSpanUpdate); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-time-date-spans/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-time-date-spans/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + httpRequestMessageLocalVar.Content = (workingTimeDateSpanUpdate as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(workingTimeDateSpanUpdate, _jsonSerializerOptions)); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Patch; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + UpdateWorkingTimeDateSpanApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-time-date-spans/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterUpdateWorkingTimeDateSpanDefaultImplementation(apiResponseLocalVar, id, workingTimeDateSpanUpdate); + + Events.ExecuteOnUpdateWorkingTimeDateSpan(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorUpdateWorkingTimeDateSpanDefaultImplementation(e, "/working-time-date-spans/{id}", uriBuilderLocalVar.Path, id, workingTimeDateSpanUpdate); + Events.ExecuteOnErrorUpdateWorkingTimeDateSpan(e); + throw; + } + } + + /// + /// The + /// + public partial class UpdateWorkingTimeDateSpanApiResponse : Timr.Api.Client.ApiResponse, IUpdateWorkingTimeDateSpanApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateWorkingTimeDateSpanApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public UpdateWorkingTimeDateSpanApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkingTimeDateSpan? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkingTimeDateSpan? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent + /// + /// + public bool IsUnprocessableContent => 422 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 422 UnprocessableContent + /// + /// + public Timr.Api.Model.Error? UnprocessableContent() + { + // This logic may be modified with the AsModel.mustache template + return IsUnprocessableContent + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 422 UnprocessableContent and the deserialized response is not null + /// + /// + /// + public bool TryUnprocessableContent([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = UnprocessableContent(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)422); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Api/WorkingTimeTypeApi.cs b/sdk/dotnet/Timr.Api/Api/WorkingTimeTypeApi.cs new file mode 100644 index 0000000..1a9445a --- /dev/null +++ b/sdk/dotnet/Timr.Api/Api/WorkingTimeTypeApi.cs @@ -0,0 +1,1426 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Timr.Api.Client; +using Timr.Api.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Timr.Api.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IWorkingTimeTypeApi : IApi + { + /// + /// The class containing the events + /// + WorkingTimeTypeApiEvents Events { get; } + + /// + /// Delete a Working Time Type + /// + /// + /// Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Type. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteWorkingTimeTypeAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Working Time Type + /// + /// + /// Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + /// + /// ID of the Working Time Type. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteWorkingTimeTypeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Working Time Types + /// + /// + /// Lists the Working Time Types the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return entries whose name contains this text. (optional) + /// filter by short name (optional) + /// filter by description (optional) + /// filter by WorkingTimeTypeCategory (optional) + /// filter by WorkingTimeTypeSubCategory (optional) + /// filter by WorkingTimeType's DurationUnit (optional) + /// Only return entries that are archived (true) or not archived (false). (optional) + /// filter entries bAWS on their RecordingMode (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + Task FetchWorkingTimeTypesAsync(Option name = default, Option shortName = default, Option description = default, Option> categories = default, Option> subCategories = default, Option> editUnits = default, Option archived = default, Option> recordingModes = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// List Working Time Types + /// + /// + /// Lists the Working Time Types the authenticated user or API token can access. + /// + /// Only return entries whose name contains this text. (optional) + /// filter by short name (optional) + /// filter by description (optional) + /// filter by WorkingTimeTypeCategory (optional) + /// filter by WorkingTimeTypeSubCategory (optional) + /// filter by WorkingTimeType's DurationUnit (optional) + /// Only return entries that are archived (true) or not archived (false). (optional) + /// filter entries bAWS on their RecordingMode (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <?> + Task FetchWorkingTimeTypesOrDefaultAsync(Option name = default, Option shortName = default, Option description = default, Option> categories = default, Option> subCategories = default, Option> editUnits = default, Option archived = default, Option> recordingModes = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Working Time Type + /// + /// + /// Returns a single Working Time Type by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Type. + /// Cancellation Token to cancel the request. + /// <> + Task GetWorkingTimeTypeAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Get a Working Time Type + /// + /// + /// Returns a single Working Time Type by its ID. + /// + /// ID of the Working Time Type. + /// Cancellation Token to cancel the request. + /// <?> + Task GetWorkingTimeTypeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface IDeleteWorkingTimeTypeApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + + /// + /// The + /// + public interface IFetchWorkingTimeTypesApiResponse : Timr.Api.Client.IApiResponse, IOk, IBadRequest + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + bool IsBadRequest { get; } + } + + /// + /// The + /// + public interface IGetWorkingTimeTypeApiResponse : Timr.Api.Client.IApiResponse, IOk, IForbidden, INotFound + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class WorkingTimeTypeApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteWorkingTimeType; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteWorkingTimeType; + + internal void ExecuteOnDeleteWorkingTimeType(WorkingTimeTypeApi.DeleteWorkingTimeTypeApiResponse apiResponse) + { + OnDeleteWorkingTimeType?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteWorkingTimeType(Exception exception) + { + OnErrorDeleteWorkingTimeType?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnFetchWorkingTimeTypes; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorFetchWorkingTimeTypes; + + internal void ExecuteOnFetchWorkingTimeTypes(WorkingTimeTypeApi.FetchWorkingTimeTypesApiResponse apiResponse) + { + OnFetchWorkingTimeTypes?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorFetchWorkingTimeTypes(Exception exception) + { + OnErrorFetchWorkingTimeTypes?.Invoke(this, new ExceptionEventArgs(exception)); + } + + /// + /// The event raised after the server response + /// + public event EventHandler? OnGetWorkingTimeType; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorGetWorkingTimeType; + + internal void ExecuteOnGetWorkingTimeType(WorkingTimeTypeApi.GetWorkingTimeTypeApiResponse apiResponse) + { + OnGetWorkingTimeType?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorGetWorkingTimeType(Exception exception) + { + OnErrorGetWorkingTimeType?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class WorkingTimeTypeApi : IWorkingTimeTypeApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public WorkingTimeTypeApiEvents Events { get; } + + /// + /// A token provider of type + /// + public TokenProvider OauthTokenProvider { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public WorkingTimeTypeApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, WorkingTimeTypeApiEvents workingTimeTypeApiEvents, + TokenProvider oauthTokenProvider) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = workingTimeTypeApiEvents; + OauthTokenProvider = oauthTokenProvider; + } + + partial void FormatDeleteWorkingTimeType(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteWorkingTimeType(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteWorkingTimeTypeDefaultImplementation(IDeleteWorkingTimeTypeApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterDeleteWorkingTimeType(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteWorkingTimeType(ref bool suppressDefaultLog, IDeleteWorkingTimeTypeApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteWorkingTimeTypeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteWorkingTimeType(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteWorkingTimeType(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Delete a Working Time Type Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + /// + /// ID of the Working Time Type. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteWorkingTimeTypeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteWorkingTimeTypeAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Working Time Type Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Type. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteWorkingTimeTypeAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteWorkingTimeType(id); + + FormatDeleteWorkingTimeType(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-time-types/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-time-types/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + DeleteWorkingTimeTypeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-time-types/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteWorkingTimeTypeDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnDeleteWorkingTimeType(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteWorkingTimeTypeDefaultImplementation(e, "/working-time-types/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorDeleteWorkingTimeType(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteWorkingTimeTypeApiResponse : Timr.Api.Client.ApiResponse, IDeleteWorkingTimeTypeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteWorkingTimeTypeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteWorkingTimeTypeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + // This logic may be modified with the AsModel.mustache template + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatFetchWorkingTimeTypes(ref Option name, ref Option shortName, ref Option description, Option> categories, Option> subCategories, Option> editUnits, ref Option archived, Option> recordingModes, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); + + /// + /// Validates the request parameters + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void ValidateFetchWorkingTimeTypes(Option name, Option shortName, Option description, Option> categories, Option> subCategories, Option> editUnits, Option> recordingModes, Option pageToken) + { + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name)); + + if (shortName.IsSet && shortName.Value == null) + throw new ArgumentNullException(nameof(shortName)); + + if (description.IsSet && description.Value == null) + throw new ArgumentNullException(nameof(description)); + + if (categories.IsSet && categories.Value == null) + throw new ArgumentNullException(nameof(categories)); + + if (subCategories.IsSet && subCategories.Value == null) + throw new ArgumentNullException(nameof(subCategories)); + + if (editUnits.IsSet && editUnits.Value == null) + throw new ArgumentNullException(nameof(editUnits)); + + if (recordingModes.IsSet && recordingModes.Value == null) + throw new ArgumentNullException(nameof(recordingModes)); + + if (pageToken.IsSet && pageToken.Value == null) + throw new ArgumentNullException(nameof(pageToken)); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void AfterFetchWorkingTimeTypesDefaultImplementation(IFetchWorkingTimeTypesApiResponse apiResponseLocalVar, Option name, Option shortName, Option description, Option> categories, Option> subCategories, Option> editUnits, Option archived, Option> recordingModes, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLog = false; + AfterFetchWorkingTimeTypes(ref suppressDefaultLog, apiResponseLocalVar, name, shortName, description, categories, subCategories, editUnits, archived, recordingModes, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void AfterFetchWorkingTimeTypes(ref bool suppressDefaultLog, IFetchWorkingTimeTypesApiResponse apiResponseLocalVar, Option name, Option shortName, Option description, Option> categories, Option> subCategories, Option> editUnits, Option archived, Option> recordingModes, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void OnErrorFetchWorkingTimeTypesDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option name, Option shortName, Option description, Option> categories, Option> subCategories, Option> editUnits, Option archived, Option> recordingModes, Option pageToken, Option limit, Option sortDirection, Option sortBy) + { + bool suppressDefaultLogLocalVar = false; + OnErrorFetchWorkingTimeTypes(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, name, shortName, description, categories, subCategories, editUnits, archived, recordingModes, pageToken, limit, sortDirection, sortBy); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + partial void OnErrorFetchWorkingTimeTypes(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, Option name, Option shortName, Option description, Option> categories, Option> subCategories, Option> editUnits, Option archived, Option> recordingModes, Option pageToken, Option limit, Option sortDirection, Option sortBy); + + /// + /// List Working Time Types Lists the Working Time Types the authenticated user or API token can access. + /// + /// Only return entries whose name contains this text. (optional) + /// filter by short name (optional) + /// filter by description (optional) + /// filter by WorkingTimeTypeCategory (optional) + /// filter by WorkingTimeTypeSubCategory (optional) + /// filter by WorkingTimeType's DurationUnit (optional) + /// Only return entries that are archived (true) or not archived (false). (optional) + /// filter entries bAWS on their RecordingMode (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchWorkingTimeTypesOrDefaultAsync(Option name = default, Option shortName = default, Option description = default, Option> categories = default, Option> subCategories = default, Option> editUnits = default, Option archived = default, Option> recordingModes = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await FetchWorkingTimeTypesAsync(name, shortName, description, categories, subCategories, editUnits, archived, recordingModes, pageToken, limit, sortDirection, sortBy, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// List Working Time Types Lists the Working Time Types the authenticated user or API token can access. + /// + /// Thrown when fails to make API call + /// Only return entries whose name contains this text. (optional) + /// filter by short name (optional) + /// filter by description (optional) + /// filter by WorkingTimeTypeCategory (optional) + /// filter by WorkingTimeTypeSubCategory (optional) + /// filter by WorkingTimeType's DurationUnit (optional) + /// Only return entries that are archived (true) or not archived (false). (optional) + /// filter entries bAWS on their RecordingMode (optional) + /// Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + /// Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + /// Direction to sort the entries in. (optional) + /// Property to sort the entries by. (optional) + /// Cancellation Token to cancel the request. + /// <> + public async Task FetchWorkingTimeTypesAsync(Option name = default, Option shortName = default, Option description = default, Option> categories = default, Option> subCategories = default, Option> editUnits = default, Option archived = default, Option> recordingModes = default, Option pageToken = default, Option limit = default, Option sortDirection = default, Option sortBy = default, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateFetchWorkingTimeTypes(name, shortName, description, categories, subCategories, editUnits, recordingModes, pageToken); + + FormatFetchWorkingTimeTypes(ref name, ref shortName, ref description, categories, subCategories, editUnits, ref archived, recordingModes, ref pageToken, ref limit, ref sortDirection, ref sortBy); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-time-types" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-time-types"); + + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); + + if (name.IsSet) + parseQueryStringLocalVar["name"] = ClientUtils.ParameterToString(name.Value); + + if (shortName.IsSet) + parseQueryStringLocalVar["short_name"] = ClientUtils.ParameterToString(shortName.Value); + + if (description.IsSet) + parseQueryStringLocalVar["description"] = ClientUtils.ParameterToString(description.Value); + + if (categories.IsSet) + parseQueryStringLocalVar["categories"] = ClientUtils.ParameterToString(categories.Value); + + if (subCategories.IsSet) + parseQueryStringLocalVar["sub_categories"] = ClientUtils.ParameterToString(subCategories.Value); + + if (editUnits.IsSet) + parseQueryStringLocalVar["edit_units"] = ClientUtils.ParameterToString(editUnits.Value); + + if (archived.IsSet) + parseQueryStringLocalVar["archived"] = ClientUtils.ParameterToString(archived.Value); + + if (recordingModes.IsSet) + parseQueryStringLocalVar["recording_modes"] = ClientUtils.ParameterToString(recordingModes.Value); + + if (pageToken.IsSet) + parseQueryStringLocalVar["page_token"] = ClientUtils.ParameterToString(pageToken.Value); + + if (limit.IsSet) + parseQueryStringLocalVar["limit"] = ClientUtils.ParameterToString(limit.Value); + + if (sortDirection.IsSet) + parseQueryStringLocalVar["sort_direction"] = ClientUtils.ParameterToString(sortDirection.Value); + + if (sortBy.IsSet) + parseQueryStringLocalVar["sort_by"] = ClientUtils.ParameterToString(sortBy.Value); + + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + FetchWorkingTimeTypesApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-time-types", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterFetchWorkingTimeTypesDefaultImplementation(apiResponseLocalVar, name, shortName, description, categories, subCategories, editUnits, archived, recordingModes, pageToken, limit, sortDirection, sortBy); + + Events.ExecuteOnFetchWorkingTimeTypes(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorFetchWorkingTimeTypesDefaultImplementation(e, "/working-time-types", uriBuilderLocalVar.Path, name, shortName, description, categories, subCategories, editUnits, archived, recordingModes, pageToken, limit, sortDirection, sortBy); + Events.ExecuteOnErrorFetchWorkingTimeTypes(e); + throw; + } + } + + /// + /// The + /// + public partial class FetchWorkingTimeTypesApiResponse : Timr.Api.Client.ApiResponse, IFetchWorkingTimeTypesApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchWorkingTimeTypesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public FetchWorkingTimeTypesApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkingTimeTypesPage? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkingTimeTypesPage? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 400 BadRequest + /// + /// + public bool IsBadRequest => 400 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 400 BadRequest + /// + /// + public Timr.Api.Model.Error? BadRequest() + { + // This logic may be modified with the AsModel.mustache template + return IsBadRequest + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 400 BadRequest and the deserialized response is not null + /// + /// + /// + public bool TryBadRequest([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = BadRequest(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)400); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + + partial void FormatGetWorkingTimeType(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateGetWorkingTimeType(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterGetWorkingTimeTypeDefaultImplementation(IGetWorkingTimeTypeApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterGetWorkingTimeType(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterGetWorkingTimeType(ref bool suppressDefaultLog, IGetWorkingTimeTypeApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorGetWorkingTimeTypeDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorGetWorkingTimeType(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorGetWorkingTimeType(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Get a Working Time Type Returns a single Working Time Type by its ID. + /// + /// ID of the Working Time Type. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetWorkingTimeTypeOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await GetWorkingTimeTypeAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Get a Working Time Type Returns a single Working Time Type by its ID. + /// + /// Thrown when fails to make API call + /// ID of the Working Time Type. + /// Cancellation Token to cancel the request. + /// <> + public async Task GetWorkingTimeTypeAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateGetWorkingTimeType(id); + + FormatGetWorkingTimeType(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/working-time-types/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/working-time-types/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/json", + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + GetWorkingTimeTypeApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/working-time-types/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterGetWorkingTimeTypeDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnGetWorkingTimeType(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorGetWorkingTimeTypeDefaultImplementation(e, "/working-time-types/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorGetWorkingTimeType(e); + throw; + } + } + + /// + /// The + /// + public partial class GetWorkingTimeTypeApiResponse : Timr.Api.Client.ApiResponse, IGetWorkingTimeTypeApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetWorkingTimeTypeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public GetWorkingTimeTypeApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Timr.Api.Model.WorkingTimeType? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Timr.Api.Model.WorkingTimeType? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + // This logic may be modified with the AsModel.mustache template + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + // This logic may be modified with the AsModel.mustache template + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/ApiException.cs b/sdk/dotnet/Timr.Api/Client/ApiException.cs new file mode 100644 index 0000000..2767690 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/ApiException.cs @@ -0,0 +1,53 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; + +namespace Timr.Api.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// The reason the api request failed + /// + public string? ReasonPhrase { get; } + + /// + /// The HttpStatusCode + /// + public System.Net.HttpStatusCode StatusCode { get; } + + /// + /// The raw data returned by the api + /// + public string RawContent { get; } + + /// + /// Construct the ApiException from parts of the response + /// + /// + /// + /// + public ApiException(string? reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent) + { + ReasonPhrase = reasonPhrase; + + StatusCode = statusCode; + + RawContent = rawContent; + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/ApiFactory.cs b/sdk/dotnet/Timr.Api/Client/ApiFactory.cs new file mode 100644 index 0000000..dae0393 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/ApiFactory.cs @@ -0,0 +1,59 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using Microsoft.Extensions.DependencyInjection; +using Timr.Api.Api; + +namespace Timr.Api.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi; + } + + /// + /// An ApiFactory + /// + public class ApiFactory : IApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/ApiResponseEventArgs.cs b/sdk/dotnet/Timr.Api/Client/ApiResponseEventArgs.cs new file mode 100644 index 0000000..9d8b8e5 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/ApiResponseEventArgs.cs @@ -0,0 +1,34 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; + +namespace Timr.Api.Client +{ + /// + /// Useful for tracking server health + /// + public class ApiResponseEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public ApiResponse ApiResponse { get; } + + /// + /// The ApiResponseEventArgs + /// + /// + public ApiResponseEventArgs(ApiResponse apiResponse) + { + ApiResponse = apiResponse; + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/ApiResponse`1.cs b/sdk/dotnet/Timr.Api/Client/ApiResponse`1.cs new file mode 100644 index 0000000..c97a2bb --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/ApiResponse`1.cs @@ -0,0 +1,340 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; + +namespace Timr.Api.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public partial interface IApiResponse + { + /// + /// The IsSuccessStatusCode from the api response + /// + bool IsSuccessStatusCode { get; } + + /// + /// Gets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response. + /// + string RawContent { get; } + + /// + /// The raw binary stream (only set for binary responses) + /// + System.IO.Stream? ContentStream { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + + /// + /// The headers contained in the api response + /// + System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The headers contained in the api response related to the content + /// + System.Net.Http.Headers.HttpContentHeaders ContentHeaders { get; } + + /// + /// The path used when making the request. + /// + string Path { get; } + + /// + /// The reason phrase contained in the api response + /// + string? ReasonPhrase { get; } + + /// + /// The DateTime when the request was sent. + /// + DateTime RequestedAt { get; } + + /// + /// The Uri used when making the request. + /// + Uri? RequestUri { get; } + } + + /// + /// API Response + /// + public partial class ApiResponse : IApiResponse + { + /// + /// Gets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The raw data + /// + public string RawContent { get; protected set; } + + /// + /// The raw binary stream (only set for binary responses) + /// + public System.IO.Stream? ContentStream { get; protected set; } + + /// + /// The IsSuccessStatusCode from the api response + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the api response + /// + public string? ReasonPhrase { get; } + + /// + /// The headers contained in the api response + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The headers contained in the api response related to the content + /// + public System.Net.Http.Headers.HttpContentHeaders ContentHeaders { get; } + + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// The DateTime when the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The path used when making the request. + /// + public string Path { get; } + + /// + /// The Uri used when making the request. + /// + public Uri? RequestUri { get; } + + /// + /// The + /// + protected System.Text.Json.JsonSerializerOptions _jsonSerializerOptions; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + /// + /// + /// + /// + public ApiResponse(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + ContentHeaders = httpResponseMessage.Content.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + RawContent = rawContent; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + /// + /// + /// + /// + public ApiResponse(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + ContentHeaders = httpResponseMessage.Content.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + ContentStream = contentStream; + RawContent = string.Empty; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + } + + /// + /// An interface for responses of type + /// + /// + public interface IBadRequest : IApiResponse + { + /// + /// Deserializes the response if the response is BadRequest + /// + /// + TType BadRequest(); + + /// + /// Returns true if the response is BadRequest and the deserialized response is not null + /// + /// + /// + bool TryBadRequest([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type + /// + /// + public interface IConflict : IApiResponse + { + /// + /// Deserializes the response if the response is Conflict + /// + /// + TType Conflict(); + + /// + /// Returns true if the response is Conflict and the deserialized response is not null + /// + /// + /// + bool TryConflict([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type + /// + /// + public interface IForbidden : IApiResponse + { + /// + /// Deserializes the response if the response is Forbidden + /// + /// + TType Forbidden(); + + /// + /// Returns true if the response is Forbidden and the deserialized response is not null + /// + /// + /// + bool TryForbidden([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type + /// + /// + public interface IOk : IApiResponse + { + /// + /// Deserializes the response if the response is Ok + /// + /// + TType Ok(); + + /// + /// Returns true if the response is Ok and the deserialized response is not null + /// + /// + /// + bool TryOk([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type + /// + /// + public interface IUnprocessableContent : IApiResponse + { + /// + /// Deserializes the response if the response is UnprocessableContent + /// + /// + TType UnprocessableContent(); + + /// + /// Returns true if the response is UnprocessableContent and the deserialized response is not null + /// + /// + /// + bool TryUnprocessableContent([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type + /// + /// + public interface ICreated : IApiResponse + { + /// + /// Deserializes the response if the response is Created + /// + /// + TType Created(); + + /// + /// Returns true if the response is Created and the deserialized response is not null + /// + /// + /// + bool TryCreated([NotNullWhen(true)]out TType? result); + } + + /// + /// An interface for responses of type + /// + /// + public interface INotFound : IApiResponse + { + /// + /// Deserializes the response if the response is NotFound + /// + /// + TType NotFound(); + + /// + /// Returns true if the response is NotFound and the deserialized response is not null + /// + /// + /// + bool TryNotFound([NotNullWhen(true)]out TType? result); + } +} diff --git a/sdk/dotnet/Timr.Api/Client/ClientUtils.cs b/sdk/dotnet/Timr.Api/Client/ClientUtils.cs new file mode 100644 index 0000000..c2e647e --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/ClientUtils.cs @@ -0,0 +1,398 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Timr.Api.Model; +using System.Runtime.CompilerServices; +using System.Net.Http.Headers; + +[assembly: InternalsVisibleTo("Timr.Api.Test")] + +namespace Timr.Api.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static partial class ClientUtils + { + + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object? obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is DateOnly dateOnly) + return dateOnly.ToString(format); + if (obj is bool boolean) + return boolean + ? "true" + : "false"; + if (obj is BreakTimeType breakTimeType) + return BreakTimeTypeValueConverter.ToJsonValue(breakTimeType); + if (obj is BudgetPlanningType budgetPlanningType) + return BudgetPlanningTypeValueConverter.ToJsonValue(budgetPlanningType); + if (obj is BudgetPlanningTypeRequest budgetPlanningTypeRequest) + return BudgetPlanningTypeRequestValueConverter.ToJsonValue(budgetPlanningTypeRequest); + if (obj is CarsSortColumn carsSortColumn) + return CarsSortColumnValueConverter.ToJsonValue(carsSortColumn); + if (obj is DeletedEntrySortColumn deletedEntrySortColumn) + return DeletedEntrySortColumnValueConverter.ToJsonValue(deletedEntrySortColumn); + if (obj is DriveLogCategoriesSortColumn driveLogCategoriesSortColumn) + return DriveLogCategoriesSortColumnValueConverter.ToJsonValue(driveLogCategoriesSortColumn); + if (obj is DriveLogStatus driveLogStatus) + return DriveLogStatusValueConverter.ToJsonValue(driveLogStatus); + if (obj is DriveLogsSortColumn driveLogsSortColumn) + return DriveLogsSortColumnValueConverter.ToJsonValue(driveLogsSortColumn); + if (obj is DurationType durationType) + return DurationTypeValueConverter.ToJsonValue(durationType); + if (obj is DurationUnit durationUnit) + return DurationUnitValueConverter.ToJsonValue(durationUnit); + if (obj is FlexTimeIndicator flexTimeIndicator) + return FlexTimeIndicatorValueConverter.ToJsonValue(flexTimeIndicator); + if (obj is HolidayCalendarsSortColumn holidayCalendarsSortColumn) + return HolidayCalendarsSortColumnValueConverter.ToJsonValue(holidayCalendarsSortColumn); + if (obj is HolidaysSortColumn holidaysSortColumn) + return HolidaysSortColumnValueConverter.ToJsonValue(holidaysSortColumn); + if (obj is Platform platform) + return PlatformValueConverter.ToJsonValue(platform); + if (obj is ProjectTimeStatus projectTimeStatus) + return ProjectTimeStatusValueConverter.ToJsonValue(projectTimeStatus); + if (obj is ProjectTimesSortColumn projectTimesSortColumn) + return ProjectTimesSortColumnValueConverter.ToJsonValue(projectTimesSortColumn); + if (obj is RecordingLockType recordingLockType) + return RecordingLockTypeValueConverter.ToJsonValue(recordingLockType); + if (obj is RecordingModeUser recordingModeUser) + return RecordingModeUserValueConverter.ToJsonValue(recordingModeUser); + if (obj is SortDirection sortDirection) + return SortDirectionValueConverter.ToJsonValue(sortDirection); + if (obj is TaskToLeaderAssignmentsSortColumn taskToLeaderAssignmentsSortColumn) + return TaskToLeaderAssignmentsSortColumnValueConverter.ToJsonValue(taskToLeaderAssignmentsSortColumn); + if (obj is TaskToTeamAssignmentsSortColumn taskToTeamAssignmentsSortColumn) + return TaskToTeamAssignmentsSortColumnValueConverter.ToJsonValue(taskToTeamAssignmentsSortColumn); + if (obj is TaskToUserAssignmentsSortColumn taskToUserAssignmentsSortColumn) + return TaskToUserAssignmentsSortColumnValueConverter.ToJsonValue(taskToUserAssignmentsSortColumn); + if (obj is TasksSortColumn tasksSortColumn) + return TasksSortColumnValueConverter.ToJsonValue(tasksSortColumn); + if (obj is TeamsSortColumn teamsSortColumn) + return TeamsSortColumnValueConverter.ToJsonValue(teamsSortColumn); + if (obj is UsersSortColumn usersSortColumn) + return UsersSortColumnValueConverter.ToJsonValue(usersSortColumn); + if (obj is VacationUnit vacationUnit) + return VacationUnitValueConverter.ToJsonValue(vacationUnit); + if (obj is WorkScheduleModelSortColumn workScheduleModelSortColumn) + return WorkScheduleModelSortColumnValueConverter.ToJsonValue(workScheduleModelSortColumn); + if (obj is WorkScheduleModelType workScheduleModelType) + return WorkScheduleModelTypeValueConverter.ToJsonValue(workScheduleModelType); + if (obj is WorkingTimeDateSpansSortColumn workingTimeDateSpansSortColumn) + return WorkingTimeDateSpansSortColumnValueConverter.ToJsonValue(workingTimeDateSpansSortColumn); + if (obj is WorkingTimeStatus workingTimeStatus) + return WorkingTimeStatusValueConverter.ToJsonValue(workingTimeStatus); + if (obj is WorkingTimeTypeCategory workingTimeTypeCategory) + return WorkingTimeTypeCategoryValueConverter.ToJsonValue(workingTimeTypeCategory); + if (obj is WorkingTimeTypeSubCategory workingTimeTypeSubCategory) + return WorkingTimeTypeSubCategoryValueConverter.ToJsonValue(workingTimeTypeSubCategory); + if (obj is WorkingTimeTypesSortColumn workingTimeTypesSortColumn) + return WorkingTimeTypesSortColumnValueConverter.ToJsonValue(workingTimeTypesSortColumn); + if (obj is WorkingTimesSortColumn workingTimesSortColumn) + return WorkingTimesSortColumnValueConverter.ToJsonValue(workingTimesSortColumn); + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them. + /// + /// The accepts array to select from. + /// The Accept header values to use. + public static IEnumerable SelectHeaderAcceptArray(string[] accepts) + { + if (accepts.Length == 0) + return []; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return [MediaTypeWithQualityHeaderValue.Parse("application/json")]; + + return accepts.Select(MediaTypeWithQualityHeaderValue.Parse); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + [GeneratedRegex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$")] + private static partial Regex JsonRegex(); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex().IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Get the discriminator + /// + /// + /// + /// + /// + public static string? GetDiscriminator(Utf8JsonReader utf8JsonReader, string discriminator) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + if (localVarJsonPropertyName != null && localVarJsonPropertyName.Equals(discriminator)) + return utf8JsonReader.GetString(); + } + } + + throw new JsonException("The specified discriminator was not found."); + } + + /// + /// The base path of the API + /// + public const string BASE_ADDRESS = "https://api.timr.com/v1"; + + /// + /// The scheme of the API + /// + public const string SCHEME = "https"; + + /// + /// The context path of the API + /// + public const string CONTEXT_PATH = "/v1"; + + /// + /// The host of the API + /// + public const string HOST = "api.timr.com"; + + /// + /// The format to use for DateTime serialization + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + } +} diff --git a/sdk/dotnet/Timr.Api/Client/CookieContainer.cs b/sdk/dotnet/Timr.Api/Client/CookieContainer.cs new file mode 100644 index 0000000..d424702 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/CookieContainer.cs @@ -0,0 +1,29 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Timr.Api.Client +{ + /// + /// A class containing a CookieContainer + /// + public sealed class CookieContainer + { + /// + /// The collection of tokens + /// + public System.Net.CookieContainer Value { get; } = new System.Net.CookieContainer(); + } +} diff --git a/sdk/dotnet/Timr.Api/Client/DateOnlyJsonConverter.cs b/sdk/dotnet/Timr.Api/Client/DateOnlyJsonConverter.cs new file mode 100644 index 0000000..7eb73b5 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/DateOnlyJsonConverter.cs @@ -0,0 +1,62 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Timr.Api.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } +} diff --git a/sdk/dotnet/Timr.Api/Client/DateOnlyNullableJsonConverter.cs b/sdk/dotnet/Timr.Api/Client/DateOnlyNullableJsonConverter.cs new file mode 100644 index 0000000..992cf7f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/DateOnlyNullableJsonConverter.cs @@ -0,0 +1,67 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Timr.Api.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/DateTimeJsonConverter.cs b/sdk/dotnet/Timr.Api/Client/DateTimeJsonConverter.cs new file mode 100644 index 0000000..0e3a665 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/DateTimeJsonConverter.cs @@ -0,0 +1,76 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Timr.Api.Client +{ + /// + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateTimeValue.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } +} diff --git a/sdk/dotnet/Timr.Api/Client/DateTimeNullableJsonConverter.cs b/sdk/dotnet/Timr.Api/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 0000000..af03b82 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/DateTimeNullableJsonConverter.cs @@ -0,0 +1,81 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Timr.Api.Client +{ + /// + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + return null; + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime? dateTimeValue, JsonSerializerOptions options) + { + if (dateTimeValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateTimeValue.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/ExceptionEventArgs.cs b/sdk/dotnet/Timr.Api/Client/ExceptionEventArgs.cs new file mode 100644 index 0000000..fac48db --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/ExceptionEventArgs.cs @@ -0,0 +1,34 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; + +namespace Timr.Api.Client +{ + /// + /// Useful for tracking server health + /// + public class ExceptionEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public Exception Exception { get; } + + /// + /// The ExceptionEventArgs + /// + /// + public ExceptionEventArgs(Exception exception) + { + Exception = exception; + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/FileParameter.cs b/sdk/dotnet/Timr.Api/Client/FileParameter.cs new file mode 100644 index 0000000..3762462 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/FileParameter.cs @@ -0,0 +1,51 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +namespace Timr.Api.Client +{ + /// + /// Represents a file to be uploaded as part of a multipart/form-data request. + /// + public sealed class FileParameter + { + /// + /// The file content stream. + /// + public global::System.IO.Stream Content { get; } + + /// + /// The filename sent in the Content-Disposition header. + /// When null the parameter name from the spec is used as a fallback. + /// + public string? FileName { get; } + + /// + /// The MIME type sent in the Content-Type header of the part. + /// Defaults to application/octet-stream. + /// + public string ContentType { get; } + + /// + /// Creates a new . + /// + /// The file content stream. + /// Optional filename for the Content-Disposition header. + /// Optional MIME type for the Content-Type header of the part. Defaults to application/octet-stream. + public FileParameter(global::System.IO.Stream content, string? fileName = null, string contentType = "application/octet-stream") + { + Content = content; + FileName = fileName; + ContentType = contentType; + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/HostConfiguration.cs b/sdk/dotnet/Timr.Api/Client/HostConfiguration.cs new file mode 100644 index 0000000..bd72775 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/HostConfiguration.cs @@ -0,0 +1,358 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Timr.Api.Api; +using Timr.Api.Model; + +namespace Timr.Api.Client +{ + /// + /// Provides hosting configuration for Timr.Api + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + internal bool HttpClientsAdded { get; private set; } + + /// + /// Instantiates the class + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + _jsonOptions.Converters.Add(new AccountsJsonConverter()); + _jsonOptions.Converters.Add(new BreakTimeJsonConverter()); + _jsonOptions.Converters.Add(new BreakTimeAutomaticJsonConverter()); + _jsonOptions.Converters.Add(new BreakTimeBaseJsonConverter()); + _jsonOptions.Converters.Add(new BreakTimeManualJsonConverter()); + _jsonOptions.Converters.Add(new BreakTimeOngoingJsonConverter()); + _jsonOptions.Converters.Add(new BreakTimeTypeJsonConverter()); + _jsonOptions.Converters.Add(new BreakTimeTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new BreakTimeUpdateJsonConverter()); + _jsonOptions.Converters.Add(new BudgetPlanningTypeJsonConverter()); + _jsonOptions.Converters.Add(new BudgetPlanningTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new BudgetPlanningTypeRequestJsonConverter()); + _jsonOptions.Converters.Add(new BudgetPlanningTypeRequestNullableJsonConverter()); + _jsonOptions.Converters.Add(new CarJsonConverter()); + _jsonOptions.Converters.Add(new CarCreateJsonConverter()); + _jsonOptions.Converters.Add(new CarPartialJsonConverter()); + _jsonOptions.Converters.Add(new CarUpdateJsonConverter()); + _jsonOptions.Converters.Add(new CarsPageJsonConverter()); + _jsonOptions.Converters.Add(new CarsSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new CarsSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new DailyWorkScheduleJsonConverter()); + _jsonOptions.Converters.Add(new DeletedEntryPageJsonConverter()); + _jsonOptions.Converters.Add(new DeletedEntryPartialJsonConverter()); + _jsonOptions.Converters.Add(new DeletedEntrySortColumnJsonConverter()); + _jsonOptions.Converters.Add(new DeletedEntrySortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new DeletedEntryWithMetadataJsonConverter()); + _jsonOptions.Converters.Add(new DeletedEntryWithMetadataPageJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogCategoriesPageJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogCategoriesSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogCategoriesSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogCategoryJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogCategoryPartialJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogCreateJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogStatusJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogStatusNullableJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogUpdateJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogUpsertJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogsPageJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogsSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new DriveLogsSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new DurationJsonConverter()); + _jsonOptions.Converters.Add(new DurationTypeJsonConverter()); + _jsonOptions.Converters.Add(new DurationTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new DurationUnitJsonConverter()); + _jsonOptions.Converters.Add(new DurationUnitNullableJsonConverter()); + _jsonOptions.Converters.Add(new ErrorJsonConverter()); + _jsonOptions.Converters.Add(new ErrorEntryJsonConverter()); + _jsonOptions.Converters.Add(new FlexTimeIndicatorJsonConverter()); + _jsonOptions.Converters.Add(new FlexTimeIndicatorNullableJsonConverter()); + _jsonOptions.Converters.Add(new HolidayJsonConverter()); + _jsonOptions.Converters.Add(new HolidayCalendarPartialJsonConverter()); + _jsonOptions.Converters.Add(new HolidayCalendarsPageJsonConverter()); + _jsonOptions.Converters.Add(new HolidayCalendarsSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new HolidayCalendarsSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new HolidaysPageJsonConverter()); + _jsonOptions.Converters.Add(new HolidaysSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new HolidaysSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new LocationJsonConverter()); + _jsonOptions.Converters.Add(new LocationCreateJsonConverter()); + _jsonOptions.Converters.Add(new LocationUpdateJsonConverter()); + _jsonOptions.Converters.Add(new NormalWorkingTimesJsonConverter()); + _jsonOptions.Converters.Add(new OvertimeSurchargeAccountJsonConverter()); + _jsonOptions.Converters.Add(new OvertimeSurchargeAccountsJsonConverter()); + _jsonOptions.Converters.Add(new OvertimeSurchargeRuleJsonConverter()); + _jsonOptions.Converters.Add(new PagingInformationJsonConverter()); + _jsonOptions.Converters.Add(new PlatformJsonConverter()); + _jsonOptions.Converters.Add(new PlatformNullableJsonConverter()); + _jsonOptions.Converters.Add(new ProblemDetailJsonConverter()); + _jsonOptions.Converters.Add(new ProjectTimeJsonConverter()); + _jsonOptions.Converters.Add(new ProjectTimeCreateJsonConverter()); + _jsonOptions.Converters.Add(new ProjectTimeStatusJsonConverter()); + _jsonOptions.Converters.Add(new ProjectTimeStatusNullableJsonConverter()); + _jsonOptions.Converters.Add(new ProjectTimeUpdateJsonConverter()); + _jsonOptions.Converters.Add(new ProjectTimeUpsertJsonConverter()); + _jsonOptions.Converters.Add(new ProjectTimesPageJsonConverter()); + _jsonOptions.Converters.Add(new ProjectTimesSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new ProjectTimesSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new RecordingLockTypeJsonConverter()); + _jsonOptions.Converters.Add(new RecordingLockTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new RecordingModeUserJsonConverter()); + _jsonOptions.Converters.Add(new RecordingModeUserNullableJsonConverter()); + _jsonOptions.Converters.Add(new SortDirectionJsonConverter()); + _jsonOptions.Converters.Add(new SortDirectionNullableJsonConverter()); + _jsonOptions.Converters.Add(new TaskJsonConverter()); + _jsonOptions.Converters.Add(new TaskBaseJsonConverter()); + _jsonOptions.Converters.Add(new TaskCreateJsonConverter()); + _jsonOptions.Converters.Add(new TaskLocationJsonConverter()); + _jsonOptions.Converters.Add(new TaskPartialJsonConverter()); + _jsonOptions.Converters.Add(new TaskReducedJsonConverter()); + _jsonOptions.Converters.Add(new TaskToLeaderAssignmentJsonConverter()); + _jsonOptions.Converters.Add(new TaskToLeaderAssignmentsPageJsonConverter()); + _jsonOptions.Converters.Add(new TaskToLeaderAssignmentsSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new TaskToLeaderAssignmentsSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new TaskToTeamAssignmentJsonConverter()); + _jsonOptions.Converters.Add(new TaskToTeamAssignmentsPageJsonConverter()); + _jsonOptions.Converters.Add(new TaskToTeamAssignmentsSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new TaskToTeamAssignmentsSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new TaskToUserAssignmentJsonConverter()); + _jsonOptions.Converters.Add(new TaskToUserAssignmentUpsertJsonConverter()); + _jsonOptions.Converters.Add(new TaskToUserAssignmentsPageJsonConverter()); + _jsonOptions.Converters.Add(new TaskToUserAssignmentsSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new TaskToUserAssignmentsSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new TaskUpdateJsonConverter()); + _jsonOptions.Converters.Add(new TasksPageJsonConverter()); + _jsonOptions.Converters.Add(new TasksReducedPageJsonConverter()); + _jsonOptions.Converters.Add(new TasksSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new TasksSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new TeamJsonConverter()); + _jsonOptions.Converters.Add(new TeamCreateJsonConverter()); + _jsonOptions.Converters.Add(new TeamPartialJsonConverter()); + _jsonOptions.Converters.Add(new TeamUpdateJsonConverter()); + _jsonOptions.Converters.Add(new TeamsPageJsonConverter()); + _jsonOptions.Converters.Add(new TeamsPartialPageJsonConverter()); + _jsonOptions.Converters.Add(new TeamsSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new TeamsSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new TimeAccountJsonConverter()); + _jsonOptions.Converters.Add(new UserJsonConverter()); + _jsonOptions.Converters.Add(new UserCreateJsonConverter()); + _jsonOptions.Converters.Add(new UserPartialJsonConverter()); + _jsonOptions.Converters.Add(new UserUpdateJsonConverter()); + _jsonOptions.Converters.Add(new UsersPageJsonConverter()); + _jsonOptions.Converters.Add(new UsersPartialPageJsonConverter()); + _jsonOptions.Converters.Add(new UsersSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new UsersSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new VacationAccountJsonConverter()); + _jsonOptions.Converters.Add(new VacationAccountBaseJsonConverter()); + _jsonOptions.Converters.Add(new VacationAccountDaysJsonConverter()); + _jsonOptions.Converters.Add(new VacationAccountMinutesJsonConverter()); + _jsonOptions.Converters.Add(new VacationUnitJsonConverter()); + _jsonOptions.Converters.Add(new VacationUnitNullableJsonConverter()); + _jsonOptions.Converters.Add(new VenuePartialJsonConverter()); + _jsonOptions.Converters.Add(new WaypointJsonConverter()); + _jsonOptions.Converters.Add(new WorkScheduleModelJsonConverter()); + _jsonOptions.Converters.Add(new WorkScheduleModelPartialJsonConverter()); + _jsonOptions.Converters.Add(new WorkScheduleModelSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new WorkScheduleModelSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new WorkScheduleModelTypeJsonConverter()); + _jsonOptions.Converters.Add(new WorkScheduleModelTypeNullableJsonConverter()); + _jsonOptions.Converters.Add(new WorkScheduleModelWeekJsonConverter()); + _jsonOptions.Converters.Add(new WorkScheduleModelsPageJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeCreateJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeDateSpanJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeDateSpanCreateJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeDateSpanPageJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeDateSpanPartialJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeDateSpanUpdateJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeDateSpansSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeDateSpansSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeRulesJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeStatusJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeStatusNullableJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeTypeJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeTypeCategoryJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeTypeCategoryNullableJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeTypePartialJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeTypeSubCategoryJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeTypeSubCategoryNullableJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeTypesPageJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeTypesSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeTypesSortColumnNullableJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeUpdateJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimeUpsertJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimesPageJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimesSortColumnJsonConverter()); + _jsonOptions.Converters.Add(new WorkingTimesSortColumnNullableJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddSingleton(); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + public HostConfiguration AddTimrApiClientHttpClients(Action? builder = null) + { + return AddTimrApiClientHttpClients((Action?)null, builder); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration AddTimrApiClientHttpClients( + Action? client, + Action? builder = null) + { + var wrapped = client != null ? new Action((_, httpClient) => + { + client(httpClient); + }) : null; + return AddTimrApiClientHttpClients(wrapped, builder); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration AddTimrApiClientHttpClients( + Action? client, + Action? builder = null) + { + if (client == null) + client = (_, c) => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); + + List builders = new List(); + + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + builders.Add(_services.AddHttpClient(client)); + + if (builder != null) + foreach (IHttpClientBuilder instance in builders) + builder(instance); + + HttpClientsAdded = true; + + return this; + } + + /// + /// Configures the JsonSerializerSettings + /// + /// + /// + public HostConfiguration ConfigureJsonOptions(Action options) + { + options(_jsonOptions); + + return this; + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + { + return AddTokens(new TTokenBase[]{ token }); + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + { + TokenContainer container = new TokenContainer(tokens); + _services.AddSingleton(services => container); + + return this; + } + + /// + /// Adds a token provider to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration UseProvider() + where TTokenProvider : TokenProvider + where TTokenBase : TokenBase + { + _services.AddSingleton(); + _services.AddSingleton>(services => services.GetRequiredService()); + + return this; + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/JsonSerializerOptionsProvider.cs b/sdk/dotnet/Timr.Api/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 0000000..8e3e812 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,36 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System.Text.Json; + +namespace Timr.Api.Client +{ + /// + /// Provides the JsonSerializerOptions + /// + public class JsonSerializerOptionsProvider + { + /// + /// the JsonSerializerOptions + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/OAuthToken.cs b/sdk/dotnet/Timr.Api/Client/OAuthToken.cs new file mode 100644 index 0000000..9fd4f94 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/OAuthToken.cs @@ -0,0 +1,48 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace Timr.Api.Client +{ + /// + /// A token constructed with OAuth. + /// + public class OAuthToken : TokenBase + { + private string _raw; + + /// + /// Consturcts an OAuthToken object. + /// + /// + /// + public OAuthToken(string value, TimeSpan? timeout = null) : base(timeout) + { + _raw = value; + } + + /// + /// Places the token in the header. + /// + /// + /// + public virtual void UseInHeader(global::System.Net.Http.HttpRequestMessage request, string headerName) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _raw); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/Option.cs b/sdk/dotnet/Timr.Api/Client/Option.cs new file mode 100644 index 0000000..3674e67 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/Option.cs @@ -0,0 +1,54 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + + +namespace Timr.Api.Client +{ + /// + /// A wrapper for operation parameters which are not required + /// + public struct Option + { + /// + /// The value to send to the server + /// + public TType Value { get; } + + /// + /// When true the value will be sent to the server + /// + internal bool IsSet { get; } + + /// + /// A wrapper for operation parameters which are not required + /// + /// + public Option(TType value) + { + IsSet = true; + Value = value; + } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); + } +} \ No newline at end of file diff --git a/sdk/dotnet/Timr.Api/Client/RateLimitProvider`1.cs b/sdk/dotnet/Timr.Api/Client/RateLimitProvider`1.cs new file mode 100644 index 0000000..b92f8ee --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/RateLimitProvider`1.cs @@ -0,0 +1,59 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Timr.Api.Client +{ + /// + /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. + /// + /// + public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase + { + internal Dictionary> AvailableTokens { get; } = new(); + + /// + /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. + /// + /// + public RateLimitProvider(TokenContainer container) + { + foreach(TTokenBase token in container.Tokens) + token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); + + global::System.Threading.Channels.BoundedChannelOptions options = new global::System.Threading.Channels.BoundedChannelOptions(container.Tokens.Count) + { + FullMode = global::System.Threading.Channels.BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(string.Empty, global::System.Threading.Channels.Channel.CreateBounded(options)); + + foreach (var availableToken in AvailableTokens) + foreach(TTokenBase token in container.Tokens) + { + token.TokenBecameAvailable += ((sender) => availableToken.Value.Writer.TryWrite((TTokenBase)sender)); + } + } + + public override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out global::System.Threading.Channels.Channel? tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/TokenBase.cs b/sdk/dotnet/Timr.Api/Client/TokenBase.cs new file mode 100644 index 0000000..4045e0d --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/TokenBase.cs @@ -0,0 +1,86 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; + +namespace Timr.Api.Client +{ + /// + /// The base for all tokens. + /// + public abstract class TokenBase + { + private DateTime _nextAvailable = DateTime.UtcNow; + private readonly object _nextAvailableLock = new object(); + private readonly System.Timers.Timer _timer = new System.Timers.Timer(); + + internal TimeSpan? Timeout { get; set; } + + /// + /// Delegate for token availability notification events. + /// + /// The token that became available. + public delegate void TokenBecameAvailableEventHandler(object sender); + + /// + /// Event raised when a rate-limited token becomes available for use. + /// + public event TokenBecameAvailableEventHandler? TokenBecameAvailable; + + /// + /// Initialize a TokenBase object. + /// + /// + internal TokenBase(TimeSpan? timeout = null) + { + Timeout = timeout; + + if (Timeout != null) + StartTimer(Timeout.Value); + } + + /// + /// Starts the token's timer + /// + /// + internal void StartTimer(TimeSpan timeout) + { + Timeout = timeout; + _timer.Interval = Timeout.Value.TotalMilliseconds; + _timer.Elapsed += OnTimer; + _timer.AutoReset = true; + _timer.Start(); + } + + /// + /// Returns true while the token is rate limited. + /// + public bool IsRateLimited { get { lock (_nextAvailableLock) return _nextAvailable > DateTime.UtcNow; } } + + /// + /// Triggered when the server returns status code TooManyRequests + /// Once triggered the local timeout will be extended an arbitrary length of time. + /// + public void BeginRateLimit() + { + lock(_nextAvailableLock) + _nextAvailable = DateTime.UtcNow.AddSeconds(5); + } + + private void OnTimer(object? sender, System.Timers.ElapsedEventArgs e) + { + if (!IsRateLimited) + TokenBecameAvailable?.Invoke(this); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/TokenContainer`1.cs b/sdk/dotnet/Timr.Api/Client/TokenContainer`1.cs new file mode 100644 index 0000000..577e70f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/TokenContainer`1.cs @@ -0,0 +1,46 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Timr.Api.Client +{ + /// + /// A container for a collection of tokens. + /// + /// + public sealed class TokenContainer where TTokenBase : TokenBase + { + /// + /// The collection of tokens + /// + public List Tokens { get; } = new List(); + + /// + /// Instantiates a TokenContainer + /// + public TokenContainer() + { + } + + /// + /// Instantiates a TokenContainer + /// + /// + public TokenContainer(global::System.Collections.Generic.IEnumerable tokens) + { + Tokens = tokens.ToList(); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Client/TokenProvider`1.cs b/sdk/dotnet/Timr.Api/Client/TokenProvider`1.cs new file mode 100644 index 0000000..799f030 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Client/TokenProvider`1.cs @@ -0,0 +1,25 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; + +namespace Timr.Api.Client +{ + /// + /// A class which will provide tokens. + /// + public abstract class TokenProvider where TTokenBase : TokenBase + { + public abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); + } +} diff --git a/sdk/dotnet/Timr.Api/Extensions/IHostBuilderExtensions.cs b/sdk/dotnet/Timr.Api/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 0000000..029c4e3 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,44 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Timr.Api.Client; + +namespace Timr.Api.Extensions +{ + /// + /// Extension methods for IHostBuilder + /// + public static class IHostBuilderExtensions + { + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureTimrApiClient(this IHostBuilder builder, Action options) + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddTimrApiClient(services, config); + }); + + return builder; + } + } +} diff --git a/sdk/dotnet/Timr.Api/Extensions/IHttpClientBuilderExtensions.cs b/sdk/dotnet/Timr.Api/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 0000000..28d9b7a --- /dev/null +++ b/sdk/dotnet/Timr.Api/Extensions/IHttpClientBuilderExtensions.cs @@ -0,0 +1,80 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly; + +namespace Timr.Api.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + public static class IHttpClientBuilderExtensions + { + /// + /// Adds a Polly retry policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries) + { + client.AddPolicyHandler(RetryPolicy(retries)); + + return client; + } + + /// + /// Adds a Polly timeout policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout) + { + client.AddPolicyHandler(TimeoutPolicy(timeout)); + + return client; + } + + /// + /// Adds a Polly circuit breaker to your clients. + /// + /// + /// + /// + /// + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak)); + + return client; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(retries); + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak); + } +} diff --git a/sdk/dotnet/Timr.Api/Extensions/IServiceCollectionExtensions.cs b/sdk/dotnet/Timr.Api/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 0000000..83b8c34 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,64 @@ +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Timr.Api.Client; + +namespace Timr.Api.Extensions +{ + /// + /// Extension methods for IServiceCollection + /// + public static class IServiceCollectionExtensions + { + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddTimrApiClient(this IServiceCollection services, Action options) + { + HostConfiguration config = new(services); + options(config); + AddTimrApiClient(services, config); + } + + internal static void AddTimrApiClient(IServiceCollection services, HostConfiguration host) + { + if (!host.HttpClientsAdded) + host.AddTimrApiClientHttpClients(); + + services.AddSingleton(); + + // ensure that a token provider was provided for this token type + // if not, default to RateLimitProvider + var containerServices = services.Where(s => s.ServiceType.IsGenericType && + s.ServiceType.GetGenericTypeDefinition().IsAssignableFrom(typeof(TokenContainer<>))).ToArray(); + + foreach(var containerService in containerServices) + { + var tokenType = containerService.ServiceType.GenericTypeArguments[0]; + + var provider = services.FirstOrDefault(s => s.ServiceType.IsAssignableFrom(typeof(TokenProvider<>).MakeGenericType(tokenType))); + + if (provider == null) + { + services.AddSingleton(typeof(RateLimitProvider<>).MakeGenericType(tokenType)); + services.AddSingleton(typeof(TokenProvider<>).MakeGenericType(tokenType), + s => s.GetRequiredService(typeof(RateLimitProvider<>).MakeGenericType(tokenType))); + } + } + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Accounts.cs b/sdk/dotnet/Timr.Api/Model/Accounts.cs new file mode 100644 index 0000000..d8d2109 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Accounts.cs @@ -0,0 +1,252 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Accounts + /// + public partial class Accounts : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// date of last balance + /// timeAccount + /// overtimeSurchargeAccounts + /// vacationAccount + [JsonConstructor] + public Accounts(DateOnly? lastBalanceDate = default, Option timeAccount = default, Option?> overtimeSurchargeAccounts = default, Option vacationAccount = default) + { + LastBalanceDate = lastBalanceDate; + TimeAccountOption = timeAccount; + OvertimeSurchargeAccountsOption = overtimeSurchargeAccounts; + VacationAccountOption = vacationAccount; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// date of last balance + /// + /// date of last balance + [JsonPropertyName("last_balance_date")] + public DateOnly? LastBalanceDate { get; set; } + + /// + /// Used to track the state of TimeAccount + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option TimeAccountOption { get; private set; } + + /// + /// Gets or Sets TimeAccount + /// + [JsonPropertyName("time_account")] + public TimeAccount? TimeAccount { get { return this.TimeAccountOption.Value; } set { this.TimeAccountOption = new(value); } } + + /// + /// Used to track the state of OvertimeSurchargeAccounts + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> OvertimeSurchargeAccountsOption { get; private set; } + + /// + /// Gets or Sets OvertimeSurchargeAccounts + /// + [JsonPropertyName("overtime_surcharge_accounts")] + public List? OvertimeSurchargeAccounts { get { return this.OvertimeSurchargeAccountsOption.Value; } set { this.OvertimeSurchargeAccountsOption = new(value); } } + + /// + /// Used to track the state of VacationAccount + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option VacationAccountOption { get; private set; } + + /// + /// Gets or Sets VacationAccount + /// + [JsonPropertyName("vacation_account")] + public VacationAccount? VacationAccount { get { return this.VacationAccountOption.Value; } set { this.VacationAccountOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Accounts {\n"); + sb.Append(" LastBalanceDate: ").Append(LastBalanceDate).Append("\n"); + sb.Append(" TimeAccount: ").Append(TimeAccount).Append("\n"); + sb.Append(" OvertimeSurchargeAccounts: ").Append(OvertimeSurchargeAccounts).Append("\n"); + sb.Append(" VacationAccount: ").Append(VacationAccount).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class AccountsJsonConverter : JsonConverter + { + /// + /// The format to use to serialize LastBalanceDate + /// + public static string LastBalanceDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Accounts Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option lastBalanceDate = default; + Option timeAccount = default; + Option?> overtimeSurchargeAccounts = default; + Option vacationAccount = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "last_balance_date": + lastBalanceDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "time_account": + timeAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "overtime_surcharge_accounts": + overtimeSurchargeAccounts = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "vacation_account": + vacationAccount = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!lastBalanceDate.IsSet) + throw new ArgumentException("Property is required for class Accounts.", nameof(lastBalanceDate)); + + return new Accounts(lastBalanceDate.Value!, timeAccount, overtimeSurchargeAccounts, vacationAccount); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Accounts accounts, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, accounts, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Accounts accounts, JsonSerializerOptions jsonSerializerOptions) + { + if (accounts.LastBalanceDate != null) + writer.WriteString("last_balance_date", accounts.LastBalanceDate.Value.ToString(LastBalanceDateFormat)); + else + writer.WriteNull("last_balance_date"); + + if (accounts.TimeAccountOption.IsSet) + if (accounts.TimeAccountOption.Value != null) + { + writer.WritePropertyName("time_account"); + JsonSerializer.Serialize(writer, accounts.TimeAccount, jsonSerializerOptions); + } + else + writer.WriteNull("time_account"); + if (accounts.OvertimeSurchargeAccountsOption.IsSet) + if (accounts.OvertimeSurchargeAccountsOption.Value != null) + { + writer.WritePropertyName("overtime_surcharge_accounts"); + JsonSerializer.Serialize(writer, accounts.OvertimeSurchargeAccounts, jsonSerializerOptions); + } + else + writer.WriteNull("overtime_surcharge_accounts"); + if (accounts.VacationAccountOption.IsSet) + if (accounts.VacationAccountOption.Value != null) + { + writer.WritePropertyName("vacation_account"); + JsonSerializer.Serialize(writer, accounts.VacationAccount, jsonSerializerOptions); + } + else + writer.WriteNull("vacation_account"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/BreakTime.cs b/sdk/dotnet/Timr.Api/Model/BreakTime.cs new file mode 100644 index 0000000..e3b5f1a --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/BreakTime.cs @@ -0,0 +1,266 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// BreakTime + /// + public partial class BreakTime : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public BreakTime(BreakTimeManual breakTimeManual) + { + BreakTimeManual = breakTimeManual; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BreakTime(BreakTimeOngoing breakTimeOngoing) + { + BreakTimeOngoing = breakTimeOngoing; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BreakTime(BreakTimeAutomatic breakTimeAutomatic) + { + BreakTimeAutomatic = breakTimeAutomatic; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets BreakTimeManual + /// + public BreakTimeManual? BreakTimeManual { get; set; } + + /// + /// Gets or Sets BreakTimeOngoing + /// + public BreakTimeOngoing? BreakTimeOngoing { get; set; } + + /// + /// Gets or Sets BreakTimeAutomatic + /// + public BreakTimeAutomatic? BreakTimeAutomatic { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BreakTime {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BreakTimeJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override BreakTime Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + + BreakTimeAutomatic? breakTimeAutomatic = null; + BreakTimeManual? breakTimeManual = null; + BreakTimeOngoing? breakTimeOngoing = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("type") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("automatic") ?? false) + { + Utf8JsonReader utf8JsonReaderBreakTimeAutomatic = utf8JsonReader; + breakTimeAutomatic = JsonSerializer.Deserialize(ref utf8JsonReaderBreakTimeAutomatic, jsonSerializerOptions); + } + if (discriminator?.Equals("manual") ?? false) + { + Utf8JsonReader utf8JsonReaderBreakTimeManual = utf8JsonReader; + breakTimeManual = JsonSerializer.Deserialize(ref utf8JsonReaderBreakTimeManual, jsonSerializerOptions); + } + if (discriminator?.Equals("ongoing") ?? false) + { + Utf8JsonReader utf8JsonReaderBreakTimeOngoing = utf8JsonReader; + breakTimeOngoing = JsonSerializer.Deserialize(ref utf8JsonReaderBreakTimeOngoing, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(BreakTimeTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BreakTime.", nameof(type)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class BreakTime."); + + if (breakTimeAutomatic != null) + return new BreakTime(breakTimeAutomatic); + + if (breakTimeManual != null) + return new BreakTime(breakTimeManual); + + if (breakTimeOngoing != null) + return new BreakTime(breakTimeOngoing); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BreakTime breakTime, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (breakTime.BreakTimeManual != null) + { + BreakTimeManualJsonConverter breakTimeManualJsonConverter = (BreakTimeManualJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(breakTime.BreakTimeManual.GetType())); + breakTimeManualJsonConverter.WriteProperties(writer, breakTime.BreakTimeManual, jsonSerializerOptions); + } + + if (breakTime.BreakTimeOngoing != null) + { + BreakTimeOngoingJsonConverter breakTimeOngoingJsonConverter = (BreakTimeOngoingJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(breakTime.BreakTimeOngoing.GetType())); + breakTimeOngoingJsonConverter.WriteProperties(writer, breakTime.BreakTimeOngoing, jsonSerializerOptions); + } + + if (breakTime.BreakTimeAutomatic != null) + { + BreakTimeAutomaticJsonConverter breakTimeAutomaticJsonConverter = (BreakTimeAutomaticJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(breakTime.BreakTimeAutomatic.GetType())); + breakTimeAutomaticJsonConverter.WriteProperties(writer, breakTime.BreakTimeAutomatic, jsonSerializerOptions); + } + + WriteProperties(writer, breakTime, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BreakTime breakTime, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/BreakTimeAutomatic.cs b/sdk/dotnet/Timr.Api/Model/BreakTimeAutomatic.cs new file mode 100644 index 0000000..df162ad --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/BreakTimeAutomatic.cs @@ -0,0 +1,243 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// BreakTimeAutomatic + /// + public partial class BreakTimeAutomatic : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// type + /// Duration of break in minutes + /// RFC 3339 date-time (ISO-8601) + /// RFC 3339 date-time (ISO-8601) + [JsonConstructor] + public BreakTimeAutomatic(BreakTimeType type, int durationMinutes, DateTimeOffset? start = default, DateTimeOffset? end = default) + { + Type = type; + DurationMinutes = durationMinutes; + Start = start; + End = end; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Type + /// + [JsonPropertyName("type")] + public BreakTimeType Type { get; set; } + + /// + /// Duration of break in minutes + /// + /// Duration of break in minutes + /* 15 */ + [JsonPropertyName("duration_minutes")] + public int DurationMinutes { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset? Start { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BreakTimeAutomatic {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" DurationMinutes: ").Append(DurationMinutes).Append("\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BreakTimeAutomaticJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override BreakTimeAutomatic Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option durationMinutes = default; + Option start = default; + Option end = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(BreakTimeTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + case "duration_minutes": + durationMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BreakTimeAutomatic.", nameof(type)); + + if (!durationMinutes.IsSet) + throw new ArgumentException("Property is required for class BreakTimeAutomatic.", nameof(durationMinutes)); + + if (!start.IsSet) + throw new ArgumentException("Property is required for class BreakTimeAutomatic.", nameof(start)); + + if (!end.IsSet) + throw new ArgumentException("Property is required for class BreakTimeAutomatic.", nameof(end)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class BreakTimeAutomatic."); + + if (durationMinutes.IsSet && durationMinutes.Value == null) + throw new ArgumentNullException(nameof(durationMinutes), "Property is not nullable for class BreakTimeAutomatic."); + + return new BreakTimeAutomatic(type.Value!.Value!, durationMinutes.Value!.Value!, start.Value!, end.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BreakTimeAutomatic breakTimeAutomatic, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, breakTimeAutomatic, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BreakTimeAutomatic breakTimeAutomatic, JsonSerializerOptions jsonSerializerOptions) + { + var typeRawValue = BreakTimeTypeValueConverter.ToJsonValue(breakTimeAutomatic.Type); + writer.WriteString("type", typeRawValue); + + writer.WriteNumber("duration_minutes", breakTimeAutomatic.DurationMinutes); + + if (breakTimeAutomatic.Start != null) + writer.WriteString("start", breakTimeAutomatic.Start.Value.ToString(StartFormat)); + else + writer.WriteNull("start"); + + if (breakTimeAutomatic.End != null) + writer.WriteString("end", breakTimeAutomatic.End.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/BreakTimeBase.cs b/sdk/dotnet/Timr.Api/Model/BreakTimeBase.cs new file mode 100644 index 0000000..f1b053b --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/BreakTimeBase.cs @@ -0,0 +1,164 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Members shared by every kind of break time, including the discriminator. + /// + public partial class BreakTimeBase : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// type + [JsonConstructor] + public BreakTimeBase(BreakTimeType type) + { + Type = type; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Type + /// + [JsonPropertyName("type")] + public BreakTimeType Type { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BreakTimeBase {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BreakTimeBaseJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override BreakTimeBase Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(BreakTimeTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BreakTimeBase.", nameof(type)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class BreakTimeBase."); + + return new BreakTimeBase(type.Value!.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BreakTimeBase breakTimeBase, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, breakTimeBase, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BreakTimeBase breakTimeBase, JsonSerializerOptions jsonSerializerOptions) + { + var typeRawValue = BreakTimeTypeValueConverter.ToJsonValue(breakTimeBase.Type); + writer.WriteString("type", typeRawValue); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/BreakTimeManual.cs b/sdk/dotnet/Timr.Api/Model/BreakTimeManual.cs new file mode 100644 index 0000000..470aea1 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/BreakTimeManual.cs @@ -0,0 +1,253 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// BreakTimeManual + /// + public partial class BreakTimeManual : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// type + /// Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. + /// start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + /// start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + [JsonConstructor] + public BreakTimeManual(BreakTimeType type, int durationMinutes, Option start = default, Option end = default) + { + Type = type; + DurationMinutes = durationMinutes; + StartOption = start; + EndOption = end; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Type + /// + [JsonPropertyName("type")] + public BreakTimeType Type { get; set; } + + /// + /// Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. + /// + /// Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. + /* 20 */ + [JsonPropertyName("duration_minutes")] + public int DurationMinutes { get; set; } + + /// + /// Used to track the state of Start + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartOption { get; private set; } + + /// + /// start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + /// + /// start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset? Start { get { return this.StartOption.Value; } set { this.StartOption = new(value); } } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + /// + /// start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BreakTimeManual {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" DurationMinutes: ").Append(DurationMinutes).Append("\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BreakTimeManualJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override BreakTimeManual Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option durationMinutes = default; + Option start = default; + Option end = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(BreakTimeTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + case "duration_minutes": + durationMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BreakTimeManual.", nameof(type)); + + if (!durationMinutes.IsSet) + throw new ArgumentException("Property is required for class BreakTimeManual.", nameof(durationMinutes)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class BreakTimeManual."); + + if (durationMinutes.IsSet && durationMinutes.Value == null) + throw new ArgumentNullException(nameof(durationMinutes), "Property is not nullable for class BreakTimeManual."); + + return new BreakTimeManual(type.Value!.Value!, durationMinutes.Value!.Value!, start, end); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BreakTimeManual breakTimeManual, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, breakTimeManual, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BreakTimeManual breakTimeManual, JsonSerializerOptions jsonSerializerOptions) + { + var typeRawValue = BreakTimeTypeValueConverter.ToJsonValue(breakTimeManual.Type); + writer.WriteString("type", typeRawValue); + + writer.WriteNumber("duration_minutes", breakTimeManual.DurationMinutes); + + if (breakTimeManual.StartOption.IsSet) + if (breakTimeManual.StartOption.Value != null) + writer.WriteString("start", breakTimeManual.StartOption.Value!.Value.ToString(StartFormat)); + else + writer.WriteNull("start"); + + if (breakTimeManual.EndOption.IsSet) + if (breakTimeManual.EndOption.Value != null) + writer.WriteString("end", breakTimeManual.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/BreakTimeOngoing.cs b/sdk/dotnet/Timr.Api/Model/BreakTimeOngoing.cs new file mode 100644 index 0000000..d60b252 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/BreakTimeOngoing.cs @@ -0,0 +1,192 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// BreakTimeOngoing + /// + public partial class BreakTimeOngoing : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// type + /// RFC 3339 date-time (ISO-8601) + [JsonConstructor] + public BreakTimeOngoing(BreakTimeType type, DateTimeOffset start) + { + Type = type; + Start = start; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Type + /// + [JsonPropertyName("type")] + public BreakTimeType Type { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset Start { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BreakTimeOngoing {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BreakTimeOngoingJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override BreakTimeOngoing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option start = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(BreakTimeTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BreakTimeOngoing.", nameof(type)); + + if (!start.IsSet) + throw new ArgumentException("Property is required for class BreakTimeOngoing.", nameof(start)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class BreakTimeOngoing."); + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class BreakTimeOngoing."); + + return new BreakTimeOngoing(type.Value!.Value!, start.Value!.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BreakTimeOngoing breakTimeOngoing, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, breakTimeOngoing, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BreakTimeOngoing breakTimeOngoing, JsonSerializerOptions jsonSerializerOptions) + { + var typeRawValue = BreakTimeTypeValueConverter.ToJsonValue(breakTimeOngoing.Type); + writer.WriteString("type", typeRawValue); + + writer.WriteString("start", breakTimeOngoing.Start.ToString(StartFormat)); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/BreakTimeType.cs b/sdk/dotnet/Timr.Api/Model/BreakTimeType.cs new file mode 100644 index 0000000..04b6c6d --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/BreakTimeType.cs @@ -0,0 +1,191 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Kind of break. `manual` was entered by the user, `automatic` was deducted by timr, `ongoing` is a break that has started and not yet ended. + /// + /// Kind of break. `manual` was entered by the user, `automatic` was deducted by timr, `ongoing` is a break that has started and not yet ended. + public enum BreakTimeType + { + /// + /// Enum Manual for value: manual + /// + Manual = 1, + + /// + /// Enum Ongoing for value: ongoing + /// + Ongoing = 2, + + /// + /// Enum Automatic for value: automatic + /// + Automatic = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class BreakTimeTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static BreakTimeType FromString(string value) + { + if (value.Equals("manual")) + return BreakTimeType.Manual; + + if (value.Equals("ongoing")) + return BreakTimeType.Ongoing; + + if (value.Equals("automatic")) + return BreakTimeType.Automatic; + + throw new NotImplementedException($"Could not convert value to type BreakTimeType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static BreakTimeType? FromStringOrDefault(string value) + { + if (value.Equals("manual")) + return BreakTimeType.Manual; + + if (value.Equals("ongoing")) + return BreakTimeType.Ongoing; + + if (value.Equals("automatic")) + return BreakTimeType.Automatic; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(BreakTimeType value) + { + if (value == BreakTimeType.Manual) + return "manual"; + + if (value == BreakTimeType.Ongoing) + return "ongoing"; + + if (value == BreakTimeType.Automatic) + return "automatic"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class BreakTimeTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override BreakTimeType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + BreakTimeType? result = rawValue == null + ? null + : BreakTimeTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the BreakTimeType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BreakTimeType breakTimeType, JsonSerializerOptions options) + { + writer.WriteStringValue(BreakTimeTypeValueConverter.ToJsonValue(breakTimeType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class BreakTimeTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a BreakTimeType from the Json object + /// + /// + /// + /// + /// + public override BreakTimeType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + BreakTimeType? result = rawValue == null + ? null + : BreakTimeTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the BreakTimeType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BreakTimeType? breakTimeType, JsonSerializerOptions options) + { + writer.WriteStringValue(breakTimeType.HasValue ? BreakTimeTypeValueConverter.ToJsonValue(breakTimeType.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/BreakTimeUpdate.cs b/sdk/dotnet/Timr.Api/Model/BreakTimeUpdate.cs new file mode 100644 index 0000000..e5049d2 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/BreakTimeUpdate.cs @@ -0,0 +1,236 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// BreakTimeUpdate + /// + public partial class BreakTimeUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public BreakTimeUpdate(BreakTimeManual breakTimeManual) + { + BreakTimeManual = breakTimeManual; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public BreakTimeUpdate(BreakTimeOngoing breakTimeOngoing) + { + BreakTimeOngoing = breakTimeOngoing; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets BreakTimeManual + /// + public BreakTimeManual? BreakTimeManual { get; set; } + + /// + /// Gets or Sets BreakTimeOngoing + /// + public BreakTimeOngoing? BreakTimeOngoing { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class BreakTimeUpdate {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class BreakTimeUpdateJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override BreakTimeUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + + BreakTimeManual? breakTimeManual = null; + BreakTimeOngoing? breakTimeOngoing = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("type") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("manual") ?? false) + { + Utf8JsonReader utf8JsonReaderBreakTimeManual = utf8JsonReader; + breakTimeManual = JsonSerializer.Deserialize(ref utf8JsonReaderBreakTimeManual, jsonSerializerOptions); + } + if (discriminator?.Equals("ongoing") ?? false) + { + Utf8JsonReader utf8JsonReaderBreakTimeOngoing = utf8JsonReader; + breakTimeOngoing = JsonSerializer.Deserialize(ref utf8JsonReaderBreakTimeOngoing, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(BreakTimeTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class BreakTimeUpdate.", nameof(type)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class BreakTimeUpdate."); + + if (breakTimeManual != null) + return new BreakTimeUpdate(breakTimeManual); + + if (breakTimeOngoing != null) + return new BreakTimeUpdate(breakTimeOngoing); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BreakTimeUpdate breakTimeUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (breakTimeUpdate.BreakTimeManual != null) + { + BreakTimeManualJsonConverter breakTimeManualJsonConverter = (BreakTimeManualJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(breakTimeUpdate.BreakTimeManual.GetType())); + breakTimeManualJsonConverter.WriteProperties(writer, breakTimeUpdate.BreakTimeManual, jsonSerializerOptions); + } + + if (breakTimeUpdate.BreakTimeOngoing != null) + { + BreakTimeOngoingJsonConverter breakTimeOngoingJsonConverter = (BreakTimeOngoingJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(breakTimeUpdate.BreakTimeOngoing.GetType())); + breakTimeOngoingJsonConverter.WriteProperties(writer, breakTimeUpdate.BreakTimeOngoing, jsonSerializerOptions); + } + + WriteProperties(writer, breakTimeUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, BreakTimeUpdate breakTimeUpdate, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/BudgetPlanningType.cs b/sdk/dotnet/Timr.Api/Model/BudgetPlanningType.cs new file mode 100644 index 0000000..6ccddfd --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/BudgetPlanningType.cs @@ -0,0 +1,205 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set for the remaining two types all budget properties are supported + /// + /// corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set for the remaining two types all budget properties are supported + public enum BudgetPlanningType + { + /// + /// Enum None for value: none + /// + None = 1, + + /// + /// Enum TaskHourlyRate for value: task_hourly_rate + /// + TaskHourlyRate = 2, + + /// + /// Enum UserHourlyRate for value: user_hourly_rate + /// + UserHourlyRate = 3, + + /// + /// Enum FixedPrice for value: fixed_price + /// + FixedPrice = 4 + } + + /// + /// Converts to and from the JSON value + /// + public static class BudgetPlanningTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static BudgetPlanningType FromString(string value) + { + if (value.Equals("none")) + return BudgetPlanningType.None; + + if (value.Equals("task_hourly_rate")) + return BudgetPlanningType.TaskHourlyRate; + + if (value.Equals("user_hourly_rate")) + return BudgetPlanningType.UserHourlyRate; + + if (value.Equals("fixed_price")) + return BudgetPlanningType.FixedPrice; + + throw new NotImplementedException($"Could not convert value to type BudgetPlanningType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static BudgetPlanningType? FromStringOrDefault(string value) + { + if (value.Equals("none")) + return BudgetPlanningType.None; + + if (value.Equals("task_hourly_rate")) + return BudgetPlanningType.TaskHourlyRate; + + if (value.Equals("user_hourly_rate")) + return BudgetPlanningType.UserHourlyRate; + + if (value.Equals("fixed_price")) + return BudgetPlanningType.FixedPrice; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(BudgetPlanningType value) + { + if (value == BudgetPlanningType.None) + return "none"; + + if (value == BudgetPlanningType.TaskHourlyRate) + return "task_hourly_rate"; + + if (value == BudgetPlanningType.UserHourlyRate) + return "user_hourly_rate"; + + if (value == BudgetPlanningType.FixedPrice) + return "fixed_price"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class BudgetPlanningTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override BudgetPlanningType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + BudgetPlanningType? result = rawValue == null + ? null + : BudgetPlanningTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the BudgetPlanningType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BudgetPlanningType budgetPlanningType, JsonSerializerOptions options) + { + writer.WriteStringValue(BudgetPlanningTypeValueConverter.ToJsonValue(budgetPlanningType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class BudgetPlanningTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a BudgetPlanningType from the Json object + /// + /// + /// + /// + /// + public override BudgetPlanningType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + BudgetPlanningType? result = rawValue == null + ? null + : BudgetPlanningTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the BudgetPlanningType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BudgetPlanningType? budgetPlanningType, JsonSerializerOptions options) + { + writer.WriteStringValue(budgetPlanningType.HasValue ? BudgetPlanningTypeValueConverter.ToJsonValue(budgetPlanningType.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/BudgetPlanningTypeRequest.cs b/sdk/dotnet/Timr.Api/Model/BudgetPlanningTypeRequest.cs new file mode 100644 index 0000000..60a13b5 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/BudgetPlanningTypeRequest.cs @@ -0,0 +1,219 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set * inherited: budget settings are inherited from the parent task for the remaining two types all budget properties are supported + /// + /// corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set * inherited: budget settings are inherited from the parent task for the remaining two types all budget properties are supported + public enum BudgetPlanningTypeRequest + { + /// + /// Enum None for value: none + /// + None = 1, + + /// + /// Enum TaskHourlyRate for value: task_hourly_rate + /// + TaskHourlyRate = 2, + + /// + /// Enum UserHourlyRate for value: user_hourly_rate + /// + UserHourlyRate = 3, + + /// + /// Enum FixedPrice for value: fixed_price + /// + FixedPrice = 4, + + /// + /// Enum Inherited for value: inherited + /// + Inherited = 5 + } + + /// + /// Converts to and from the JSON value + /// + public static class BudgetPlanningTypeRequestValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static BudgetPlanningTypeRequest FromString(string value) + { + if (value.Equals("none")) + return BudgetPlanningTypeRequest.None; + + if (value.Equals("task_hourly_rate")) + return BudgetPlanningTypeRequest.TaskHourlyRate; + + if (value.Equals("user_hourly_rate")) + return BudgetPlanningTypeRequest.UserHourlyRate; + + if (value.Equals("fixed_price")) + return BudgetPlanningTypeRequest.FixedPrice; + + if (value.Equals("inherited")) + return BudgetPlanningTypeRequest.Inherited; + + throw new NotImplementedException($"Could not convert value to type BudgetPlanningTypeRequest: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static BudgetPlanningTypeRequest? FromStringOrDefault(string value) + { + if (value.Equals("none")) + return BudgetPlanningTypeRequest.None; + + if (value.Equals("task_hourly_rate")) + return BudgetPlanningTypeRequest.TaskHourlyRate; + + if (value.Equals("user_hourly_rate")) + return BudgetPlanningTypeRequest.UserHourlyRate; + + if (value.Equals("fixed_price")) + return BudgetPlanningTypeRequest.FixedPrice; + + if (value.Equals("inherited")) + return BudgetPlanningTypeRequest.Inherited; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(BudgetPlanningTypeRequest value) + { + if (value == BudgetPlanningTypeRequest.None) + return "none"; + + if (value == BudgetPlanningTypeRequest.TaskHourlyRate) + return "task_hourly_rate"; + + if (value == BudgetPlanningTypeRequest.UserHourlyRate) + return "user_hourly_rate"; + + if (value == BudgetPlanningTypeRequest.FixedPrice) + return "fixed_price"; + + if (value == BudgetPlanningTypeRequest.Inherited) + return "inherited"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class BudgetPlanningTypeRequestJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override BudgetPlanningTypeRequest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + BudgetPlanningTypeRequest? result = rawValue == null + ? null + : BudgetPlanningTypeRequestValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the BudgetPlanningTypeRequest to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BudgetPlanningTypeRequest budgetPlanningTypeRequest, JsonSerializerOptions options) + { + writer.WriteStringValue(BudgetPlanningTypeRequestValueConverter.ToJsonValue(budgetPlanningTypeRequest).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class BudgetPlanningTypeRequestNullableJsonConverter : JsonConverter + { + /// + /// Returns a BudgetPlanningTypeRequest from the Json object + /// + /// + /// + /// + /// + public override BudgetPlanningTypeRequest? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + BudgetPlanningTypeRequest? result = rawValue == null + ? null + : BudgetPlanningTypeRequestValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the BudgetPlanningTypeRequest to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, BudgetPlanningTypeRequest? budgetPlanningTypeRequest, JsonSerializerOptions options) + { + writer.WriteStringValue(budgetPlanningTypeRequest.HasValue ? BudgetPlanningTypeRequestValueConverter.ToJsonValue(budgetPlanningTypeRequest.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Car.cs b/sdk/dotnet/Timr.Api/Model/Car.cs new file mode 100644 index 0000000..b34a8ac --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Car.cs @@ -0,0 +1,285 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// A vehicle identified by `name` and license `plate`. `usable` says whether it can currently be selected. + /// + public partial class Car : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// plate + /// usable + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// metadata + [JsonConstructor] + public Car(string id, string name, string plate, bool usable, string? externalId = default, Option?> metadata = default) + { + Id = id; + Name = name; + Plate = plate; + Usable = usable; + ExternalId = externalId; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets Plate + /// + [JsonPropertyName("plate")] + public string Plate { get; set; } + + /// + /// Gets or Sets Usable + /// + [JsonPropertyName("usable")] + public bool Usable { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Car {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Plate: ").Append(Plate).Append("\n"); + sb.Append(" Usable: ").Append(Usable).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CarJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Car Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option plate = default; + Option usable = default; + Option externalId = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "plate": + plate = new Option(utf8JsonReader.GetString()!); + break; + case "usable": + usable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class Car.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class Car.", nameof(name)); + + if (!plate.IsSet) + throw new ArgumentException("Property is required for class Car.", nameof(plate)); + + if (!usable.IsSet) + throw new ArgumentException("Property is required for class Car.", nameof(usable)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class Car.", nameof(externalId)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Car."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Car."); + + if (plate.IsSet && plate.Value == null) + throw new ArgumentNullException(nameof(plate), "Property is not nullable for class Car."); + + if (usable.IsSet && usable.Value == null) + throw new ArgumentNullException(nameof(usable), "Property is not nullable for class Car."); + + return new Car(id.Value!, name.Value!, plate.Value!, usable.Value!.Value!, externalId.Value!, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Car car, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, car, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Car car, JsonSerializerOptions jsonSerializerOptions) + { + if (car.Id == null) + throw new ArgumentNullException(nameof(car.Id), "Property is required for class Car."); + + if (car.Name == null) + throw new ArgumentNullException(nameof(car.Name), "Property is required for class Car."); + + if (car.Plate == null) + throw new ArgumentNullException(nameof(car.Plate), "Property is required for class Car."); + + writer.WriteString("id", car.Id); + + writer.WriteString("name", car.Name); + + writer.WriteString("plate", car.Plate); + + writer.WriteBoolean("usable", car.Usable); + + if (car.ExternalId != null) + writer.WriteString("external_id", car.ExternalId); + else + writer.WriteNull("external_id"); + + if (car.MetadataOption.IsSet) + if (car.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, car.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/CarCreate.cs b/sdk/dotnet/Timr.Api/Model/CarCreate.cs new file mode 100644 index 0000000..6059164 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/CarCreate.cs @@ -0,0 +1,294 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// CarCreate + /// + public partial class CarCreate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + /// plate + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// usable + /// metadata + [JsonConstructor] + public CarCreate(string name, string plate, Option externalId = default, Option usable = default, Option?> metadata = default) + { + Name = name; + Plate = plate; + ExternalIdOption = externalId; + UsableOption = usable; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets Plate + /// + [JsonPropertyName("plate")] + public string Plate { get; set; } + + /// + /// Used to track the state of ExternalId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ExternalIdOption { get; private set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get { return this.ExternalIdOption.Value; } set { this.ExternalIdOption = new(value); } } + + /// + /// Used to track the state of Usable + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option UsableOption { get; private set; } + + /// + /// Gets or Sets Usable + /// + [JsonPropertyName("usable")] + public bool? Usable { get { return this.UsableOption.Value; } set { this.UsableOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CarCreate {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Plate: ").Append(Plate).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Usable: ").Append(Usable).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Name (string) maxLength + if (this.Name != null && this.Name.Length > 191) + { + yield return new ValidationResult("Invalid value for Name, length must be less than 191.", new [] { "Name" }); + } + + // Name (string) minLength + if (this.Name != null && this.Name.Length < 1) + { + yield return new ValidationResult("Invalid value for Name, length must be greater than 1.", new [] { "Name" }); + } + + // Plate (string) maxLength + if (this.Plate != null && this.Plate.Length > 191) + { + yield return new ValidationResult("Invalid value for Plate, length must be less than 191.", new [] { "Plate" }); + } + + // Plate (string) minLength + if (this.Plate != null && this.Plate.Length < 1) + { + yield return new ValidationResult("Invalid value for Plate, length must be greater than 1.", new [] { "Plate" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CarCreateJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override CarCreate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option plate = default; + Option externalId = default; + Option usable = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "plate": + plate = new Option(utf8JsonReader.GetString()!); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "usable": + usable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!name.IsSet) + throw new ArgumentException("Property is required for class CarCreate.", nameof(name)); + + if (!plate.IsSet) + throw new ArgumentException("Property is required for class CarCreate.", nameof(plate)); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class CarCreate."); + + if (plate.IsSet && plate.Value == null) + throw new ArgumentNullException(nameof(plate), "Property is not nullable for class CarCreate."); + + if (usable.IsSet && usable.Value == null) + throw new ArgumentNullException(nameof(usable), "Property is not nullable for class CarCreate."); + + return new CarCreate(name.Value!, plate.Value!, externalId, usable, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CarCreate carCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, carCreate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CarCreate carCreate, JsonSerializerOptions jsonSerializerOptions) + { + if (carCreate.Name == null) + throw new ArgumentNullException(nameof(carCreate.Name), "Property is required for class CarCreate."); + + if (carCreate.Plate == null) + throw new ArgumentNullException(nameof(carCreate.Plate), "Property is required for class CarCreate."); + + writer.WriteString("name", carCreate.Name); + + writer.WriteString("plate", carCreate.Plate); + + if (carCreate.ExternalIdOption.IsSet) + if (carCreate.ExternalIdOption.Value != null) + writer.WriteString("external_id", carCreate.ExternalId); + else + writer.WriteNull("external_id"); + + if (carCreate.UsableOption.IsSet) + writer.WriteBoolean("usable", carCreate.UsableOption.Value!.Value); + + if (carCreate.MetadataOption.IsSet) + if (carCreate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, carCreate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/CarPartial.cs b/sdk/dotnet/Timr.Api/Model/CarPartial.cs new file mode 100644 index 0000000..9376dc0 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/CarPartial.cs @@ -0,0 +1,235 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// CarPartial + /// + public partial class CarPartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// plate + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonConstructor] + public CarPartial(string id, string name, string plate, string? externalId = default) + { + Id = id; + Name = name; + Plate = plate; + ExternalId = externalId; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets Plate + /// + [JsonPropertyName("plate")] + public string Plate { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CarPartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Plate: ").Append(Plate).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CarPartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override CarPartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option plate = default; + Option externalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "plate": + plate = new Option(utf8JsonReader.GetString()!); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class CarPartial.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class CarPartial.", nameof(name)); + + if (!plate.IsSet) + throw new ArgumentException("Property is required for class CarPartial.", nameof(plate)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class CarPartial.", nameof(externalId)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class CarPartial."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class CarPartial."); + + if (plate.IsSet && plate.Value == null) + throw new ArgumentNullException(nameof(plate), "Property is not nullable for class CarPartial."); + + return new CarPartial(id.Value!, name.Value!, plate.Value!, externalId.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CarPartial carPartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, carPartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CarPartial carPartial, JsonSerializerOptions jsonSerializerOptions) + { + if (carPartial.Id == null) + throw new ArgumentNullException(nameof(carPartial.Id), "Property is required for class CarPartial."); + + if (carPartial.Name == null) + throw new ArgumentNullException(nameof(carPartial.Name), "Property is required for class CarPartial."); + + if (carPartial.Plate == null) + throw new ArgumentNullException(nameof(carPartial.Plate), "Property is required for class CarPartial."); + + writer.WriteString("id", carPartial.Id); + + writer.WriteString("name", carPartial.Name); + + writer.WriteString("plate", carPartial.Plate); + + if (carPartial.ExternalId != null) + writer.WriteString("external_id", carPartial.ExternalId); + else + writer.WriteNull("external_id"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/CarUpdate.cs b/sdk/dotnet/Timr.Api/Model/CarUpdate.cs new file mode 100644 index 0000000..6e0f9a2 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/CarUpdate.cs @@ -0,0 +1,304 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// CarUpdate + /// + public partial class CarUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + /// plate + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// usable + /// metadata + [JsonConstructor] + public CarUpdate(Option name = default, Option plate = default, Option externalId = default, Option usable = default, Option?> metadata = default) + { + NameOption = name; + PlateOption = plate; + ExternalIdOption = externalId; + UsableOption = usable; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string? Name { get { return this.NameOption.Value; } set { this.NameOption = new(value); } } + + /// + /// Used to track the state of Plate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option PlateOption { get; private set; } + + /// + /// Gets or Sets Plate + /// + [JsonPropertyName("plate")] + public string? Plate { get { return this.PlateOption.Value; } set { this.PlateOption = new(value); } } + + /// + /// Used to track the state of ExternalId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ExternalIdOption { get; private set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get { return this.ExternalIdOption.Value; } set { this.ExternalIdOption = new(value); } } + + /// + /// Used to track the state of Usable + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option UsableOption { get; private set; } + + /// + /// Gets or Sets Usable + /// + [JsonPropertyName("usable")] + public bool? Usable { get { return this.UsableOption.Value; } set { this.UsableOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CarUpdate {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Plate: ").Append(Plate).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Usable: ").Append(Usable).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Name (string) maxLength + if (this.Name != null && this.Name.Length > 191) + { + yield return new ValidationResult("Invalid value for Name, length must be less than 191.", new [] { "Name" }); + } + + // Name (string) minLength + if (this.Name != null && this.Name.Length < 1) + { + yield return new ValidationResult("Invalid value for Name, length must be greater than 1.", new [] { "Name" }); + } + + // Plate (string) maxLength + if (this.Plate != null && this.Plate.Length > 191) + { + yield return new ValidationResult("Invalid value for Plate, length must be less than 191.", new [] { "Plate" }); + } + + // Plate (string) minLength + if (this.Plate != null && this.Plate.Length < 1) + { + yield return new ValidationResult("Invalid value for Plate, length must be greater than 1.", new [] { "Plate" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CarUpdateJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override CarUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option plate = default; + Option externalId = default; + Option usable = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "plate": + plate = new Option(utf8JsonReader.GetString()!); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "usable": + usable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class CarUpdate."); + + if (plate.IsSet && plate.Value == null) + throw new ArgumentNullException(nameof(plate), "Property is not nullable for class CarUpdate."); + + if (usable.IsSet && usable.Value == null) + throw new ArgumentNullException(nameof(usable), "Property is not nullable for class CarUpdate."); + + return new CarUpdate(name, plate, externalId, usable, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CarUpdate carUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, carUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CarUpdate carUpdate, JsonSerializerOptions jsonSerializerOptions) + { + if (carUpdate.NameOption.IsSet && carUpdate.Name == null) + throw new ArgumentNullException(nameof(carUpdate.Name), "Property is required for class CarUpdate."); + + if (carUpdate.PlateOption.IsSet && carUpdate.Plate == null) + throw new ArgumentNullException(nameof(carUpdate.Plate), "Property is required for class CarUpdate."); + + if (carUpdate.NameOption.IsSet) + writer.WriteString("name", carUpdate.Name); + + if (carUpdate.PlateOption.IsSet) + writer.WriteString("plate", carUpdate.Plate); + + if (carUpdate.ExternalIdOption.IsSet) + if (carUpdate.ExternalIdOption.Value != null) + writer.WriteString("external_id", carUpdate.ExternalId); + else + writer.WriteNull("external_id"); + + if (carUpdate.UsableOption.IsSet) + writer.WriteBoolean("usable", carUpdate.UsableOption.Value!.Value); + + if (carUpdate.MetadataOption.IsSet) + if (carUpdate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, carUpdate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/CarsPage.cs b/sdk/dotnet/Timr.Api/Model/CarsPage.cs new file mode 100644 index 0000000..869b4b8 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/CarsPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// CarsPage + /// + public partial class CarsPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public CarsPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class CarsPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class CarsPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override CarsPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class CarsPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class CarsPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class CarsPage."); + + return new CarsPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CarsPage carsPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, carsPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, CarsPage carsPage, JsonSerializerOptions jsonSerializerOptions) + { + if (carsPage.Data == null) + throw new ArgumentNullException(nameof(carsPage.Data), "Property is required for class CarsPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, carsPage.Data, jsonSerializerOptions); + if (carsPage.NextPageToken != null) + writer.WriteString("next_page_token", carsPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/CarsSortColumn.cs b/sdk/dotnet/Timr.Api/Model/CarsSortColumn.cs new file mode 100644 index 0000000..1b321b4 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/CarsSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Cars. + /// + /// Sort property for Cars. + public enum CarsSortColumn + { + /// + /// Enum Name for value: name + /// + Name = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class CarsSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static CarsSortColumn FromString(string value) + { + if (value.Equals("name")) + return CarsSortColumn.Name; + + throw new NotImplementedException($"Could not convert value to type CarsSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static CarsSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("name")) + return CarsSortColumn.Name; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(CarsSortColumn value) + { + if (value == CarsSortColumn.Name) + return "name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class CarsSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override CarsSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + CarsSortColumn? result = rawValue == null + ? null + : CarsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the CarsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CarsSortColumn carsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(CarsSortColumnValueConverter.ToJsonValue(carsSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class CarsSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a CarsSortColumn from the Json object + /// + /// + /// + /// + /// + public override CarsSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + CarsSortColumn? result = rawValue == null + ? null + : CarsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the CarsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, CarsSortColumn? carsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(carsSortColumn.HasValue ? CarsSortColumnValueConverter.ToJsonValue(carsSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DailyWorkSchedule.cs b/sdk/dotnet/Timr.Api/Model/DailyWorkSchedule.cs new file mode 100644 index 0000000..9be76db --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DailyWorkSchedule.cs @@ -0,0 +1,196 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DailyWorkSchedule + /// + public partial class DailyWorkSchedule : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// value in minutes + /// this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set + [JsonConstructor] + public DailyWorkSchedule(long targetDurationMinutes, Option?> normalWorkingTimes = default) + { + TargetDurationMinutes = targetDurationMinutes; + NormalWorkingTimesOption = normalWorkingTimes; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// value in minutes + /// + /// value in minutes + /* 480 */ + [JsonPropertyName("target_duration_minutes")] + public long TargetDurationMinutes { get; set; } + + /// + /// Used to track the state of NormalWorkingTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> NormalWorkingTimesOption { get; private set; } + + /// + /// this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set + /// + /// this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set + [JsonPropertyName("normal_working_times")] + public List? NormalWorkingTimes { get { return this.NormalWorkingTimesOption.Value; } set { this.NormalWorkingTimesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DailyWorkSchedule {\n"); + sb.Append(" TargetDurationMinutes: ").Append(TargetDurationMinutes).Append("\n"); + sb.Append(" NormalWorkingTimes: ").Append(NormalWorkingTimes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DailyWorkScheduleJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DailyWorkSchedule Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option targetDurationMinutes = default; + Option?> normalWorkingTimes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "target_duration_minutes": + targetDurationMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "normal_working_times": + normalWorkingTimes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + default: + break; + } + } + } + + if (!targetDurationMinutes.IsSet) + throw new ArgumentException("Property is required for class DailyWorkSchedule.", nameof(targetDurationMinutes)); + + if (targetDurationMinutes.IsSet && targetDurationMinutes.Value == null) + throw new ArgumentNullException(nameof(targetDurationMinutes), "Property is not nullable for class DailyWorkSchedule."); + + if (normalWorkingTimes.IsSet && normalWorkingTimes.Value == null) + throw new ArgumentNullException(nameof(normalWorkingTimes), "Property is not nullable for class DailyWorkSchedule."); + + return new DailyWorkSchedule(targetDurationMinutes.Value!.Value!, normalWorkingTimes); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DailyWorkSchedule dailyWorkSchedule, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, dailyWorkSchedule, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DailyWorkSchedule dailyWorkSchedule, JsonSerializerOptions jsonSerializerOptions) + { + if (dailyWorkSchedule.NormalWorkingTimesOption.IsSet && dailyWorkSchedule.NormalWorkingTimes == null) + throw new ArgumentNullException(nameof(dailyWorkSchedule.NormalWorkingTimes), "Property is required for class DailyWorkSchedule."); + + writer.WriteNumber("target_duration_minutes", dailyWorkSchedule.TargetDurationMinutes); + + if (dailyWorkSchedule.NormalWorkingTimesOption.IsSet) + { + writer.WritePropertyName("normal_working_times"); + JsonSerializer.Serialize(writer, dailyWorkSchedule.NormalWorkingTimes, jsonSerializerOptions); + } + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DeletedEntryPage.cs b/sdk/dotnet/Timr.Api/Model/DeletedEntryPage.cs new file mode 100644 index 0000000..65470f2 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DeletedEntryPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DeletedEntryPage + /// + public partial class DeletedEntryPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public DeletedEntryPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeletedEntryPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeletedEntryPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DeletedEntryPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class DeletedEntryPage."); + + return new DeletedEntryPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeletedEntryPage deletedEntryPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, deletedEntryPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeletedEntryPage deletedEntryPage, JsonSerializerOptions jsonSerializerOptions) + { + if (deletedEntryPage.Data == null) + throw new ArgumentNullException(nameof(deletedEntryPage.Data), "Property is required for class DeletedEntryPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, deletedEntryPage.Data, jsonSerializerOptions); + if (deletedEntryPage.NextPageToken != null) + writer.WriteString("next_page_token", deletedEntryPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DeletedEntryPartial.cs b/sdk/dotnet/Timr.Api/Model/DeletedEntryPartial.cs new file mode 100644 index 0000000..09ba156 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DeletedEntryPartial.cs @@ -0,0 +1,218 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DeletedEntryPartial + /// + public partial class DeletedEntryPartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + [JsonConstructor] + public DeletedEntryPartial(string id, DateTimeOffset lastModified, UserPartial? lastModifiedBy = default) + { + Id = id; + LastModified = lastModified; + LastModifiedBy = lastModifiedBy; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("last_modified")] + public DateTimeOffset LastModified { get; set; } + + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + [JsonPropertyName("last_modified_by")] + public UserPartial? LastModifiedBy { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeletedEntryPartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LastModified: ").Append(LastModified).Append("\n"); + sb.Append(" LastModifiedBy: ").Append(LastModifiedBy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeletedEntryPartialJsonConverter : JsonConverter + { + /// + /// The format to use to serialize LastModified + /// + public static string LastModifiedFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DeletedEntryPartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option lastModified = default; + Option lastModifiedBy = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "last_modified": + lastModified = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "last_modified_by": + lastModifiedBy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryPartial.", nameof(id)); + + if (!lastModified.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryPartial.", nameof(lastModified)); + + if (!lastModifiedBy.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryPartial.", nameof(lastModifiedBy)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class DeletedEntryPartial."); + + if (lastModified.IsSet && lastModified.Value == null) + throw new ArgumentNullException(nameof(lastModified), "Property is not nullable for class DeletedEntryPartial."); + + return new DeletedEntryPartial(id.Value!, lastModified.Value!.Value!, lastModifiedBy.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeletedEntryPartial deletedEntryPartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, deletedEntryPartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeletedEntryPartial deletedEntryPartial, JsonSerializerOptions jsonSerializerOptions) + { + if (deletedEntryPartial.Id == null) + throw new ArgumentNullException(nameof(deletedEntryPartial.Id), "Property is required for class DeletedEntryPartial."); + + writer.WriteString("id", deletedEntryPartial.Id); + + writer.WriteString("last_modified", deletedEntryPartial.LastModified.ToString(LastModifiedFormat)); + + if (deletedEntryPartial.LastModifiedBy != null) + { + writer.WritePropertyName("last_modified_by"); + JsonSerializer.Serialize(writer, deletedEntryPartial.LastModifiedBy, jsonSerializerOptions); + } + else + writer.WriteNull("last_modified_by"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DeletedEntrySortColumn.cs b/sdk/dotnet/Timr.Api/Model/DeletedEntrySortColumn.cs new file mode 100644 index 0000000..10af722 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DeletedEntrySortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for deleted entries. + /// + /// Sort property for deleted entries. + public enum DeletedEntrySortColumn + { + /// + /// Enum LastModified for value: last_modified + /// + LastModified = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class DeletedEntrySortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static DeletedEntrySortColumn FromString(string value) + { + if (value.Equals("last_modified")) + return DeletedEntrySortColumn.LastModified; + + throw new NotImplementedException($"Could not convert value to type DeletedEntrySortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static DeletedEntrySortColumn? FromStringOrDefault(string value) + { + if (value.Equals("last_modified")) + return DeletedEntrySortColumn.LastModified; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(DeletedEntrySortColumn value) + { + if (value == DeletedEntrySortColumn.LastModified) + return "last_modified"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class DeletedEntrySortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override DeletedEntrySortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DeletedEntrySortColumn? result = rawValue == null + ? null + : DeletedEntrySortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DeletedEntrySortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeletedEntrySortColumn deletedEntrySortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(DeletedEntrySortColumnValueConverter.ToJsonValue(deletedEntrySortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class DeletedEntrySortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a DeletedEntrySortColumn from the Json object + /// + /// + /// + /// + /// + public override DeletedEntrySortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DeletedEntrySortColumn? result = rawValue == null + ? null + : DeletedEntrySortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DeletedEntrySortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeletedEntrySortColumn? deletedEntrySortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(deletedEntrySortColumn.HasValue ? DeletedEntrySortColumnValueConverter.ToJsonValue(deletedEntrySortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DeletedEntryWithMetadata.cs b/sdk/dotnet/Timr.Api/Model/DeletedEntryWithMetadata.cs new file mode 100644 index 0000000..e01aace --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DeletedEntryWithMetadata.cs @@ -0,0 +1,246 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DeletedEntryWithMetadata + /// + public partial class DeletedEntryWithMetadata : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// metadata + [JsonConstructor] + public DeletedEntryWithMetadata(string id, DateTimeOffset lastModified, UserPartial? lastModifiedBy = default, Option?> metadata = default) + { + Id = id; + LastModified = lastModified; + LastModifiedBy = lastModifiedBy; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("last_modified")] + public DateTimeOffset LastModified { get; set; } + + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + [JsonPropertyName("last_modified_by")] + public UserPartial? LastModifiedBy { get; set; } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeletedEntryWithMetadata {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" LastModified: ").Append(LastModified).Append("\n"); + sb.Append(" LastModifiedBy: ").Append(LastModifiedBy).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeletedEntryWithMetadataJsonConverter : JsonConverter + { + /// + /// The format to use to serialize LastModified + /// + public static string LastModifiedFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DeletedEntryWithMetadata Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option lastModified = default; + Option lastModifiedBy = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "last_modified": + lastModified = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "last_modified_by": + lastModifiedBy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryWithMetadata.", nameof(id)); + + if (!lastModified.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryWithMetadata.", nameof(lastModified)); + + if (!lastModifiedBy.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryWithMetadata.", nameof(lastModifiedBy)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class DeletedEntryWithMetadata."); + + if (lastModified.IsSet && lastModified.Value == null) + throw new ArgumentNullException(nameof(lastModified), "Property is not nullable for class DeletedEntryWithMetadata."); + + return new DeletedEntryWithMetadata(id.Value!, lastModified.Value!.Value!, lastModifiedBy.Value!, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeletedEntryWithMetadata deletedEntryWithMetadata, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, deletedEntryWithMetadata, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeletedEntryWithMetadata deletedEntryWithMetadata, JsonSerializerOptions jsonSerializerOptions) + { + if (deletedEntryWithMetadata.Id == null) + throw new ArgumentNullException(nameof(deletedEntryWithMetadata.Id), "Property is required for class DeletedEntryWithMetadata."); + + writer.WriteString("id", deletedEntryWithMetadata.Id); + + writer.WriteString("last_modified", deletedEntryWithMetadata.LastModified.ToString(LastModifiedFormat)); + + if (deletedEntryWithMetadata.LastModifiedBy != null) + { + writer.WritePropertyName("last_modified_by"); + JsonSerializer.Serialize(writer, deletedEntryWithMetadata.LastModifiedBy, jsonSerializerOptions); + } + else + writer.WriteNull("last_modified_by"); + if (deletedEntryWithMetadata.MetadataOption.IsSet) + if (deletedEntryWithMetadata.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, deletedEntryWithMetadata.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DeletedEntryWithMetadataPage.cs b/sdk/dotnet/Timr.Api/Model/DeletedEntryWithMetadataPage.cs new file mode 100644 index 0000000..36f841f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DeletedEntryWithMetadataPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DeletedEntryWithMetadataPage + /// + public partial class DeletedEntryWithMetadataPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public DeletedEntryWithMetadataPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DeletedEntryWithMetadataPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DeletedEntryWithMetadataPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DeletedEntryWithMetadataPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryWithMetadataPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class DeletedEntryWithMetadataPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class DeletedEntryWithMetadataPage."); + + return new DeletedEntryWithMetadataPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DeletedEntryWithMetadataPage deletedEntryWithMetadataPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, deletedEntryWithMetadataPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DeletedEntryWithMetadataPage deletedEntryWithMetadataPage, JsonSerializerOptions jsonSerializerOptions) + { + if (deletedEntryWithMetadataPage.Data == null) + throw new ArgumentNullException(nameof(deletedEntryWithMetadataPage.Data), "Property is required for class DeletedEntryWithMetadataPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, deletedEntryWithMetadataPage.Data, jsonSerializerOptions); + if (deletedEntryWithMetadataPage.NextPageToken != null) + writer.WriteString("next_page_token", deletedEntryWithMetadataPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLog.cs b/sdk/dotnet/Timr.Api/Model/DriveLog.cs new file mode 100644 index 0000000..cacbd2b --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLog.cs @@ -0,0 +1,742 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// One trip in a `car`: `start` and `end`, `start_mileage` and `end_mileage` with the resulting `distance`, the `purpose`, the places `visited`, and its `drive_log_category`. May include a recorded GPS `route`. + /// + public partial class DriveLog : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// RFC 3339 date-time (ISO-8601) + /// changed + /// startMileage + /// user + /// car + /// driveLogCategory + /// hasTrack + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// status + /// RFC 3339 date-time (ISO-8601) + /// duration + /// endMileage + /// Driven distance in kilometers + /// route + /// purpose + /// visited + /// startVenue + /// endVenue + /// startLocation + /// endLocation + /// startPlatform + /// endPlatform + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// metadata + [JsonConstructor] + public DriveLog(string id, DateTimeOffset start, bool changed, long startMileage, UserPartial user, CarPartial car, DriveLogCategoryPartial driveLogCategory, bool hasTrack, DateTimeOffset lastModified, DriveLogStatus status, DateTimeOffset? end = default, Duration? duration = default, long? endMileage = default, long? distance = default, string? route = default, string? purpose = default, string? visited = default, VenuePartial? startVenue = default, VenuePartial? endVenue = default, Location? startLocation = default, Location? endLocation = default, Platform? startPlatform = default, Platform? endPlatform = default, UserPartial? lastModifiedBy = default, Option?> metadata = default) + { + Id = id; + Start = start; + Changed = changed; + StartMileage = startMileage; + User = user; + Car = car; + DriveLogCategory = driveLogCategory; + HasTrack = hasTrack; + LastModified = lastModified; + Status = status; + End = end; + Duration = duration; + EndMileage = endMileage; + Distance = distance; + Route = route; + Purpose = purpose; + Visited = visited; + StartVenue = startVenue; + EndVenue = endVenue; + StartLocation = startLocation; + EndLocation = endLocation; + StartPlatform = startPlatform; + EndPlatform = endPlatform; + LastModifiedBy = lastModifiedBy; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public DriveLogStatus Status { get; set; } + + /// + /// Gets or Sets StartPlatform + /// + [JsonPropertyName("start_platform")] + public Platform? StartPlatform { get; set; } + + /// + /// Gets or Sets EndPlatform + /// + [JsonPropertyName("end_platform")] + public Platform? EndPlatform { get; set; } + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + /* 074e7048-9097-11eb-a8b3-0242ac130003 */ + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset Start { get; set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool Changed { get; set; } + + /// + /// Gets or Sets StartMileage + /// + /* 42 */ + [JsonPropertyName("start_mileage")] + public long StartMileage { get; set; } + + /// + /// Gets or Sets User + /// + [JsonPropertyName("user")] + public UserPartial User { get; set; } + + /// + /// Gets or Sets Car + /// + [JsonPropertyName("car")] + public CarPartial Car { get; set; } + + /// + /// Gets or Sets DriveLogCategory + /// + [JsonPropertyName("drive_log_category")] + public DriveLogCategoryPartial DriveLogCategory { get; set; } + + /// + /// Gets or Sets HasTrack + /// + [JsonPropertyName("has_track")] + public bool HasTrack { get; set; } + + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("last_modified")] + public DateTimeOffset LastModified { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get; set; } + + /// + /// Gets or Sets Duration + /// + [JsonPropertyName("duration")] + public Duration? Duration { get; set; } + + /// + /// Gets or Sets EndMileage + /// + /* 42 */ + [JsonPropertyName("end_mileage")] + public long? EndMileage { get; set; } + + /// + /// Driven distance in kilometers + /// + /// Driven distance in kilometers + /* 42 */ + [JsonPropertyName("distance")] + public long? Distance { get; set; } + + /// + /// Gets or Sets Route + /// + [JsonPropertyName("route")] + public string? Route { get; set; } + + /// + /// Gets or Sets Purpose + /// + [JsonPropertyName("purpose")] + public string? Purpose { get; set; } + + /// + /// Gets or Sets Visited + /// + [JsonPropertyName("visited")] + public string? Visited { get; set; } + + /// + /// Gets or Sets StartVenue + /// + [JsonPropertyName("start_venue")] + public VenuePartial? StartVenue { get; set; } + + /// + /// Gets or Sets EndVenue + /// + [JsonPropertyName("end_venue")] + public VenuePartial? EndVenue { get; set; } + + /// + /// Gets or Sets StartLocation + /// + [JsonPropertyName("start_location")] + public Location? StartLocation { get; set; } + + /// + /// Gets or Sets EndLocation + /// + [JsonPropertyName("end_location")] + public Location? EndLocation { get; set; } + + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + [JsonPropertyName("last_modified_by")] + public UserPartial? LastModifiedBy { get; set; } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DriveLog {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" StartMileage: ").Append(StartMileage).Append("\n"); + sb.Append(" User: ").Append(User).Append("\n"); + sb.Append(" Car: ").Append(Car).Append("\n"); + sb.Append(" DriveLogCategory: ").Append(DriveLogCategory).Append("\n"); + sb.Append(" HasTrack: ").Append(HasTrack).Append("\n"); + sb.Append(" LastModified: ").Append(LastModified).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" Duration: ").Append(Duration).Append("\n"); + sb.Append(" EndMileage: ").Append(EndMileage).Append("\n"); + sb.Append(" Distance: ").Append(Distance).Append("\n"); + sb.Append(" Route: ").Append(Route).Append("\n"); + sb.Append(" Purpose: ").Append(Purpose).Append("\n"); + sb.Append(" Visited: ").Append(Visited).Append("\n"); + sb.Append(" StartVenue: ").Append(StartVenue).Append("\n"); + sb.Append(" EndVenue: ").Append(EndVenue).Append("\n"); + sb.Append(" StartLocation: ").Append(StartLocation).Append("\n"); + sb.Append(" EndLocation: ").Append(EndLocation).Append("\n"); + sb.Append(" StartPlatform: ").Append(StartPlatform).Append("\n"); + sb.Append(" EndPlatform: ").Append(EndPlatform).Append("\n"); + sb.Append(" LastModifiedBy: ").Append(LastModifiedBy).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DriveLogJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize LastModified + /// + public static string LastModifiedFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DriveLog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option start = default; + Option changed = default; + Option startMileage = default; + Option user = default; + Option car = default; + Option driveLogCategory = default; + Option hasTrack = default; + Option lastModified = default; + Option status = default; + Option end = default; + Option duration = default; + Option endMileage = default; + Option distance = default; + Option route = default; + Option purpose = default; + Option visited = default; + Option startVenue = default; + Option endVenue = default; + Option startLocation = default; + Option endLocation = default; + Option startPlatform = default; + Option endPlatform = default; + Option lastModifiedBy = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "start_mileage": + startMileage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "user": + user = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "car": + car = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "drive_log_category": + driveLogCategory = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "has_track": + hasTrack = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "last_modified": + lastModified = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(DriveLogStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "duration": + duration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_mileage": + endMileage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "distance": + distance = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "route": + route = new Option(utf8JsonReader.GetString()); + break; + case "purpose": + purpose = new Option(utf8JsonReader.GetString()); + break; + case "visited": + visited = new Option(utf8JsonReader.GetString()); + break; + case "start_venue": + startVenue = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_venue": + endVenue = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_location": + startLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_location": + endLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_platform": + string? startPlatformRawValue = utf8JsonReader.GetString(); + startPlatform = new Option(startPlatformRawValue == null ? null : PlatformValueConverter.FromStringOrDefault(startPlatformRawValue)); + break; + case "end_platform": + string? endPlatformRawValue = utf8JsonReader.GetString(); + endPlatform = new Option(endPlatformRawValue == null ? null : PlatformValueConverter.FromStringOrDefault(endPlatformRawValue)); + break; + case "last_modified_by": + lastModifiedBy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(id)); + + if (!start.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(start)); + + if (!changed.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(changed)); + + if (!startMileage.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(startMileage)); + + if (!user.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(user)); + + if (!car.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(car)); + + if (!driveLogCategory.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(driveLogCategory)); + + if (!hasTrack.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(hasTrack)); + + if (!lastModified.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(lastModified)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(status)); + + if (!end.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(end)); + + if (!duration.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(duration)); + + if (!endMileage.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(endMileage)); + + if (!distance.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(distance)); + + if (!route.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(route)); + + if (!purpose.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(purpose)); + + if (!visited.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(visited)); + + if (!startVenue.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(startVenue)); + + if (!endVenue.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(endVenue)); + + if (!startLocation.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(startLocation)); + + if (!endLocation.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(endLocation)); + + if (!startPlatform.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(startPlatform)); + + if (!endPlatform.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(endPlatform)); + + if (!lastModifiedBy.IsSet) + throw new ArgumentException("Property is required for class DriveLog.", nameof(lastModifiedBy)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class DriveLog."); + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class DriveLog."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class DriveLog."); + + if (startMileage.IsSet && startMileage.Value == null) + throw new ArgumentNullException(nameof(startMileage), "Property is not nullable for class DriveLog."); + + if (user.IsSet && user.Value == null) + throw new ArgumentNullException(nameof(user), "Property is not nullable for class DriveLog."); + + if (car.IsSet && car.Value == null) + throw new ArgumentNullException(nameof(car), "Property is not nullable for class DriveLog."); + + if (driveLogCategory.IsSet && driveLogCategory.Value == null) + throw new ArgumentNullException(nameof(driveLogCategory), "Property is not nullable for class DriveLog."); + + if (hasTrack.IsSet && hasTrack.Value == null) + throw new ArgumentNullException(nameof(hasTrack), "Property is not nullable for class DriveLog."); + + if (lastModified.IsSet && lastModified.Value == null) + throw new ArgumentNullException(nameof(lastModified), "Property is not nullable for class DriveLog."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class DriveLog."); + + return new DriveLog(id.Value!, start.Value!.Value!, changed.Value!.Value!, startMileage.Value!.Value!, user.Value!, car.Value!, driveLogCategory.Value!, hasTrack.Value!.Value!, lastModified.Value!.Value!, status.Value!.Value!, end.Value!, duration.Value!, endMileage.Value!, distance.Value!, route.Value!, purpose.Value!, visited.Value!, startVenue.Value!, endVenue.Value!, startLocation.Value!, endLocation.Value!, startPlatform.Value!, endPlatform.Value!, lastModifiedBy.Value!, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLog driveLog, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, driveLog, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DriveLog driveLog, JsonSerializerOptions jsonSerializerOptions) + { + if (driveLog.Id == null) + throw new ArgumentNullException(nameof(driveLog.Id), "Property is required for class DriveLog."); + + if (driveLog.User == null) + throw new ArgumentNullException(nameof(driveLog.User), "Property is required for class DriveLog."); + + if (driveLog.Car == null) + throw new ArgumentNullException(nameof(driveLog.Car), "Property is required for class DriveLog."); + + if (driveLog.DriveLogCategory == null) + throw new ArgumentNullException(nameof(driveLog.DriveLogCategory), "Property is required for class DriveLog."); + + writer.WriteString("id", driveLog.Id); + + writer.WriteString("start", driveLog.Start.ToString(StartFormat)); + + writer.WriteBoolean("changed", driveLog.Changed); + + writer.WriteNumber("start_mileage", driveLog.StartMileage); + + writer.WritePropertyName("user"); + JsonSerializer.Serialize(writer, driveLog.User, jsonSerializerOptions); + writer.WritePropertyName("car"); + JsonSerializer.Serialize(writer, driveLog.Car, jsonSerializerOptions); + writer.WritePropertyName("drive_log_category"); + JsonSerializer.Serialize(writer, driveLog.DriveLogCategory, jsonSerializerOptions); + writer.WriteBoolean("has_track", driveLog.HasTrack); + + writer.WriteString("last_modified", driveLog.LastModified.ToString(LastModifiedFormat)); + + var statusRawValue = DriveLogStatusValueConverter.ToJsonValue(driveLog.Status); + writer.WriteString("status", statusRawValue); + + if (driveLog.End != null) + writer.WriteString("end", driveLog.End.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (driveLog.Duration != null) + { + writer.WritePropertyName("duration"); + JsonSerializer.Serialize(writer, driveLog.Duration, jsonSerializerOptions); + } + else + writer.WriteNull("duration"); + if (driveLog.EndMileage != null) + writer.WriteNumber("end_mileage", driveLog.EndMileage.Value); + else + writer.WriteNull("end_mileage"); + + if (driveLog.Distance != null) + writer.WriteNumber("distance", driveLog.Distance.Value); + else + writer.WriteNull("distance"); + + if (driveLog.Route != null) + writer.WriteString("route", driveLog.Route); + else + writer.WriteNull("route"); + + if (driveLog.Purpose != null) + writer.WriteString("purpose", driveLog.Purpose); + else + writer.WriteNull("purpose"); + + if (driveLog.Visited != null) + writer.WriteString("visited", driveLog.Visited); + else + writer.WriteNull("visited"); + + if (driveLog.StartVenue != null) + { + writer.WritePropertyName("start_venue"); + JsonSerializer.Serialize(writer, driveLog.StartVenue, jsonSerializerOptions); + } + else + writer.WriteNull("start_venue"); + if (driveLog.EndVenue != null) + { + writer.WritePropertyName("end_venue"); + JsonSerializer.Serialize(writer, driveLog.EndVenue, jsonSerializerOptions); + } + else + writer.WriteNull("end_venue"); + if (driveLog.StartLocation != null) + { + writer.WritePropertyName("start_location"); + JsonSerializer.Serialize(writer, driveLog.StartLocation, jsonSerializerOptions); + } + else + writer.WriteNull("start_location"); + if (driveLog.EndLocation != null) + { + writer.WritePropertyName("end_location"); + JsonSerializer.Serialize(writer, driveLog.EndLocation, jsonSerializerOptions); + } + else + writer.WriteNull("end_location"); + if (driveLog.StartPlatform == null) + writer.WriteNull("start_platform"); + else + { + var startPlatformRawValue = PlatformValueConverter.ToJsonValue(driveLog.StartPlatform.Value); + if (startPlatformRawValue != null) + writer.WriteString("start_platform", startPlatformRawValue); + else + writer.WriteNull("start_platform"); + } + + if (driveLog.EndPlatform == null) + writer.WriteNull("end_platform"); + else + { + var endPlatformRawValue = PlatformValueConverter.ToJsonValue(driveLog.EndPlatform.Value); + if (endPlatformRawValue != null) + writer.WriteString("end_platform", endPlatformRawValue); + else + writer.WriteNull("end_platform"); + } + + if (driveLog.LastModifiedBy != null) + { + writer.WritePropertyName("last_modified_by"); + JsonSerializer.Serialize(writer, driveLog.LastModifiedBy, jsonSerializerOptions); + } + else + writer.WriteNull("last_modified_by"); + if (driveLog.MetadataOption.IsSet) + if (driveLog.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, driveLog.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogCategoriesPage.cs b/sdk/dotnet/Timr.Api/Model/DriveLogCategoriesPage.cs new file mode 100644 index 0000000..f719e8c --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogCategoriesPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DriveLogCategoriesPage + /// + public partial class DriveLogCategoriesPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public DriveLogCategoriesPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DriveLogCategoriesPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DriveLogCategoriesPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DriveLogCategoriesPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategoriesPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategoriesPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class DriveLogCategoriesPage."); + + return new DriveLogCategoriesPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogCategoriesPage driveLogCategoriesPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, driveLogCategoriesPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DriveLogCategoriesPage driveLogCategoriesPage, JsonSerializerOptions jsonSerializerOptions) + { + if (driveLogCategoriesPage.Data == null) + throw new ArgumentNullException(nameof(driveLogCategoriesPage.Data), "Property is required for class DriveLogCategoriesPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, driveLogCategoriesPage.Data, jsonSerializerOptions); + if (driveLogCategoriesPage.NextPageToken != null) + writer.WriteString("next_page_token", driveLogCategoriesPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogCategoriesSortColumn.cs b/sdk/dotnet/Timr.Api/Model/DriveLogCategoriesSortColumn.cs new file mode 100644 index 0000000..3ee2a01 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogCategoriesSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Drive Log Categories. + /// + /// Sort property for Drive Log Categories. + public enum DriveLogCategoriesSortColumn + { + /// + /// Enum Name for value: name + /// + Name = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class DriveLogCategoriesSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static DriveLogCategoriesSortColumn FromString(string value) + { + if (value.Equals("name")) + return DriveLogCategoriesSortColumn.Name; + + throw new NotImplementedException($"Could not convert value to type DriveLogCategoriesSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static DriveLogCategoriesSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("name")) + return DriveLogCategoriesSortColumn.Name; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(DriveLogCategoriesSortColumn value) + { + if (value == DriveLogCategoriesSortColumn.Name) + return "name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class DriveLogCategoriesSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override DriveLogCategoriesSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DriveLogCategoriesSortColumn? result = rawValue == null + ? null + : DriveLogCategoriesSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DriveLogCategoriesSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogCategoriesSortColumn driveLogCategoriesSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(DriveLogCategoriesSortColumnValueConverter.ToJsonValue(driveLogCategoriesSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class DriveLogCategoriesSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a DriveLogCategoriesSortColumn from the Json object + /// + /// + /// + /// + /// + public override DriveLogCategoriesSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DriveLogCategoriesSortColumn? result = rawValue == null + ? null + : DriveLogCategoriesSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DriveLogCategoriesSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogCategoriesSortColumn? driveLogCategoriesSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(driveLogCategoriesSortColumn.HasValue ? DriveLogCategoriesSortColumnValueConverter.ToJsonValue(driveLogCategoriesSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogCategory.cs b/sdk/dotnet/Timr.Api/Model/DriveLogCategory.cs new file mode 100644 index 0000000..1cc5149 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogCategory.cs @@ -0,0 +1,287 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// A drive log category with a `name` and a display `color`; `business` marks it as business travel. + /// + public partial class DriveLogCategory : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// business + /// color + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + [JsonConstructor] + public DriveLogCategory(string id, string name, bool business, string color, DateTimeOffset lastModified, UserPartial? lastModifiedBy = default) + { + Id = id; + Name = name; + Business = business; + Color = color; + LastModified = lastModified; + LastModifiedBy = lastModifiedBy; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets Business + /// + [JsonPropertyName("business")] + public bool Business { get; set; } + + /// + /// Gets or Sets Color + /// + [JsonPropertyName("color")] + public string Color { get; set; } + + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("last_modified")] + public DateTimeOffset LastModified { get; set; } + + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + [JsonPropertyName("last_modified_by")] + public UserPartial? LastModifiedBy { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DriveLogCategory {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Business: ").Append(Business).Append("\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append(" LastModified: ").Append(LastModified).Append("\n"); + sb.Append(" LastModifiedBy: ").Append(LastModifiedBy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DriveLogCategoryJsonConverter : JsonConverter + { + /// + /// The format to use to serialize LastModified + /// + public static string LastModifiedFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DriveLogCategory Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option business = default; + Option color = default; + Option lastModified = default; + Option lastModifiedBy = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "business": + business = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "color": + color = new Option(utf8JsonReader.GetString()!); + break; + case "last_modified": + lastModified = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "last_modified_by": + lastModifiedBy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategory.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategory.", nameof(name)); + + if (!business.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategory.", nameof(business)); + + if (!color.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategory.", nameof(color)); + + if (!lastModified.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategory.", nameof(lastModified)); + + if (!lastModifiedBy.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategory.", nameof(lastModifiedBy)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class DriveLogCategory."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class DriveLogCategory."); + + if (business.IsSet && business.Value == null) + throw new ArgumentNullException(nameof(business), "Property is not nullable for class DriveLogCategory."); + + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class DriveLogCategory."); + + if (lastModified.IsSet && lastModified.Value == null) + throw new ArgumentNullException(nameof(lastModified), "Property is not nullable for class DriveLogCategory."); + + return new DriveLogCategory(id.Value!, name.Value!, business.Value!.Value!, color.Value!, lastModified.Value!.Value!, lastModifiedBy.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogCategory driveLogCategory, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, driveLogCategory, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DriveLogCategory driveLogCategory, JsonSerializerOptions jsonSerializerOptions) + { + if (driveLogCategory.Id == null) + throw new ArgumentNullException(nameof(driveLogCategory.Id), "Property is required for class DriveLogCategory."); + + if (driveLogCategory.Name == null) + throw new ArgumentNullException(nameof(driveLogCategory.Name), "Property is required for class DriveLogCategory."); + + if (driveLogCategory.Color == null) + throw new ArgumentNullException(nameof(driveLogCategory.Color), "Property is required for class DriveLogCategory."); + + writer.WriteString("id", driveLogCategory.Id); + + writer.WriteString("name", driveLogCategory.Name); + + writer.WriteBoolean("business", driveLogCategory.Business); + + writer.WriteString("color", driveLogCategory.Color); + + writer.WriteString("last_modified", driveLogCategory.LastModified.ToString(LastModifiedFormat)); + + if (driveLogCategory.LastModifiedBy != null) + { + writer.WritePropertyName("last_modified_by"); + JsonSerializer.Serialize(writer, driveLogCategory.LastModifiedBy, jsonSerializerOptions); + } + else + writer.WriteNull("last_modified_by"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogCategoryPartial.cs b/sdk/dotnet/Timr.Api/Model/DriveLogCategoryPartial.cs new file mode 100644 index 0000000..1d38582 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogCategoryPartial.cs @@ -0,0 +1,234 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DriveLogCategoryPartial + /// + public partial class DriveLogCategoryPartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// business + /// color + [JsonConstructor] + public DriveLogCategoryPartial(string id, string name, bool business, string color) + { + Id = id; + Name = name; + Business = business; + Color = color; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets Business + /// + [JsonPropertyName("business")] + public bool Business { get; set; } + + /// + /// Gets or Sets Color + /// + [JsonPropertyName("color")] + public string Color { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DriveLogCategoryPartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Business: ").Append(Business).Append("\n"); + sb.Append(" Color: ").Append(Color).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DriveLogCategoryPartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DriveLogCategoryPartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option business = default; + Option color = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "business": + business = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "color": + color = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategoryPartial.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategoryPartial.", nameof(name)); + + if (!business.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategoryPartial.", nameof(business)); + + if (!color.IsSet) + throw new ArgumentException("Property is required for class DriveLogCategoryPartial.", nameof(color)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class DriveLogCategoryPartial."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class DriveLogCategoryPartial."); + + if (business.IsSet && business.Value == null) + throw new ArgumentNullException(nameof(business), "Property is not nullable for class DriveLogCategoryPartial."); + + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class DriveLogCategoryPartial."); + + return new DriveLogCategoryPartial(id.Value!, name.Value!, business.Value!.Value!, color.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogCategoryPartial driveLogCategoryPartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, driveLogCategoryPartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DriveLogCategoryPartial driveLogCategoryPartial, JsonSerializerOptions jsonSerializerOptions) + { + if (driveLogCategoryPartial.Id == null) + throw new ArgumentNullException(nameof(driveLogCategoryPartial.Id), "Property is required for class DriveLogCategoryPartial."); + + if (driveLogCategoryPartial.Name == null) + throw new ArgumentNullException(nameof(driveLogCategoryPartial.Name), "Property is required for class DriveLogCategoryPartial."); + + if (driveLogCategoryPartial.Color == null) + throw new ArgumentNullException(nameof(driveLogCategoryPartial.Color), "Property is required for class DriveLogCategoryPartial."); + + writer.WriteString("id", driveLogCategoryPartial.Id); + + writer.WriteString("name", driveLogCategoryPartial.Name); + + writer.WriteBoolean("business", driveLogCategoryPartial.Business); + + writer.WriteString("color", driveLogCategoryPartial.Color); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogCreate.cs b/sdk/dotnet/Timr.Api/Model/DriveLogCreate.cs new file mode 100644 index 0000000..cadfc9c --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogCreate.cs @@ -0,0 +1,528 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DriveLogCreate + /// + public partial class DriveLogCreate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// RFC 3339 date-time (ISO-8601) + /// changed + /// startMileage + /// driveLogCategoryId + /// status + /// userId + /// carId + /// RFC 3339 date-time (ISO-8601) + /// endMileage + /// route + /// purpose + /// visited + /// metadata + /// startLocation + /// endLocation + [JsonConstructor] + public DriveLogCreate(DateTimeOffset start, bool changed, long startMileage, string driveLogCategoryId, DriveLogStatus status, string userId, string carId, Option end = default, Option endMileage = default, Option route = default, Option purpose = default, Option visited = default, Option?> metadata = default, Option startLocation = default, Option endLocation = default) + { + Start = start; + Changed = changed; + StartMileage = startMileage; + DriveLogCategoryId = driveLogCategoryId; + Status = status; + UserId = userId; + CarId = carId; + EndOption = end; + EndMileageOption = endMileage; + RouteOption = route; + PurposeOption = purpose; + VisitedOption = visited; + MetadataOption = metadata; + StartLocationOption = startLocation; + EndLocationOption = endLocation; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public DriveLogStatus Status { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset Start { get; set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool Changed { get; set; } + + /// + /// Gets or Sets StartMileage + /// + [JsonPropertyName("start_mileage")] + public long StartMileage { get; set; } + + /// + /// Gets or Sets DriveLogCategoryId + /// + [JsonPropertyName("drive_log_category_id")] + public string DriveLogCategoryId { get; set; } + + /// + /// Gets or Sets UserId + /// + [JsonPropertyName("user_id")] + public string UserId { get; set; } + + /// + /// Gets or Sets CarId + /// + [JsonPropertyName("car_id")] + public string CarId { get; set; } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of EndMileage + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndMileageOption { get; private set; } + + /// + /// Gets or Sets EndMileage + /// + [JsonPropertyName("end_mileage")] + public long? EndMileage { get { return this.EndMileageOption.Value; } set { this.EndMileageOption = new(value); } } + + /// + /// Used to track the state of Route + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option RouteOption { get; private set; } + + /// + /// Gets or Sets Route + /// + [JsonPropertyName("route")] + public string? Route { get { return this.RouteOption.Value; } set { this.RouteOption = new(value); } } + + /// + /// Used to track the state of Purpose + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option PurposeOption { get; private set; } + + /// + /// Gets or Sets Purpose + /// + [JsonPropertyName("purpose")] + public string? Purpose { get { return this.PurposeOption.Value; } set { this.PurposeOption = new(value); } } + + /// + /// Used to track the state of Visited + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option VisitedOption { get; private set; } + + /// + /// Gets or Sets Visited + /// + [JsonPropertyName("visited")] + public string? Visited { get { return this.VisitedOption.Value; } set { this.VisitedOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Used to track the state of StartLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartLocationOption { get; private set; } + + /// + /// Gets or Sets StartLocation + /// + [JsonPropertyName("start_location")] + public LocationCreate? StartLocation { get { return this.StartLocationOption.Value; } set { this.StartLocationOption = new(value); } } + + /// + /// Used to track the state of EndLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndLocationOption { get; private set; } + + /// + /// Gets or Sets EndLocation + /// + [JsonPropertyName("end_location")] + public LocationCreate? EndLocation { get { return this.EndLocationOption.Value; } set { this.EndLocationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DriveLogCreate {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" StartMileage: ").Append(StartMileage).Append("\n"); + sb.Append(" DriveLogCategoryId: ").Append(DriveLogCategoryId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" UserId: ").Append(UserId).Append("\n"); + sb.Append(" CarId: ").Append(CarId).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" EndMileage: ").Append(EndMileage).Append("\n"); + sb.Append(" Route: ").Append(Route).Append("\n"); + sb.Append(" Purpose: ").Append(Purpose).Append("\n"); + sb.Append(" Visited: ").Append(Visited).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" StartLocation: ").Append(StartLocation).Append("\n"); + sb.Append(" EndLocation: ").Append(EndLocation).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DriveLogCreateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DriveLogCreate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option changed = default; + Option startMileage = default; + Option driveLogCategoryId = default; + Option status = default; + Option userId = default; + Option carId = default; + Option end = default; + Option endMileage = default; + Option route = default; + Option purpose = default; + Option visited = default; + Option?> metadata = default; + Option startLocation = default; + Option endLocation = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "start_mileage": + startMileage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "drive_log_category_id": + driveLogCategoryId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(DriveLogStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "user_id": + userId = new Option(utf8JsonReader.GetString()!); + break; + case "car_id": + carId = new Option(utf8JsonReader.GetString()!); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_mileage": + endMileage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "route": + route = new Option(utf8JsonReader.GetString()); + break; + case "purpose": + purpose = new Option(utf8JsonReader.GetString()); + break; + case "visited": + visited = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_location": + startLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_location": + endLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!start.IsSet) + throw new ArgumentException("Property is required for class DriveLogCreate.", nameof(start)); + + if (!changed.IsSet) + throw new ArgumentException("Property is required for class DriveLogCreate.", nameof(changed)); + + if (!startMileage.IsSet) + throw new ArgumentException("Property is required for class DriveLogCreate.", nameof(startMileage)); + + if (!driveLogCategoryId.IsSet) + throw new ArgumentException("Property is required for class DriveLogCreate.", nameof(driveLogCategoryId)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class DriveLogCreate.", nameof(status)); + + if (!userId.IsSet) + throw new ArgumentException("Property is required for class DriveLogCreate.", nameof(userId)); + + if (!carId.IsSet) + throw new ArgumentException("Property is required for class DriveLogCreate.", nameof(carId)); + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class DriveLogCreate."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class DriveLogCreate."); + + if (startMileage.IsSet && startMileage.Value == null) + throw new ArgumentNullException(nameof(startMileage), "Property is not nullable for class DriveLogCreate."); + + if (driveLogCategoryId.IsSet && driveLogCategoryId.Value == null) + throw new ArgumentNullException(nameof(driveLogCategoryId), "Property is not nullable for class DriveLogCreate."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class DriveLogCreate."); + + if (userId.IsSet && userId.Value == null) + throw new ArgumentNullException(nameof(userId), "Property is not nullable for class DriveLogCreate."); + + if (carId.IsSet && carId.Value == null) + throw new ArgumentNullException(nameof(carId), "Property is not nullable for class DriveLogCreate."); + + return new DriveLogCreate(start.Value!.Value!, changed.Value!.Value!, startMileage.Value!.Value!, driveLogCategoryId.Value!, status.Value!.Value!, userId.Value!, carId.Value!, end, endMileage, route, purpose, visited, metadata, startLocation, endLocation); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogCreate driveLogCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, driveLogCreate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DriveLogCreate driveLogCreate, JsonSerializerOptions jsonSerializerOptions) + { + if (driveLogCreate.DriveLogCategoryId == null) + throw new ArgumentNullException(nameof(driveLogCreate.DriveLogCategoryId), "Property is required for class DriveLogCreate."); + + if (driveLogCreate.UserId == null) + throw new ArgumentNullException(nameof(driveLogCreate.UserId), "Property is required for class DriveLogCreate."); + + if (driveLogCreate.CarId == null) + throw new ArgumentNullException(nameof(driveLogCreate.CarId), "Property is required for class DriveLogCreate."); + + writer.WriteString("start", driveLogCreate.Start.ToString(StartFormat)); + + writer.WriteBoolean("changed", driveLogCreate.Changed); + + writer.WriteNumber("start_mileage", driveLogCreate.StartMileage); + + writer.WriteString("drive_log_category_id", driveLogCreate.DriveLogCategoryId); + + var statusRawValue = DriveLogStatusValueConverter.ToJsonValue(driveLogCreate.Status); + writer.WriteString("status", statusRawValue); + + writer.WriteString("user_id", driveLogCreate.UserId); + + writer.WriteString("car_id", driveLogCreate.CarId); + + if (driveLogCreate.EndOption.IsSet) + if (driveLogCreate.EndOption.Value != null) + writer.WriteString("end", driveLogCreate.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (driveLogCreate.EndMileageOption.IsSet) + if (driveLogCreate.EndMileageOption.Value != null) + writer.WriteNumber("end_mileage", driveLogCreate.EndMileageOption.Value!.Value); + else + writer.WriteNull("end_mileage"); + + if (driveLogCreate.RouteOption.IsSet) + if (driveLogCreate.RouteOption.Value != null) + writer.WriteString("route", driveLogCreate.Route); + else + writer.WriteNull("route"); + + if (driveLogCreate.PurposeOption.IsSet) + if (driveLogCreate.PurposeOption.Value != null) + writer.WriteString("purpose", driveLogCreate.Purpose); + else + writer.WriteNull("purpose"); + + if (driveLogCreate.VisitedOption.IsSet) + if (driveLogCreate.VisitedOption.Value != null) + writer.WriteString("visited", driveLogCreate.Visited); + else + writer.WriteNull("visited"); + + if (driveLogCreate.MetadataOption.IsSet) + if (driveLogCreate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, driveLogCreate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + if (driveLogCreate.StartLocationOption.IsSet) + if (driveLogCreate.StartLocationOption.Value != null) + { + writer.WritePropertyName("start_location"); + JsonSerializer.Serialize(writer, driveLogCreate.StartLocation, jsonSerializerOptions); + } + else + writer.WriteNull("start_location"); + if (driveLogCreate.EndLocationOption.IsSet) + if (driveLogCreate.EndLocationOption.Value != null) + { + writer.WritePropertyName("end_location"); + JsonSerializer.Serialize(writer, driveLogCreate.EndLocation, jsonSerializerOptions); + } + else + writer.WriteNull("end_location"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogStatus.cs b/sdk/dotnet/Timr.Api/Model/DriveLogStatus.cs new file mode 100644 index 0000000..a964459 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogStatus.cs @@ -0,0 +1,247 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Processing state of a Drive Log. `running` means the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + /// + /// Processing state of a Drive Log. `running` means the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + public enum DriveLogStatus + { + /// + /// Enum Changeable for value: changeable + /// + Changeable = 1, + + /// + /// Enum Locked for value: locked + /// + Locked = 2, + + /// + /// Enum Approved for value: approved + /// + Approved = 3, + + /// + /// Enum Cleared for value: cleared + /// + Cleared = 4, + + /// + /// Enum Closed for value: closed + /// + Closed = 5, + + /// + /// Enum Archived for value: archived + /// + Archived = 6, + + /// + /// Enum Running for value: running + /// + Running = 7 + } + + /// + /// Converts to and from the JSON value + /// + public static class DriveLogStatusValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static DriveLogStatus FromString(string value) + { + if (value.Equals("changeable")) + return DriveLogStatus.Changeable; + + if (value.Equals("locked")) + return DriveLogStatus.Locked; + + if (value.Equals("approved")) + return DriveLogStatus.Approved; + + if (value.Equals("cleared")) + return DriveLogStatus.Cleared; + + if (value.Equals("closed")) + return DriveLogStatus.Closed; + + if (value.Equals("archived")) + return DriveLogStatus.Archived; + + if (value.Equals("running")) + return DriveLogStatus.Running; + + throw new NotImplementedException($"Could not convert value to type DriveLogStatus: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static DriveLogStatus? FromStringOrDefault(string value) + { + if (value.Equals("changeable")) + return DriveLogStatus.Changeable; + + if (value.Equals("locked")) + return DriveLogStatus.Locked; + + if (value.Equals("approved")) + return DriveLogStatus.Approved; + + if (value.Equals("cleared")) + return DriveLogStatus.Cleared; + + if (value.Equals("closed")) + return DriveLogStatus.Closed; + + if (value.Equals("archived")) + return DriveLogStatus.Archived; + + if (value.Equals("running")) + return DriveLogStatus.Running; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(DriveLogStatus value) + { + if (value == DriveLogStatus.Changeable) + return "changeable"; + + if (value == DriveLogStatus.Locked) + return "locked"; + + if (value == DriveLogStatus.Approved) + return "approved"; + + if (value == DriveLogStatus.Cleared) + return "cleared"; + + if (value == DriveLogStatus.Closed) + return "closed"; + + if (value == DriveLogStatus.Archived) + return "archived"; + + if (value == DriveLogStatus.Running) + return "running"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class DriveLogStatusJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override DriveLogStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DriveLogStatus? result = rawValue == null + ? null + : DriveLogStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DriveLogStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogStatus driveLogStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(DriveLogStatusValueConverter.ToJsonValue(driveLogStatus).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class DriveLogStatusNullableJsonConverter : JsonConverter + { + /// + /// Returns a DriveLogStatus from the Json object + /// + /// + /// + /// + /// + public override DriveLogStatus? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DriveLogStatus? result = rawValue == null + ? null + : DriveLogStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DriveLogStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogStatus? driveLogStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(driveLogStatus.HasValue ? DriveLogStatusValueConverter.ToJsonValue(driveLogStatus.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogUpdate.cs b/sdk/dotnet/Timr.Api/Model/DriveLogUpdate.cs new file mode 100644 index 0000000..50fc486 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogUpdate.cs @@ -0,0 +1,506 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DriveLogUpdate + /// + public partial class DriveLogUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// RFC 3339 date-time (ISO-8601) + /// RFC 3339 date-time (ISO-8601) + /// changed + /// startMileage + /// endMileage + /// route + /// purpose + /// visited + /// driveLogCategoryId + /// status + /// metadata + /// startLocation + /// endLocation + [JsonConstructor] + public DriveLogUpdate(Option start = default, Option end = default, Option changed = default, Option startMileage = default, Option endMileage = default, Option route = default, Option purpose = default, Option visited = default, Option driveLogCategoryId = default, Option status = default, Option?> metadata = default, Option startLocation = default, Option endLocation = default) + { + StartOption = start; + EndOption = end; + ChangedOption = changed; + StartMileageOption = startMileage; + EndMileageOption = endMileage; + RouteOption = route; + PurposeOption = purpose; + VisitedOption = visited; + DriveLogCategoryIdOption = driveLogCategoryId; + StatusOption = status; + MetadataOption = metadata; + StartLocationOption = startLocation; + EndLocationOption = endLocation; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public DriveLogStatus? Status { get { return this.StatusOption.Value; } set { this.StatusOption = new(value); } } + + /// + /// Used to track the state of Start + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset? Start { get { return this.StartOption.Value; } set { this.StartOption = new(value); } } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of Changed + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ChangedOption { get; private set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool? Changed { get { return this.ChangedOption.Value; } set { this.ChangedOption = new(value); } } + + /// + /// Used to track the state of StartMileage + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartMileageOption { get; private set; } + + /// + /// Gets or Sets StartMileage + /// + [JsonPropertyName("start_mileage")] + public long? StartMileage { get { return this.StartMileageOption.Value; } set { this.StartMileageOption = new(value); } } + + /// + /// Used to track the state of EndMileage + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndMileageOption { get; private set; } + + /// + /// Gets or Sets EndMileage + /// + [JsonPropertyName("end_mileage")] + public long? EndMileage { get { return this.EndMileageOption.Value; } set { this.EndMileageOption = new(value); } } + + /// + /// Used to track the state of Route + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option RouteOption { get; private set; } + + /// + /// Gets or Sets Route + /// + [JsonPropertyName("route")] + public string? Route { get { return this.RouteOption.Value; } set { this.RouteOption = new(value); } } + + /// + /// Used to track the state of Purpose + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option PurposeOption { get; private set; } + + /// + /// Gets or Sets Purpose + /// + [JsonPropertyName("purpose")] + public string? Purpose { get { return this.PurposeOption.Value; } set { this.PurposeOption = new(value); } } + + /// + /// Used to track the state of Visited + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option VisitedOption { get; private set; } + + /// + /// Gets or Sets Visited + /// + [JsonPropertyName("visited")] + public string? Visited { get { return this.VisitedOption.Value; } set { this.VisitedOption = new(value); } } + + /// + /// Used to track the state of DriveLogCategoryId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DriveLogCategoryIdOption { get; private set; } + + /// + /// Gets or Sets DriveLogCategoryId + /// + [JsonPropertyName("drive_log_category_id")] + public string? DriveLogCategoryId { get { return this.DriveLogCategoryIdOption.Value; } set { this.DriveLogCategoryIdOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Used to track the state of StartLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartLocationOption { get; private set; } + + /// + /// Gets or Sets StartLocation + /// + [JsonPropertyName("start_location")] + public LocationUpdate? StartLocation { get { return this.StartLocationOption.Value; } set { this.StartLocationOption = new(value); } } + + /// + /// Used to track the state of EndLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndLocationOption { get; private set; } + + /// + /// Gets or Sets EndLocation + /// + [JsonPropertyName("end_location")] + public LocationUpdate? EndLocation { get { return this.EndLocationOption.Value; } set { this.EndLocationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DriveLogUpdate {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" StartMileage: ").Append(StartMileage).Append("\n"); + sb.Append(" EndMileage: ").Append(EndMileage).Append("\n"); + sb.Append(" Route: ").Append(Route).Append("\n"); + sb.Append(" Purpose: ").Append(Purpose).Append("\n"); + sb.Append(" Visited: ").Append(Visited).Append("\n"); + sb.Append(" DriveLogCategoryId: ").Append(DriveLogCategoryId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" StartLocation: ").Append(StartLocation).Append("\n"); + sb.Append(" EndLocation: ").Append(EndLocation).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DriveLogUpdateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DriveLogUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option end = default; + Option changed = default; + Option startMileage = default; + Option endMileage = default; + Option route = default; + Option purpose = default; + Option visited = default; + Option driveLogCategoryId = default; + Option status = default; + Option?> metadata = default; + Option startLocation = default; + Option endLocation = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "start_mileage": + startMileage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "end_mileage": + endMileage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "route": + route = new Option(utf8JsonReader.GetString()); + break; + case "purpose": + purpose = new Option(utf8JsonReader.GetString()); + break; + case "visited": + visited = new Option(utf8JsonReader.GetString()); + break; + case "drive_log_category_id": + driveLogCategoryId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(DriveLogStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_location": + startLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_location": + endLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class DriveLogUpdate."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class DriveLogUpdate."); + + if (startMileage.IsSet && startMileage.Value == null) + throw new ArgumentNullException(nameof(startMileage), "Property is not nullable for class DriveLogUpdate."); + + if (driveLogCategoryId.IsSet && driveLogCategoryId.Value == null) + throw new ArgumentNullException(nameof(driveLogCategoryId), "Property is not nullable for class DriveLogUpdate."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class DriveLogUpdate."); + + return new DriveLogUpdate(start, end, changed, startMileage, endMileage, route, purpose, visited, driveLogCategoryId, status, metadata, startLocation, endLocation); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogUpdate driveLogUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, driveLogUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DriveLogUpdate driveLogUpdate, JsonSerializerOptions jsonSerializerOptions) + { + if (driveLogUpdate.DriveLogCategoryIdOption.IsSet && driveLogUpdate.DriveLogCategoryId == null) + throw new ArgumentNullException(nameof(driveLogUpdate.DriveLogCategoryId), "Property is required for class DriveLogUpdate."); + + if (driveLogUpdate.StartOption.IsSet) + writer.WriteString("start", driveLogUpdate.StartOption.Value!.Value.ToString(StartFormat)); + + if (driveLogUpdate.EndOption.IsSet) + if (driveLogUpdate.EndOption.Value != null) + writer.WriteString("end", driveLogUpdate.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (driveLogUpdate.ChangedOption.IsSet) + writer.WriteBoolean("changed", driveLogUpdate.ChangedOption.Value!.Value); + + if (driveLogUpdate.StartMileageOption.IsSet) + writer.WriteNumber("start_mileage", driveLogUpdate.StartMileageOption.Value!.Value); + + if (driveLogUpdate.EndMileageOption.IsSet) + if (driveLogUpdate.EndMileageOption.Value != null) + writer.WriteNumber("end_mileage", driveLogUpdate.EndMileageOption.Value!.Value); + else + writer.WriteNull("end_mileage"); + + if (driveLogUpdate.RouteOption.IsSet) + if (driveLogUpdate.RouteOption.Value != null) + writer.WriteString("route", driveLogUpdate.Route); + else + writer.WriteNull("route"); + + if (driveLogUpdate.PurposeOption.IsSet) + if (driveLogUpdate.PurposeOption.Value != null) + writer.WriteString("purpose", driveLogUpdate.Purpose); + else + writer.WriteNull("purpose"); + + if (driveLogUpdate.VisitedOption.IsSet) + if (driveLogUpdate.VisitedOption.Value != null) + writer.WriteString("visited", driveLogUpdate.Visited); + else + writer.WriteNull("visited"); + + if (driveLogUpdate.DriveLogCategoryIdOption.IsSet) + writer.WriteString("drive_log_category_id", driveLogUpdate.DriveLogCategoryId); + + if (driveLogUpdate.StatusOption.IsSet) + { + var statusRawValue = DriveLogStatusValueConverter.ToJsonValue(driveLogUpdate.Status!.Value); + writer.WriteString("status", statusRawValue); + } + if (driveLogUpdate.MetadataOption.IsSet) + if (driveLogUpdate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, driveLogUpdate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + if (driveLogUpdate.StartLocationOption.IsSet) + if (driveLogUpdate.StartLocationOption.Value != null) + { + writer.WritePropertyName("start_location"); + JsonSerializer.Serialize(writer, driveLogUpdate.StartLocation, jsonSerializerOptions); + } + else + writer.WriteNull("start_location"); + if (driveLogUpdate.EndLocationOption.IsSet) + if (driveLogUpdate.EndLocationOption.Value != null) + { + writer.WritePropertyName("end_location"); + JsonSerializer.Serialize(writer, driveLogUpdate.EndLocation, jsonSerializerOptions); + } + else + writer.WriteNull("end_location"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogUpsert.cs b/sdk/dotnet/Timr.Api/Model/DriveLogUpsert.cs new file mode 100644 index 0000000..442caf8 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogUpsert.cs @@ -0,0 +1,450 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DriveLogUpsert + /// + public partial class DriveLogUpsert : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// RFC 3339 date-time (ISO-8601) + /// RFC 3339 date-time (ISO-8601) + /// changed + /// startMileage + /// endMileage + /// route + /// purpose + /// visited + /// driveLogCategoryId + /// status + /// metadata + [JsonConstructor] + public DriveLogUpsert(Option start = default, Option end = default, Option changed = default, Option startMileage = default, Option endMileage = default, Option route = default, Option purpose = default, Option visited = default, Option driveLogCategoryId = default, Option status = default, Option?> metadata = default) + { + StartOption = start; + EndOption = end; + ChangedOption = changed; + StartMileageOption = startMileage; + EndMileageOption = endMileage; + RouteOption = route; + PurposeOption = purpose; + VisitedOption = visited; + DriveLogCategoryIdOption = driveLogCategoryId; + StatusOption = status; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public DriveLogStatus? Status { get { return this.StatusOption.Value; } set { this.StatusOption = new(value); } } + + /// + /// Used to track the state of Start + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset? Start { get { return this.StartOption.Value; } set { this.StartOption = new(value); } } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of Changed + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ChangedOption { get; private set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool? Changed { get { return this.ChangedOption.Value; } set { this.ChangedOption = new(value); } } + + /// + /// Used to track the state of StartMileage + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartMileageOption { get; private set; } + + /// + /// Gets or Sets StartMileage + /// + [JsonPropertyName("start_mileage")] + public long? StartMileage { get { return this.StartMileageOption.Value; } set { this.StartMileageOption = new(value); } } + + /// + /// Used to track the state of EndMileage + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndMileageOption { get; private set; } + + /// + /// Gets or Sets EndMileage + /// + [JsonPropertyName("end_mileage")] + public long? EndMileage { get { return this.EndMileageOption.Value; } set { this.EndMileageOption = new(value); } } + + /// + /// Used to track the state of Route + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option RouteOption { get; private set; } + + /// + /// Gets or Sets Route + /// + [JsonPropertyName("route")] + public string? Route { get { return this.RouteOption.Value; } set { this.RouteOption = new(value); } } + + /// + /// Used to track the state of Purpose + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option PurposeOption { get; private set; } + + /// + /// Gets or Sets Purpose + /// + [JsonPropertyName("purpose")] + public string? Purpose { get { return this.PurposeOption.Value; } set { this.PurposeOption = new(value); } } + + /// + /// Used to track the state of Visited + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option VisitedOption { get; private set; } + + /// + /// Gets or Sets Visited + /// + [JsonPropertyName("visited")] + public string? Visited { get { return this.VisitedOption.Value; } set { this.VisitedOption = new(value); } } + + /// + /// Used to track the state of DriveLogCategoryId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DriveLogCategoryIdOption { get; private set; } + + /// + /// Gets or Sets DriveLogCategoryId + /// + [JsonPropertyName("drive_log_category_id")] + public string? DriveLogCategoryId { get { return this.DriveLogCategoryIdOption.Value; } set { this.DriveLogCategoryIdOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DriveLogUpsert {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" StartMileage: ").Append(StartMileage).Append("\n"); + sb.Append(" EndMileage: ").Append(EndMileage).Append("\n"); + sb.Append(" Route: ").Append(Route).Append("\n"); + sb.Append(" Purpose: ").Append(Purpose).Append("\n"); + sb.Append(" Visited: ").Append(Visited).Append("\n"); + sb.Append(" DriveLogCategoryId: ").Append(DriveLogCategoryId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DriveLogUpsertJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DriveLogUpsert Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option end = default; + Option changed = default; + Option startMileage = default; + Option endMileage = default; + Option route = default; + Option purpose = default; + Option visited = default; + Option driveLogCategoryId = default; + Option status = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "start_mileage": + startMileage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "end_mileage": + endMileage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "route": + route = new Option(utf8JsonReader.GetString()); + break; + case "purpose": + purpose = new Option(utf8JsonReader.GetString()); + break; + case "visited": + visited = new Option(utf8JsonReader.GetString()); + break; + case "drive_log_category_id": + driveLogCategoryId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(DriveLogStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class DriveLogUpsert."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class DriveLogUpsert."); + + if (startMileage.IsSet && startMileage.Value == null) + throw new ArgumentNullException(nameof(startMileage), "Property is not nullable for class DriveLogUpsert."); + + if (driveLogCategoryId.IsSet && driveLogCategoryId.Value == null) + throw new ArgumentNullException(nameof(driveLogCategoryId), "Property is not nullable for class DriveLogUpsert."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class DriveLogUpsert."); + + return new DriveLogUpsert(start, end, changed, startMileage, endMileage, route, purpose, visited, driveLogCategoryId, status, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogUpsert driveLogUpsert, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, driveLogUpsert, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DriveLogUpsert driveLogUpsert, JsonSerializerOptions jsonSerializerOptions) + { + if (driveLogUpsert.DriveLogCategoryIdOption.IsSet && driveLogUpsert.DriveLogCategoryId == null) + throw new ArgumentNullException(nameof(driveLogUpsert.DriveLogCategoryId), "Property is required for class DriveLogUpsert."); + + if (driveLogUpsert.StartOption.IsSet) + writer.WriteString("start", driveLogUpsert.StartOption.Value!.Value.ToString(StartFormat)); + + if (driveLogUpsert.EndOption.IsSet) + if (driveLogUpsert.EndOption.Value != null) + writer.WriteString("end", driveLogUpsert.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (driveLogUpsert.ChangedOption.IsSet) + writer.WriteBoolean("changed", driveLogUpsert.ChangedOption.Value!.Value); + + if (driveLogUpsert.StartMileageOption.IsSet) + writer.WriteNumber("start_mileage", driveLogUpsert.StartMileageOption.Value!.Value); + + if (driveLogUpsert.EndMileageOption.IsSet) + if (driveLogUpsert.EndMileageOption.Value != null) + writer.WriteNumber("end_mileage", driveLogUpsert.EndMileageOption.Value!.Value); + else + writer.WriteNull("end_mileage"); + + if (driveLogUpsert.RouteOption.IsSet) + if (driveLogUpsert.RouteOption.Value != null) + writer.WriteString("route", driveLogUpsert.Route); + else + writer.WriteNull("route"); + + if (driveLogUpsert.PurposeOption.IsSet) + if (driveLogUpsert.PurposeOption.Value != null) + writer.WriteString("purpose", driveLogUpsert.Purpose); + else + writer.WriteNull("purpose"); + + if (driveLogUpsert.VisitedOption.IsSet) + if (driveLogUpsert.VisitedOption.Value != null) + writer.WriteString("visited", driveLogUpsert.Visited); + else + writer.WriteNull("visited"); + + if (driveLogUpsert.DriveLogCategoryIdOption.IsSet) + writer.WriteString("drive_log_category_id", driveLogUpsert.DriveLogCategoryId); + + if (driveLogUpsert.StatusOption.IsSet) + { + var statusRawValue = DriveLogStatusValueConverter.ToJsonValue(driveLogUpsert.Status!.Value); + writer.WriteString("status", statusRawValue); + } + if (driveLogUpsert.MetadataOption.IsSet) + if (driveLogUpsert.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, driveLogUpsert.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogsPage.cs b/sdk/dotnet/Timr.Api/Model/DriveLogsPage.cs new file mode 100644 index 0000000..1c965d0 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogsPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// DriveLogsPage + /// + public partial class DriveLogsPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public DriveLogsPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class DriveLogsPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DriveLogsPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override DriveLogsPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class DriveLogsPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class DriveLogsPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class DriveLogsPage."); + + return new DriveLogsPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogsPage driveLogsPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, driveLogsPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, DriveLogsPage driveLogsPage, JsonSerializerOptions jsonSerializerOptions) + { + if (driveLogsPage.Data == null) + throw new ArgumentNullException(nameof(driveLogsPage.Data), "Property is required for class DriveLogsPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, driveLogsPage.Data, jsonSerializerOptions); + if (driveLogsPage.NextPageToken != null) + writer.WriteString("next_page_token", driveLogsPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DriveLogsSortColumn.cs b/sdk/dotnet/Timr.Api/Model/DriveLogsSortColumn.cs new file mode 100644 index 0000000..bfceb5c --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DriveLogsSortColumn.cs @@ -0,0 +1,177 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Drive Logs. + /// + /// Sort property for Drive Logs. + public enum DriveLogsSortColumn + { + /// + /// Enum Start for value: start + /// + Start = 1, + + /// + /// Enum LastModified for value: last_modified + /// + LastModified = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class DriveLogsSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static DriveLogsSortColumn FromString(string value) + { + if (value.Equals("start")) + return DriveLogsSortColumn.Start; + + if (value.Equals("last_modified")) + return DriveLogsSortColumn.LastModified; + + throw new NotImplementedException($"Could not convert value to type DriveLogsSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static DriveLogsSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("start")) + return DriveLogsSortColumn.Start; + + if (value.Equals("last_modified")) + return DriveLogsSortColumn.LastModified; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(DriveLogsSortColumn value) + { + if (value == DriveLogsSortColumn.Start) + return "start"; + + if (value == DriveLogsSortColumn.LastModified) + return "last_modified"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class DriveLogsSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override DriveLogsSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DriveLogsSortColumn? result = rawValue == null + ? null + : DriveLogsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DriveLogsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogsSortColumn driveLogsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(DriveLogsSortColumnValueConverter.ToJsonValue(driveLogsSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class DriveLogsSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a DriveLogsSortColumn from the Json object + /// + /// + /// + /// + /// + public override DriveLogsSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DriveLogsSortColumn? result = rawValue == null + ? null + : DriveLogsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DriveLogsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DriveLogsSortColumn? driveLogsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(driveLogsSortColumn.HasValue ? DriveLogsSortColumnValueConverter.ToJsonValue(driveLogsSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Duration.cs b/sdk/dotnet/Timr.Api/Model/Duration.cs new file mode 100644 index 0000000..08912da --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Duration.cs @@ -0,0 +1,210 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Duration + /// + public partial class Duration : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// type + /// Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + /// Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + [JsonConstructor] + public Duration(DurationType type, long minutes, long minutesRounded) + { + Type = type; + Minutes = minutes; + MinutesRounded = minutesRounded; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Type + /// + [JsonPropertyName("type")] + public DurationType Type { get; set; } + + /// + /// Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + /// + /// Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + /* 42 */ + [JsonPropertyName("minutes")] + public long Minutes { get; set; } + + /// + /// Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + /// + /// Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + /* 45 */ + [JsonPropertyName("minutes_rounded")] + public long MinutesRounded { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Duration {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Minutes: ").Append(Minutes).Append("\n"); + sb.Append(" MinutesRounded: ").Append(MinutesRounded).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class DurationJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Duration Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option minutes = default; + Option minutesRounded = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(DurationTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + case "minutes": + minutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "minutes_rounded": + minutesRounded = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Duration.", nameof(type)); + + if (!minutes.IsSet) + throw new ArgumentException("Property is required for class Duration.", nameof(minutes)); + + if (!minutesRounded.IsSet) + throw new ArgumentException("Property is required for class Duration.", nameof(minutesRounded)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class Duration."); + + if (minutes.IsSet && minutes.Value == null) + throw new ArgumentNullException(nameof(minutes), "Property is not nullable for class Duration."); + + if (minutesRounded.IsSet && minutesRounded.Value == null) + throw new ArgumentNullException(nameof(minutesRounded), "Property is not nullable for class Duration."); + + return new Duration(type.Value!.Value!, minutes.Value!.Value!, minutesRounded.Value!.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Duration duration, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, duration, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Duration duration, JsonSerializerOptions jsonSerializerOptions) + { + var typeRawValue = DurationTypeValueConverter.ToJsonValue(duration.Type); + writer.WriteString("type", typeRawValue); + + writer.WriteNumber("minutes", duration.Minutes); + + writer.WriteNumber("minutes_rounded", duration.MinutesRounded); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DurationType.cs b/sdk/dotnet/Timr.Api/Model/DurationType.cs new file mode 100644 index 0000000..d04e207 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DurationType.cs @@ -0,0 +1,191 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// How the duration of a single recording is expressed. Not to be confused with `DurationUnit`, which states the unit a Working Time Type is recorded in. + /// + /// How the duration of a single recording is expressed. Not to be confused with `DurationUnit`, which states the unit a Working Time Type is recorded in. + public enum DurationType + { + /// + /// Enum Minutes for value: minutes + /// + Minutes = 1, + + /// + /// Enum FullDay for value: full_day + /// + FullDay = 2, + + /// + /// Enum HalfDay for value: half_day + /// + HalfDay = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class DurationTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static DurationType FromString(string value) + { + if (value.Equals("minutes")) + return DurationType.Minutes; + + if (value.Equals("full_day")) + return DurationType.FullDay; + + if (value.Equals("half_day")) + return DurationType.HalfDay; + + throw new NotImplementedException($"Could not convert value to type DurationType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static DurationType? FromStringOrDefault(string value) + { + if (value.Equals("minutes")) + return DurationType.Minutes; + + if (value.Equals("full_day")) + return DurationType.FullDay; + + if (value.Equals("half_day")) + return DurationType.HalfDay; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(DurationType value) + { + if (value == DurationType.Minutes) + return "minutes"; + + if (value == DurationType.FullDay) + return "full_day"; + + if (value == DurationType.HalfDay) + return "half_day"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class DurationTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override DurationType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DurationType? result = rawValue == null + ? null + : DurationTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DurationType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DurationType durationType, JsonSerializerOptions options) + { + writer.WriteStringValue(DurationTypeValueConverter.ToJsonValue(durationType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class DurationTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a DurationType from the Json object + /// + /// + /// + /// + /// + public override DurationType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DurationType? result = rawValue == null + ? null + : DurationTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DurationType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DurationType? durationType, JsonSerializerOptions options) + { + writer.WriteStringValue(durationType.HasValue ? DurationTypeValueConverter.ToJsonValue(durationType.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/DurationUnit.cs b/sdk/dotnet/Timr.Api/Model/DurationUnit.cs new file mode 100644 index 0000000..10f0463 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/DurationUnit.cs @@ -0,0 +1,191 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Unit a Working Time Type is recorded in. Not to be confused with `DurationType`, which states how an individual recording's duration is expressed. + /// + /// Unit a Working Time Type is recorded in. Not to be confused with `DurationType`, which states how an individual recording's duration is expressed. + public enum DurationUnit + { + /// + /// Enum Minutes for value: minutes + /// + Minutes = 1, + + /// + /// Enum HalfDays for value: half_days + /// + HalfDays = 2, + + /// + /// Enum Days for value: days + /// + Days = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class DurationUnitValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static DurationUnit FromString(string value) + { + if (value.Equals("minutes")) + return DurationUnit.Minutes; + + if (value.Equals("half_days")) + return DurationUnit.HalfDays; + + if (value.Equals("days")) + return DurationUnit.Days; + + throw new NotImplementedException($"Could not convert value to type DurationUnit: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static DurationUnit? FromStringOrDefault(string value) + { + if (value.Equals("minutes")) + return DurationUnit.Minutes; + + if (value.Equals("half_days")) + return DurationUnit.HalfDays; + + if (value.Equals("days")) + return DurationUnit.Days; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(DurationUnit value) + { + if (value == DurationUnit.Minutes) + return "minutes"; + + if (value == DurationUnit.HalfDays) + return "half_days"; + + if (value == DurationUnit.Days) + return "days"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class DurationUnitJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override DurationUnit Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DurationUnit? result = rawValue == null + ? null + : DurationUnitValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DurationUnit to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DurationUnit durationUnit, JsonSerializerOptions options) + { + writer.WriteStringValue(DurationUnitValueConverter.ToJsonValue(durationUnit).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class DurationUnitNullableJsonConverter : JsonConverter + { + /// + /// Returns a DurationUnit from the Json object + /// + /// + /// + /// + /// + public override DurationUnit? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + DurationUnit? result = rawValue == null + ? null + : DurationUnitValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the DurationUnit to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DurationUnit? durationUnit, JsonSerializerOptions options) + { + writer.WriteStringValue(durationUnit.HasValue ? DurationUnitValueConverter.ToJsonValue(durationUnit.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Error.cs b/sdk/dotnet/Timr.Api/Model/Error.cs new file mode 100644 index 0000000..c41fc21 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Error.cs @@ -0,0 +1,355 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TIMR error response body, extending the Problem Details base with `timestamp`, `trace_id` and per-field `errors[]` for validation, binding, constraint, request-body deserialization, and reference-not-found errors. The semantic identifier is encoded in the `type` URI (e.g. `https://errors.timr.com/conflict/resource-outdated`). Slugs in the `type` URI are lowercase kebab-case: a top-level category (`validation`, `reference-not-found`, `conflict`, `forbidden`, `internal`) optionally followed by a specific sub-slug (`conflict/resource-outdated`, `validation/end-time-required`, `reference-not-found/user`). + /// + public partial class Error : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// type + /// title + /// status + /// timestamp + /// detail + /// instance + /// traceId + /// errors + [JsonConstructor] + public Error(string type, string title, int status, DateTimeOffset timestamp, Option detail = default, Option instance = default, Option traceId = default, Option?> errors = default) + { + Type = type; + Title = title; + Status = status; + Timestamp = timestamp; + DetailOption = detail; + InstanceOption = instance; + TraceIdOption = traceId; + ErrorsOption = errors; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Type + /// + /* https://errors.timr.com/validation/end-time-required */ + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Gets or Sets Title + /// + /* Bad Request */ + [JsonPropertyName("title")] + public string Title { get; set; } + + /// + /// Gets or Sets Status + /// + /* 400 */ + [JsonPropertyName("status")] + public int Status { get; set; } + + /// + /// Gets or Sets Timestamp + /// + /* 2026-05-25T09:42:11Z */ + [JsonPropertyName("timestamp")] + public DateTimeOffset Timestamp { get; set; } + + /// + /// Used to track the state of Detail + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DetailOption { get; private set; } + + /// + /// Gets or Sets Detail + /// + /* Concrete error message */ + [JsonPropertyName("detail")] + public string? Detail { get { return this.DetailOption.Value; } set { this.DetailOption = new(value); } } + + /// + /// Used to track the state of Instance + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option InstanceOption { get; private set; } + + /// + /// Gets or Sets Instance + /// + /* /working-times/12345 */ + [JsonPropertyName("instance")] + public string? Instance { get { return this.InstanceOption.Value; } set { this.InstanceOption = new(value); } } + + /// + /// Used to track the state of TraceId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option TraceIdOption { get; private set; } + + /// + /// Gets or Sets TraceId + /// + /* 4bf92f3577b34da6a3ce929d0e0e4736 */ + [JsonPropertyName("trace_id")] + public string? TraceId { get { return this.TraceIdOption.Value; } set { this.TraceIdOption = new(value); } } + + /// + /// Used to track the state of Errors + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ErrorsOption { get; private set; } + + /// + /// Gets or Sets Errors + /// + [JsonPropertyName("errors")] + public List? Errors { get { return this.ErrorsOption.Value; } set { this.ErrorsOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Error {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append(" TraceId: ").Append(TraceId).Append("\n"); + sb.Append(" Errors: ").Append(Errors).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ErrorJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Error Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option title = default; + Option status = default; + Option timestamp = default; + Option detail = default; + Option instance = default; + Option traceId = default; + Option?> errors = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + case "trace_id": + traceId = new Option(utf8JsonReader.GetString()); + break; + case "errors": + errors = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class Error.", nameof(type)); + + if (!title.IsSet) + throw new ArgumentException("Property is required for class Error.", nameof(title)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class Error.", nameof(status)); + + if (!timestamp.IsSet) + throw new ArgumentException("Property is required for class Error.", nameof(timestamp)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class Error."); + + if (title.IsSet && title.Value == null) + throw new ArgumentNullException(nameof(title), "Property is not nullable for class Error."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class Error."); + + if (timestamp.IsSet && timestamp.Value == null) + throw new ArgumentNullException(nameof(timestamp), "Property is not nullable for class Error."); + + if (detail.IsSet && detail.Value == null) + throw new ArgumentNullException(nameof(detail), "Property is not nullable for class Error."); + + if (instance.IsSet && instance.Value == null) + throw new ArgumentNullException(nameof(instance), "Property is not nullable for class Error."); + + return new Error(type.Value!, title.Value!, status.Value!.Value!, timestamp.Value!.Value!, detail, instance, traceId, errors); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Error error, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, error, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Error error, JsonSerializerOptions jsonSerializerOptions) + { + if (error.Type == null) + throw new ArgumentNullException(nameof(error.Type), "Property is required for class Error."); + + if (error.Title == null) + throw new ArgumentNullException(nameof(error.Title), "Property is required for class Error."); + + if (error.DetailOption.IsSet && error.Detail == null) + throw new ArgumentNullException(nameof(error.Detail), "Property is required for class Error."); + + if (error.InstanceOption.IsSet && error.Instance == null) + throw new ArgumentNullException(nameof(error.Instance), "Property is required for class Error."); + + writer.WriteString("type", error.Type); + + writer.WriteString("title", error.Title); + + writer.WriteNumber("status", error.Status); + + writer.WriteString("timestamp", error.Timestamp.ToString(TimestampFormat)); + + if (error.DetailOption.IsSet) + writer.WriteString("detail", error.Detail); + + if (error.InstanceOption.IsSet) + writer.WriteString("instance", error.Instance); + + if (error.TraceIdOption.IsSet) + if (error.TraceIdOption.Value != null) + writer.WriteString("trace_id", error.TraceId); + else + writer.WriteNull("trace_id"); + + if (error.ErrorsOption.IsSet) + if (error.ErrorsOption.Value != null) + { + writer.WritePropertyName("errors"); + JsonSerializer.Serialize(writer, error.Errors, jsonSerializerOptions); + } + else + writer.WriteNull("errors"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/ErrorEntry.cs b/sdk/dotnet/Timr.Api/Model/ErrorEntry.cs new file mode 100644 index 0000000..6609364 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/ErrorEntry.cs @@ -0,0 +1,217 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Field-level or sub-error entry, shaped like a sub-ProblemDetail. The `type` URI identifies the specific constraint or sub-error category (e.g. `validation/not-null` for a Bean Validation `@NotNull`, `validation/paused-working-time` for a TIMR custom validator code, `validation/type-mismatch` for a value that does not fit its target type, `validation/unknown-property` for a property the resource does not declare, `reference-not-found/user` for a `MappingException`). `field` is the JSONPath of the offending property in the request body, rooted at `$` — array elements included. An error about a query parameter names it plainly instead, without the `$.` prefix. + /// + public partial class ErrorEntry : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// type + /// detail + /// field + [JsonConstructor] + public ErrorEntry(string type, string detail, Option field = default) + { + Type = type; + Detail = detail; + FieldOption = field; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Type + /// + /* https://errors.timr.com/validation/paused-working-time */ + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Gets or Sets Detail + /// + /* break_times must contain exactly one break time of type 'ongoing' */ + [JsonPropertyName("detail")] + public string Detail { get; set; } + + /// + /// Used to track the state of Field + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option FieldOption { get; private set; } + + /// + /// Gets or Sets Field + /// + /* $.break_times[0].duration */ + [JsonPropertyName("field")] + public string? Field { get { return this.FieldOption.Value; } set { this.FieldOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ErrorEntry {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" Field: ").Append(Field).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ErrorEntryJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ErrorEntry Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option detail = default; + Option field = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "field": + field = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class ErrorEntry.", nameof(type)); + + if (!detail.IsSet) + throw new ArgumentException("Property is required for class ErrorEntry.", nameof(detail)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class ErrorEntry."); + + if (detail.IsSet && detail.Value == null) + throw new ArgumentNullException(nameof(detail), "Property is not nullable for class ErrorEntry."); + + return new ErrorEntry(type.Value!, detail.Value!, field); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ErrorEntry errorEntry, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, errorEntry, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ErrorEntry errorEntry, JsonSerializerOptions jsonSerializerOptions) + { + if (errorEntry.Type == null) + throw new ArgumentNullException(nameof(errorEntry.Type), "Property is required for class ErrorEntry."); + + if (errorEntry.Detail == null) + throw new ArgumentNullException(nameof(errorEntry.Detail), "Property is required for class ErrorEntry."); + + writer.WriteString("type", errorEntry.Type); + + writer.WriteString("detail", errorEntry.Detail); + + if (errorEntry.FieldOption.IsSet) + if (errorEntry.FieldOption.Value != null) + writer.WriteString("field", errorEntry.Field); + else + writer.WriteNull("field"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/FlexTimeIndicator.cs b/sdk/dotnet/Timr.Api/Model/FlexTimeIndicator.cs new file mode 100644 index 0000000..32de3dc --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/FlexTimeIndicator.cs @@ -0,0 +1,191 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Traffic-light rating of the flex time balance. The thresholds are an account setting and are not part of this contract. + /// + /// Traffic-light rating of the flex time balance. The thresholds are an account setting and are not part of this contract. + public enum FlexTimeIndicator + { + /// + /// Enum Green for value: green + /// + Green = 1, + + /// + /// Enum Yellow for value: yellow + /// + Yellow = 2, + + /// + /// Enum Red for value: red + /// + Red = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class FlexTimeIndicatorValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static FlexTimeIndicator FromString(string value) + { + if (value.Equals("green")) + return FlexTimeIndicator.Green; + + if (value.Equals("yellow")) + return FlexTimeIndicator.Yellow; + + if (value.Equals("red")) + return FlexTimeIndicator.Red; + + throw new NotImplementedException($"Could not convert value to type FlexTimeIndicator: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static FlexTimeIndicator? FromStringOrDefault(string value) + { + if (value.Equals("green")) + return FlexTimeIndicator.Green; + + if (value.Equals("yellow")) + return FlexTimeIndicator.Yellow; + + if (value.Equals("red")) + return FlexTimeIndicator.Red; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(FlexTimeIndicator value) + { + if (value == FlexTimeIndicator.Green) + return "green"; + + if (value == FlexTimeIndicator.Yellow) + return "yellow"; + + if (value == FlexTimeIndicator.Red) + return "red"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class FlexTimeIndicatorJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override FlexTimeIndicator Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + FlexTimeIndicator? result = rawValue == null + ? null + : FlexTimeIndicatorValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the FlexTimeIndicator to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FlexTimeIndicator flexTimeIndicator, JsonSerializerOptions options) + { + writer.WriteStringValue(FlexTimeIndicatorValueConverter.ToJsonValue(flexTimeIndicator).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class FlexTimeIndicatorNullableJsonConverter : JsonConverter + { + /// + /// Returns a FlexTimeIndicator from the Json object + /// + /// + /// + /// + /// + public override FlexTimeIndicator? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + FlexTimeIndicator? result = rawValue == null + ? null + : FlexTimeIndicatorValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the FlexTimeIndicator to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, FlexTimeIndicator? flexTimeIndicator, JsonSerializerOptions options) + { + writer.WriteStringValue(flexTimeIndicator.HasValue ? FlexTimeIndicatorValueConverter.ToJsonValue(flexTimeIndicator.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Holiday.cs b/sdk/dotnet/Timr.Api/Model/Holiday.cs new file mode 100644 index 0000000..394e58f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Holiday.cs @@ -0,0 +1,212 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Holiday + /// + public partial class Holiday : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// RFC 3339 date (ISO-8601) + /// description + /// halfDay + [JsonConstructor] + public Holiday(DateOnly date, string description, bool halfDay) + { + Date = date; + Description = description; + HalfDay = halfDay; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("date")] + public DateOnly Date { get; set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// Gets or Sets HalfDay + /// + [JsonPropertyName("half_day")] + public bool HalfDay { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Holiday {\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" HalfDay: ").Append(HalfDay).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HolidayJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Date + /// + public static string DateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Holiday Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option date = default; + Option description = default; + Option halfDay = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "date": + date = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + case "half_day": + halfDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!date.IsSet) + throw new ArgumentException("Property is required for class Holiday.", nameof(date)); + + if (!description.IsSet) + throw new ArgumentException("Property is required for class Holiday.", nameof(description)); + + if (!halfDay.IsSet) + throw new ArgumentException("Property is required for class Holiday.", nameof(halfDay)); + + if (date.IsSet && date.Value == null) + throw new ArgumentNullException(nameof(date), "Property is not nullable for class Holiday."); + + if (description.IsSet && description.Value == null) + throw new ArgumentNullException(nameof(description), "Property is not nullable for class Holiday."); + + if (halfDay.IsSet && halfDay.Value == null) + throw new ArgumentNullException(nameof(halfDay), "Property is not nullable for class Holiday."); + + return new Holiday(date.Value!.Value!, description.Value!, halfDay.Value!.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Holiday holiday, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, holiday, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Holiday holiday, JsonSerializerOptions jsonSerializerOptions) + { + if (holiday.Description == null) + throw new ArgumentNullException(nameof(holiday.Description), "Property is required for class Holiday."); + + writer.WriteString("date", holiday.Date.ToString(DateFormat)); + + writer.WriteString("description", holiday.Description); + + writer.WriteBoolean("half_day", holiday.HalfDay); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/HolidayCalendarPartial.cs b/sdk/dotnet/Timr.Api/Model/HolidayCalendarPartial.cs new file mode 100644 index 0000000..ef50786 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/HolidayCalendarPartial.cs @@ -0,0 +1,189 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// A holiday calendar. Its holidays are either generated automatically or maintained manually. + /// + public partial class HolidayCalendarPartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// description + [JsonConstructor] + public HolidayCalendarPartial(string id, string description) + { + Id = id; + Description = description; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HolidayCalendarPartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HolidayCalendarPartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override HolidayCalendarPartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option description = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class HolidayCalendarPartial.", nameof(id)); + + if (!description.IsSet) + throw new ArgumentException("Property is required for class HolidayCalendarPartial.", nameof(description)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class HolidayCalendarPartial."); + + if (description.IsSet && description.Value == null) + throw new ArgumentNullException(nameof(description), "Property is not nullable for class HolidayCalendarPartial."); + + return new HolidayCalendarPartial(id.Value!, description.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HolidayCalendarPartial holidayCalendarPartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, holidayCalendarPartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HolidayCalendarPartial holidayCalendarPartial, JsonSerializerOptions jsonSerializerOptions) + { + if (holidayCalendarPartial.Id == null) + throw new ArgumentNullException(nameof(holidayCalendarPartial.Id), "Property is required for class HolidayCalendarPartial."); + + if (holidayCalendarPartial.Description == null) + throw new ArgumentNullException(nameof(holidayCalendarPartial.Description), "Property is required for class HolidayCalendarPartial."); + + writer.WriteString("id", holidayCalendarPartial.Id); + + writer.WriteString("description", holidayCalendarPartial.Description); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/HolidayCalendarsPage.cs b/sdk/dotnet/Timr.Api/Model/HolidayCalendarsPage.cs new file mode 100644 index 0000000..1820ae6 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/HolidayCalendarsPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// HolidayCalendarsPage + /// + public partial class HolidayCalendarsPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public HolidayCalendarsPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HolidayCalendarsPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HolidayCalendarsPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override HolidayCalendarsPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class HolidayCalendarsPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class HolidayCalendarsPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class HolidayCalendarsPage."); + + return new HolidayCalendarsPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HolidayCalendarsPage holidayCalendarsPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, holidayCalendarsPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HolidayCalendarsPage holidayCalendarsPage, JsonSerializerOptions jsonSerializerOptions) + { + if (holidayCalendarsPage.Data == null) + throw new ArgumentNullException(nameof(holidayCalendarsPage.Data), "Property is required for class HolidayCalendarsPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, holidayCalendarsPage.Data, jsonSerializerOptions); + if (holidayCalendarsPage.NextPageToken != null) + writer.WriteString("next_page_token", holidayCalendarsPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/HolidayCalendarsSortColumn.cs b/sdk/dotnet/Timr.Api/Model/HolidayCalendarsSortColumn.cs new file mode 100644 index 0000000..1eced5c --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/HolidayCalendarsSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Holiday Calendars. + /// + /// Sort property for Holiday Calendars. + public enum HolidayCalendarsSortColumn + { + /// + /// Enum Description for value: description + /// + Description = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class HolidayCalendarsSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static HolidayCalendarsSortColumn FromString(string value) + { + if (value.Equals("description")) + return HolidayCalendarsSortColumn.Description; + + throw new NotImplementedException($"Could not convert value to type HolidayCalendarsSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static HolidayCalendarsSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("description")) + return HolidayCalendarsSortColumn.Description; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(HolidayCalendarsSortColumn value) + { + if (value == HolidayCalendarsSortColumn.Description) + return "description"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class HolidayCalendarsSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override HolidayCalendarsSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + HolidayCalendarsSortColumn? result = rawValue == null + ? null + : HolidayCalendarsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the HolidayCalendarsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HolidayCalendarsSortColumn holidayCalendarsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(HolidayCalendarsSortColumnValueConverter.ToJsonValue(holidayCalendarsSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class HolidayCalendarsSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a HolidayCalendarsSortColumn from the Json object + /// + /// + /// + /// + /// + public override HolidayCalendarsSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + HolidayCalendarsSortColumn? result = rawValue == null + ? null + : HolidayCalendarsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the HolidayCalendarsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HolidayCalendarsSortColumn? holidayCalendarsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(holidayCalendarsSortColumn.HasValue ? HolidayCalendarsSortColumnValueConverter.ToJsonValue(holidayCalendarsSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/HolidaysPage.cs b/sdk/dotnet/Timr.Api/Model/HolidaysPage.cs new file mode 100644 index 0000000..3b40f4e --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/HolidaysPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// HolidaysPage + /// + public partial class HolidaysPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public HolidaysPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class HolidaysPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class HolidaysPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override HolidaysPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class HolidaysPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class HolidaysPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class HolidaysPage."); + + return new HolidaysPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HolidaysPage holidaysPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, holidaysPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, HolidaysPage holidaysPage, JsonSerializerOptions jsonSerializerOptions) + { + if (holidaysPage.Data == null) + throw new ArgumentNullException(nameof(holidaysPage.Data), "Property is required for class HolidaysPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, holidaysPage.Data, jsonSerializerOptions); + if (holidaysPage.NextPageToken != null) + writer.WriteString("next_page_token", holidaysPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/HolidaysSortColumn.cs b/sdk/dotnet/Timr.Api/Model/HolidaysSortColumn.cs new file mode 100644 index 0000000..ed6096d --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/HolidaysSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Holidays. + /// + /// Sort property for Holidays. + public enum HolidaysSortColumn + { + /// + /// Enum Date for value: date + /// + Date = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class HolidaysSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static HolidaysSortColumn FromString(string value) + { + if (value.Equals("date")) + return HolidaysSortColumn.Date; + + throw new NotImplementedException($"Could not convert value to type HolidaysSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static HolidaysSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("date")) + return HolidaysSortColumn.Date; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(HolidaysSortColumn value) + { + if (value == HolidaysSortColumn.Date) + return "date"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class HolidaysSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override HolidaysSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + HolidaysSortColumn? result = rawValue == null + ? null + : HolidaysSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the HolidaysSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HolidaysSortColumn holidaysSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(HolidaysSortColumnValueConverter.ToJsonValue(holidaysSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class HolidaysSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a HolidaysSortColumn from the Json object + /// + /// + /// + /// + /// + public override HolidaysSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + HolidaysSortColumn? result = rawValue == null + ? null + : HolidaysSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the HolidaysSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, HolidaysSortColumn? holidaysSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(holidaysSortColumn.HasValue ? HolidaysSortColumnValueConverter.ToJsonValue(holidaysSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Location.cs b/sdk/dotnet/Timr.Api/Model/Location.cs new file mode 100644 index 0000000..c8e67c1 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Location.cs @@ -0,0 +1,269 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Location + /// + public partial class Location : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Latitude in decimal degrees. + /// Longitude in decimal degrees. + /// RFC 3339 date-time (ISO-8601) + /// formattedAddress + /// Horizontal GPS accuracy in meters. + [JsonConstructor] + public Location(float? lat = default, float? lon = default, Option timestamp = default, Option formattedAddress = default, float? accuracy = default) + { + Lat = lat; + Lon = lon; + TimestampOption = timestamp; + FormattedAddressOption = formattedAddress; + Accuracy = accuracy; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Latitude in decimal degrees. + /// + /// Latitude in decimal degrees. + /* 48.2455964 */ + [JsonPropertyName("lat")] + public float? Lat { get; set; } + + /// + /// Longitude in decimal degrees. + /// + /// Longitude in decimal degrees. + /* 13.0543811 */ + [JsonPropertyName("lon")] + public float? Lon { get; set; } + + /// + /// Used to track the state of Timestamp + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option TimestampOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this.TimestampOption.Value; } set { this.TimestampOption = new(value); } } + + /// + /// Used to track the state of FormattedAddress + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option FormattedAddressOption { get; private set; } + + /// + /// Gets or Sets FormattedAddress + /// + /* Salzburger Straße 2, 5280 Braunau am Inn */ + [JsonPropertyName("formatted_address")] + public string? FormattedAddress { get { return this.FormattedAddressOption.Value; } set { this.FormattedAddressOption = new(value); } } + + /// + /// Horizontal GPS accuracy in meters. + /// + /// Horizontal GPS accuracy in meters. + /* 12.5 */ + [JsonPropertyName("accuracy")] + public float? Accuracy { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Location {\n"); + sb.Append(" Lat: ").Append(Lat).Append("\n"); + sb.Append(" Lon: ").Append(Lon).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" FormattedAddress: ").Append(FormattedAddress).Append("\n"); + sb.Append(" Accuracy: ").Append(Accuracy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LocationJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Location Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option lat = default; + Option lon = default; + Option timestamp = default; + Option formattedAddress = default; + Option accuracy = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "lat": + lat = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + case "lon": + lon = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "formatted_address": + formattedAddress = new Option(utf8JsonReader.GetString()); + break; + case "accuracy": + accuracy = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + default: + break; + } + } + } + + if (!lat.IsSet) + throw new ArgumentException("Property is required for class Location.", nameof(lat)); + + if (!lon.IsSet) + throw new ArgumentException("Property is required for class Location.", nameof(lon)); + + if (!accuracy.IsSet) + throw new ArgumentException("Property is required for class Location.", nameof(accuracy)); + + return new Location(lat.Value!, lon.Value!, timestamp, formattedAddress, accuracy.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Location location, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, location, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Location location, JsonSerializerOptions jsonSerializerOptions) + { + if (location.Lat != null) + writer.WriteNumber("lat", location.Lat.Value); + else + writer.WriteNull("lat"); + + if (location.Lon != null) + writer.WriteNumber("lon", location.Lon.Value); + else + writer.WriteNull("lon"); + + if (location.TimestampOption.IsSet) + if (location.TimestampOption.Value != null) + writer.WriteString("timestamp", location.TimestampOption.Value!.Value.ToString(TimestampFormat)); + else + writer.WriteNull("timestamp"); + + if (location.FormattedAddressOption.IsSet) + if (location.FormattedAddressOption.Value != null) + writer.WriteString("formatted_address", location.FormattedAddress); + else + writer.WriteNull("formatted_address"); + + if (location.Accuracy != null) + writer.WriteNumber("accuracy", location.Accuracy.Value); + else + writer.WriteNull("accuracy"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/LocationCreate.cs b/sdk/dotnet/Timr.Api/Model/LocationCreate.cs new file mode 100644 index 0000000..4309b40 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/LocationCreate.cs @@ -0,0 +1,274 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// LocationCreate + /// + public partial class LocationCreate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Latitude in decimal degrees. + /// Longitude in decimal degrees. + /// RFC 3339 date-time (ISO-8601) + /// formattedAddress + /// Horizontal GPS accuracy in meters. + [JsonConstructor] + public LocationCreate(float lat, float lon, Option timestamp = default, Option formattedAddress = default, Option accuracy = default) + { + Lat = lat; + Lon = lon; + TimestampOption = timestamp; + FormattedAddressOption = formattedAddress; + AccuracyOption = accuracy; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Latitude in decimal degrees. + /// + /// Latitude in decimal degrees. + /* 48.2455964 */ + [JsonPropertyName("lat")] + public float Lat { get; set; } + + /// + /// Longitude in decimal degrees. + /// + /// Longitude in decimal degrees. + /* 13.0543811 */ + [JsonPropertyName("lon")] + public float Lon { get; set; } + + /// + /// Used to track the state of Timestamp + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option TimestampOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this.TimestampOption.Value; } set { this.TimestampOption = new(value); } } + + /// + /// Used to track the state of FormattedAddress + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option FormattedAddressOption { get; private set; } + + /// + /// Gets or Sets FormattedAddress + /// + /* Salzburger Straße 2, 5280 Braunau am Inn */ + [JsonPropertyName("formatted_address")] + public string? FormattedAddress { get { return this.FormattedAddressOption.Value; } set { this.FormattedAddressOption = new(value); } } + + /// + /// Used to track the state of Accuracy + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option AccuracyOption { get; private set; } + + /// + /// Horizontal GPS accuracy in meters. + /// + /// Horizontal GPS accuracy in meters. + /* 12.5 */ + [JsonPropertyName("accuracy")] + public float? Accuracy { get { return this.AccuracyOption.Value; } set { this.AccuracyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LocationCreate {\n"); + sb.Append(" Lat: ").Append(Lat).Append("\n"); + sb.Append(" Lon: ").Append(Lon).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" FormattedAddress: ").Append(FormattedAddress).Append("\n"); + sb.Append(" Accuracy: ").Append(Accuracy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LocationCreateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override LocationCreate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option lat = default; + Option lon = default; + Option timestamp = default; + Option formattedAddress = default; + Option accuracy = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "lat": + lat = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + case "lon": + lon = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "formatted_address": + formattedAddress = new Option(utf8JsonReader.GetString()); + break; + case "accuracy": + accuracy = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + default: + break; + } + } + } + + if (!lat.IsSet) + throw new ArgumentException("Property is required for class LocationCreate.", nameof(lat)); + + if (!lon.IsSet) + throw new ArgumentException("Property is required for class LocationCreate.", nameof(lon)); + + if (lat.IsSet && lat.Value == null) + throw new ArgumentNullException(nameof(lat), "Property is not nullable for class LocationCreate."); + + if (lon.IsSet && lon.Value == null) + throw new ArgumentNullException(nameof(lon), "Property is not nullable for class LocationCreate."); + + return new LocationCreate(lat.Value!.Value!, lon.Value!.Value!, timestamp, formattedAddress, accuracy); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LocationCreate locationCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, locationCreate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LocationCreate locationCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("lat", locationCreate.Lat); + + writer.WriteNumber("lon", locationCreate.Lon); + + if (locationCreate.TimestampOption.IsSet) + if (locationCreate.TimestampOption.Value != null) + writer.WriteString("timestamp", locationCreate.TimestampOption.Value!.Value.ToString(TimestampFormat)); + else + writer.WriteNull("timestamp"); + + if (locationCreate.FormattedAddressOption.IsSet) + if (locationCreate.FormattedAddressOption.Value != null) + writer.WriteString("formatted_address", locationCreate.FormattedAddress); + else + writer.WriteNull("formatted_address"); + + if (locationCreate.AccuracyOption.IsSet) + if (locationCreate.AccuracyOption.Value != null) + writer.WriteNumber("accuracy", locationCreate.AccuracyOption.Value!.Value); + else + writer.WriteNull("accuracy"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/LocationUpdate.cs b/sdk/dotnet/Timr.Api/Model/LocationUpdate.cs new file mode 100644 index 0000000..2feccde --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/LocationUpdate.cs @@ -0,0 +1,284 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// LocationUpdate + /// + public partial class LocationUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Latitude in decimal degrees. + /// Longitude in decimal degrees. + /// RFC 3339 date-time (ISO-8601) + /// formattedAddress + /// Horizontal GPS accuracy in meters. + [JsonConstructor] + public LocationUpdate(Option lat = default, Option lon = default, Option timestamp = default, Option formattedAddress = default, Option accuracy = default) + { + LatOption = lat; + LonOption = lon; + TimestampOption = timestamp; + FormattedAddressOption = formattedAddress; + AccuracyOption = accuracy; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Lat + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LatOption { get; private set; } + + /// + /// Latitude in decimal degrees. + /// + /// Latitude in decimal degrees. + /* 48.2455964 */ + [JsonPropertyName("lat")] + public float? Lat { get { return this.LatOption.Value; } set { this.LatOption = new(value); } } + + /// + /// Used to track the state of Lon + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LonOption { get; private set; } + + /// + /// Longitude in decimal degrees. + /// + /// Longitude in decimal degrees. + /* 13.0543811 */ + [JsonPropertyName("lon")] + public float? Lon { get { return this.LonOption.Value; } set { this.LonOption = new(value); } } + + /// + /// Used to track the state of Timestamp + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option TimestampOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("timestamp")] + public DateTimeOffset? Timestamp { get { return this.TimestampOption.Value; } set { this.TimestampOption = new(value); } } + + /// + /// Used to track the state of FormattedAddress + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option FormattedAddressOption { get; private set; } + + /// + /// Gets or Sets FormattedAddress + /// + /* Salzburger Straße 2, 5280 Braunau am Inn */ + [JsonPropertyName("formatted_address")] + public string? FormattedAddress { get { return this.FormattedAddressOption.Value; } set { this.FormattedAddressOption = new(value); } } + + /// + /// Used to track the state of Accuracy + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option AccuracyOption { get; private set; } + + /// + /// Horizontal GPS accuracy in meters. + /// + /// Horizontal GPS accuracy in meters. + /* 12.5 */ + [JsonPropertyName("accuracy")] + public float? Accuracy { get { return this.AccuracyOption.Value; } set { this.AccuracyOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class LocationUpdate {\n"); + sb.Append(" Lat: ").Append(Lat).Append("\n"); + sb.Append(" Lon: ").Append(Lon).Append("\n"); + sb.Append(" Timestamp: ").Append(Timestamp).Append("\n"); + sb.Append(" FormattedAddress: ").Append(FormattedAddress).Append("\n"); + sb.Append(" Accuracy: ").Append(Accuracy).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class LocationUpdateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Timestamp + /// + public static string TimestampFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override LocationUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option lat = default; + Option lon = default; + Option timestamp = default; + Option formattedAddress = default; + Option accuracy = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "lat": + lat = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + case "lon": + lon = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + case "timestamp": + timestamp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "formatted_address": + formattedAddress = new Option(utf8JsonReader.GetString()); + break; + case "accuracy": + accuracy = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + default: + break; + } + } + } + + if (lat.IsSet && lat.Value == null) + throw new ArgumentNullException(nameof(lat), "Property is not nullable for class LocationUpdate."); + + if (lon.IsSet && lon.Value == null) + throw new ArgumentNullException(nameof(lon), "Property is not nullable for class LocationUpdate."); + + return new LocationUpdate(lat, lon, timestamp, formattedAddress, accuracy); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, LocationUpdate locationUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, locationUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, LocationUpdate locationUpdate, JsonSerializerOptions jsonSerializerOptions) + { + if (locationUpdate.LatOption.IsSet) + writer.WriteNumber("lat", locationUpdate.LatOption.Value!.Value); + + if (locationUpdate.LonOption.IsSet) + writer.WriteNumber("lon", locationUpdate.LonOption.Value!.Value); + + if (locationUpdate.TimestampOption.IsSet) + if (locationUpdate.TimestampOption.Value != null) + writer.WriteString("timestamp", locationUpdate.TimestampOption.Value!.Value.ToString(TimestampFormat)); + else + writer.WriteNull("timestamp"); + + if (locationUpdate.FormattedAddressOption.IsSet) + if (locationUpdate.FormattedAddressOption.Value != null) + writer.WriteString("formatted_address", locationUpdate.FormattedAddress); + else + writer.WriteNull("formatted_address"); + + if (locationUpdate.AccuracyOption.IsSet) + if (locationUpdate.AccuracyOption.Value != null) + writer.WriteNumber("accuracy", locationUpdate.AccuracyOption.Value!.Value); + else + writer.WriteNull("accuracy"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/NormalWorkingTimes.cs b/sdk/dotnet/Timr.Api/Model/NormalWorkingTimes.cs new file mode 100644 index 0000000..0af407c --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/NormalWorkingTimes.cs @@ -0,0 +1,192 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// NormalWorkingTimes + /// + public partial class NormalWorkingTimes : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// start + /// end + [JsonConstructor] + public NormalWorkingTimes(Option start = default, Option end = default) + { + StartOption = start; + EndOption = end; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Start + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartOption { get; private set; } + + /// + /// Gets or Sets Start + /// + [JsonPropertyName("start")] + public string? Start { get { return this.StartOption.Value; } set { this.StartOption = new(value); } } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// Gets or Sets End + /// + [JsonPropertyName("end")] + public string? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NormalWorkingTimes {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NormalWorkingTimesJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override NormalWorkingTimes Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option end = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(utf8JsonReader.GetString()); + break; + case "end": + end = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + return new NormalWorkingTimes(start, end); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NormalWorkingTimes normalWorkingTimes, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, normalWorkingTimes, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, NormalWorkingTimes normalWorkingTimes, JsonSerializerOptions jsonSerializerOptions) + { + if (normalWorkingTimes.StartOption.IsSet) + if (normalWorkingTimes.StartOption.Value != null) + writer.WriteString("start", normalWorkingTimes.Start); + else + writer.WriteNull("start"); + + if (normalWorkingTimes.EndOption.IsSet) + if (normalWorkingTimes.EndOption.Value != null) + writer.WriteString("end", normalWorkingTimes.End); + else + writer.WriteNull("end"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/OvertimeSurchargeAccount.cs b/sdk/dotnet/Timr.Api/Model/OvertimeSurchargeAccount.cs new file mode 100644 index 0000000..015e1eb --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/OvertimeSurchargeAccount.cs @@ -0,0 +1,203 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// OvertimeSurchargeAccount + /// + public partial class OvertimeSurchargeAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// balanceLastPeriodMinutes + /// newMinutes + /// balanceTotalMinutes + [JsonConstructor] + public OvertimeSurchargeAccount(int? balanceLastPeriodMinutes = default, int? newMinutes = default, int? balanceTotalMinutes = default) + { + BalanceLastPeriodMinutes = balanceLastPeriodMinutes; + NewMinutes = newMinutes; + BalanceTotalMinutes = balanceTotalMinutes; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets BalanceLastPeriodMinutes + /// + [JsonPropertyName("balance_last_period_minutes")] + public int? BalanceLastPeriodMinutes { get; set; } + + /// + /// Gets or Sets NewMinutes + /// + [JsonPropertyName("new_minutes")] + public int? NewMinutes { get; set; } + + /// + /// Gets or Sets BalanceTotalMinutes + /// + [JsonPropertyName("balance_total_minutes")] + public int? BalanceTotalMinutes { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OvertimeSurchargeAccount {\n"); + sb.Append(" BalanceLastPeriodMinutes: ").Append(BalanceLastPeriodMinutes).Append("\n"); + sb.Append(" NewMinutes: ").Append(NewMinutes).Append("\n"); + sb.Append(" BalanceTotalMinutes: ").Append(BalanceTotalMinutes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OvertimeSurchargeAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override OvertimeSurchargeAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceLastPeriodMinutes = default; + Option newMinutes = default; + Option balanceTotalMinutes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "balance_last_period_minutes": + balanceLastPeriodMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "new_minutes": + newMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "balance_total_minutes": + balanceTotalMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + default: + break; + } + } + } + + if (!balanceLastPeriodMinutes.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeAccount.", nameof(balanceLastPeriodMinutes)); + + if (!newMinutes.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeAccount.", nameof(newMinutes)); + + if (!balanceTotalMinutes.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeAccount.", nameof(balanceTotalMinutes)); + + return new OvertimeSurchargeAccount(balanceLastPeriodMinutes.Value!, newMinutes.Value!, balanceTotalMinutes.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OvertimeSurchargeAccount overtimeSurchargeAccount, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, overtimeSurchargeAccount, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OvertimeSurchargeAccount overtimeSurchargeAccount, JsonSerializerOptions jsonSerializerOptions) + { + if (overtimeSurchargeAccount.BalanceLastPeriodMinutes != null) + writer.WriteNumber("balance_last_period_minutes", overtimeSurchargeAccount.BalanceLastPeriodMinutes.Value); + else + writer.WriteNull("balance_last_period_minutes"); + + if (overtimeSurchargeAccount.NewMinutes != null) + writer.WriteNumber("new_minutes", overtimeSurchargeAccount.NewMinutes.Value); + else + writer.WriteNull("new_minutes"); + + if (overtimeSurchargeAccount.BalanceTotalMinutes != null) + writer.WriteNumber("balance_total_minutes", overtimeSurchargeAccount.BalanceTotalMinutes.Value); + else + writer.WriteNull("balance_total_minutes"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/OvertimeSurchargeAccounts.cs b/sdk/dotnet/Timr.Api/Model/OvertimeSurchargeAccounts.cs new file mode 100644 index 0000000..622a26f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/OvertimeSurchargeAccounts.cs @@ -0,0 +1,233 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// OvertimeSurchargeAccounts + /// + public partial class OvertimeSurchargeAccounts : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// rule + /// overtime + /// surcharge + /// percentage + [JsonConstructor] + public OvertimeSurchargeAccounts(OvertimeSurchargeRule rule, OvertimeSurchargeAccount overtime, OvertimeSurchargeAccount surcharge, decimal? percentage = default) + { + Rule = rule; + Overtime = overtime; + Surcharge = surcharge; + Percentage = percentage; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Rule + /// + [JsonPropertyName("rule")] + public OvertimeSurchargeRule Rule { get; set; } + + /// + /// Gets or Sets Overtime + /// + [JsonPropertyName("overtime")] + public OvertimeSurchargeAccount Overtime { get; set; } + + /// + /// Gets or Sets Surcharge + /// + [JsonPropertyName("surcharge")] + public OvertimeSurchargeAccount Surcharge { get; set; } + + /// + /// Gets or Sets Percentage + /// + [JsonPropertyName("percentage")] + public decimal? Percentage { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OvertimeSurchargeAccounts {\n"); + sb.Append(" Rule: ").Append(Rule).Append("\n"); + sb.Append(" Overtime: ").Append(Overtime).Append("\n"); + sb.Append(" Surcharge: ").Append(Surcharge).Append("\n"); + sb.Append(" Percentage: ").Append(Percentage).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OvertimeSurchargeAccountsJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override OvertimeSurchargeAccounts Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option rule = default; + Option overtime = default; + Option surcharge = default; + Option percentage = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "rule": + rule = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "overtime": + overtime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "surcharge": + surcharge = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "percentage": + percentage = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + default: + break; + } + } + } + + if (!rule.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeAccounts.", nameof(rule)); + + if (!overtime.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeAccounts.", nameof(overtime)); + + if (!surcharge.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeAccounts.", nameof(surcharge)); + + if (!percentage.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeAccounts.", nameof(percentage)); + + if (rule.IsSet && rule.Value == null) + throw new ArgumentNullException(nameof(rule), "Property is not nullable for class OvertimeSurchargeAccounts."); + + if (overtime.IsSet && overtime.Value == null) + throw new ArgumentNullException(nameof(overtime), "Property is not nullable for class OvertimeSurchargeAccounts."); + + if (surcharge.IsSet && surcharge.Value == null) + throw new ArgumentNullException(nameof(surcharge), "Property is not nullable for class OvertimeSurchargeAccounts."); + + return new OvertimeSurchargeAccounts(rule.Value!, overtime.Value!, surcharge.Value!, percentage.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OvertimeSurchargeAccounts overtimeSurchargeAccounts, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, overtimeSurchargeAccounts, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OvertimeSurchargeAccounts overtimeSurchargeAccounts, JsonSerializerOptions jsonSerializerOptions) + { + if (overtimeSurchargeAccounts.Rule == null) + throw new ArgumentNullException(nameof(overtimeSurchargeAccounts.Rule), "Property is required for class OvertimeSurchargeAccounts."); + + if (overtimeSurchargeAccounts.Overtime == null) + throw new ArgumentNullException(nameof(overtimeSurchargeAccounts.Overtime), "Property is required for class OvertimeSurchargeAccounts."); + + if (overtimeSurchargeAccounts.Surcharge == null) + throw new ArgumentNullException(nameof(overtimeSurchargeAccounts.Surcharge), "Property is required for class OvertimeSurchargeAccounts."); + + writer.WritePropertyName("rule"); + JsonSerializer.Serialize(writer, overtimeSurchargeAccounts.Rule, jsonSerializerOptions); + writer.WritePropertyName("overtime"); + JsonSerializer.Serialize(writer, overtimeSurchargeAccounts.Overtime, jsonSerializerOptions); + writer.WritePropertyName("surcharge"); + JsonSerializer.Serialize(writer, overtimeSurchargeAccounts.Surcharge, jsonSerializerOptions); + if (overtimeSurchargeAccounts.Percentage != null) + writer.WriteNumber("percentage", overtimeSurchargeAccounts.Percentage.Value); + else + writer.WriteNull("percentage"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/OvertimeSurchargeRule.cs b/sdk/dotnet/Timr.Api/Model/OvertimeSurchargeRule.cs new file mode 100644 index 0000000..b670f57 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/OvertimeSurchargeRule.cs @@ -0,0 +1,210 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// OvertimeSurchargeRule + /// + public partial class OvertimeSurchargeRule : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// shortName + [JsonConstructor] + public OvertimeSurchargeRule(Guid id, string name, string shortName) + { + Id = id; + Name = name; + ShortName = shortName; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public Guid Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets ShortName + /// + [JsonPropertyName("short_name")] + public string ShortName { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class OvertimeSurchargeRule {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" ShortName: ").Append(ShortName).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class OvertimeSurchargeRuleJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override OvertimeSurchargeRule Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option shortName = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (Guid?)null : utf8JsonReader.GetGuid()); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "short_name": + shortName = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeRule.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeRule.", nameof(name)); + + if (!shortName.IsSet) + throw new ArgumentException("Property is required for class OvertimeSurchargeRule.", nameof(shortName)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class OvertimeSurchargeRule."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class OvertimeSurchargeRule."); + + if (shortName.IsSet && shortName.Value == null) + throw new ArgumentNullException(nameof(shortName), "Property is not nullable for class OvertimeSurchargeRule."); + + return new OvertimeSurchargeRule(id.Value!.Value!, name.Value!, shortName.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, OvertimeSurchargeRule overtimeSurchargeRule, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, overtimeSurchargeRule, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, OvertimeSurchargeRule overtimeSurchargeRule, JsonSerializerOptions jsonSerializerOptions) + { + if (overtimeSurchargeRule.Name == null) + throw new ArgumentNullException(nameof(overtimeSurchargeRule.Name), "Property is required for class OvertimeSurchargeRule."); + + if (overtimeSurchargeRule.ShortName == null) + throw new ArgumentNullException(nameof(overtimeSurchargeRule.ShortName), "Property is required for class OvertimeSurchargeRule."); + + writer.WriteString("id", overtimeSurchargeRule.Id); + + writer.WriteString("name", overtimeSurchargeRule.Name); + + writer.WriteString("short_name", overtimeSurchargeRule.ShortName); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/PagingInformation.cs b/sdk/dotnet/Timr.Api/Model/PagingInformation.cs new file mode 100644 index 0000000..34094ec --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/PagingInformation.cs @@ -0,0 +1,162 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// PagingInformation + /// + public partial class PagingInformation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public PagingInformation(string? nextPageToken = default) + { + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class PagingInformation {\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class PagingInformationJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override PagingInformation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class PagingInformation.", nameof(nextPageToken)); + + return new PagingInformation(nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, PagingInformation pagingInformation, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, pagingInformation, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, PagingInformation pagingInformation, JsonSerializerOptions jsonSerializerOptions) + { + if (pagingInformation.NextPageToken != null) + writer.WriteString("next_page_token", pagingInformation.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Platform.cs b/sdk/dotnet/Timr.Api/Model/Platform.cs new file mode 100644 index 0000000..5ccbd9b --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Platform.cs @@ -0,0 +1,233 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Platform the entry was recorded on. + /// + /// Platform the entry was recorded on. + public enum Platform + { + /// + /// Enum TimrWeb for value: timr_web + /// + TimrWeb = 1, + + /// + /// Enum TimrMobile for value: timr_mobile + /// + TimrMobile = 2, + + /// + /// Enum TourMobile for value: tour_mobile + /// + TourMobile = 3, + + /// + /// Enum TimrTerminal for value: timr_terminal + /// + TimrTerminal = 4, + + /// + /// Enum SyncApi for value: sync_api + /// + SyncApi = 5, + + /// + /// Enum TimrApi for value: timr_api + /// + TimrApi = 6 + } + + /// + /// Converts to and from the JSON value + /// + public static class PlatformValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static Platform FromString(string value) + { + if (value.Equals("timr_web")) + return Platform.TimrWeb; + + if (value.Equals("timr_mobile")) + return Platform.TimrMobile; + + if (value.Equals("tour_mobile")) + return Platform.TourMobile; + + if (value.Equals("timr_terminal")) + return Platform.TimrTerminal; + + if (value.Equals("sync_api")) + return Platform.SyncApi; + + if (value.Equals("timr_api")) + return Platform.TimrApi; + + throw new NotImplementedException($"Could not convert value to type Platform: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static Platform? FromStringOrDefault(string value) + { + if (value.Equals("timr_web")) + return Platform.TimrWeb; + + if (value.Equals("timr_mobile")) + return Platform.TimrMobile; + + if (value.Equals("tour_mobile")) + return Platform.TourMobile; + + if (value.Equals("timr_terminal")) + return Platform.TimrTerminal; + + if (value.Equals("sync_api")) + return Platform.SyncApi; + + if (value.Equals("timr_api")) + return Platform.TimrApi; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(Platform value) + { + if (value == Platform.TimrWeb) + return "timr_web"; + + if (value == Platform.TimrMobile) + return "timr_mobile"; + + if (value == Platform.TourMobile) + return "tour_mobile"; + + if (value == Platform.TimrTerminal) + return "timr_terminal"; + + if (value == Platform.SyncApi) + return "sync_api"; + + if (value == Platform.TimrApi) + return "timr_api"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class PlatformJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override Platform Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Platform? result = rawValue == null + ? null + : PlatformValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Platform to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Platform platform, JsonSerializerOptions options) + { + writer.WriteStringValue(PlatformValueConverter.ToJsonValue(platform).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class PlatformNullableJsonConverter : JsonConverter + { + /// + /// Returns a Platform from the Json object + /// + /// + /// + /// + /// + public override Platform? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + Platform? result = rawValue == null + ? null + : PlatformValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the Platform to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Platform? platform, JsonSerializerOptions options) + { + writer.WriteStringValue(platform.HasValue ? PlatformValueConverter.ToJsonValue(platform.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/ProblemDetail.cs b/sdk/dotnet/Timr.Api/Model/ProblemDetail.cs new file mode 100644 index 0000000..d74f05e --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/ProblemDetail.cs @@ -0,0 +1,272 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// RFC 9457 Problem Details base members (`type`, `title`, `status`, `detail`, `instance`) — the common shape of all error response bodies. + /// + public partial class ProblemDetail : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// type + /// title + /// status + /// detail + /// instance + [JsonConstructor] + public ProblemDetail(string type, string title, int status, Option detail = default, Option instance = default) + { + Type = type; + Title = title; + Status = status; + DetailOption = detail; + InstanceOption = instance; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Type + /// + /* https://errors.timr.com/validation/end-time-required */ + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Gets or Sets Title + /// + /* Bad Request */ + [JsonPropertyName("title")] + public string Title { get; set; } + + /// + /// Gets or Sets Status + /// + /* 400 */ + [JsonPropertyName("status")] + public int Status { get; set; } + + /// + /// Used to track the state of Detail + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DetailOption { get; private set; } + + /// + /// Gets or Sets Detail + /// + /* Concrete error message */ + [JsonPropertyName("detail")] + public string? Detail { get { return this.DetailOption.Value; } set { this.DetailOption = new(value); } } + + /// + /// Used to track the state of Instance + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option InstanceOption { get; private set; } + + /// + /// Gets or Sets Instance + /// + /* /working-times/12345 */ + [JsonPropertyName("instance")] + public string? Instance { get { return this.InstanceOption.Value; } set { this.InstanceOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ProblemDetail {\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Title: ").Append(Title).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Detail: ").Append(Detail).Append("\n"); + sb.Append(" Instance: ").Append(Instance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ProblemDetailJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ProblemDetail Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option type = default; + Option title = default; + Option status = default; + Option detail = default; + Option instance = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "type": + type = new Option(utf8JsonReader.GetString()!); + break; + case "title": + title = new Option(utf8JsonReader.GetString()!); + break; + case "status": + status = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "detail": + detail = new Option(utf8JsonReader.GetString()!); + break; + case "instance": + instance = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!type.IsSet) + throw new ArgumentException("Property is required for class ProblemDetail.", nameof(type)); + + if (!title.IsSet) + throw new ArgumentException("Property is required for class ProblemDetail.", nameof(title)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class ProblemDetail.", nameof(status)); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class ProblemDetail."); + + if (title.IsSet && title.Value == null) + throw new ArgumentNullException(nameof(title), "Property is not nullable for class ProblemDetail."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class ProblemDetail."); + + if (detail.IsSet && detail.Value == null) + throw new ArgumentNullException(nameof(detail), "Property is not nullable for class ProblemDetail."); + + if (instance.IsSet && instance.Value == null) + throw new ArgumentNullException(nameof(instance), "Property is not nullable for class ProblemDetail."); + + return new ProblemDetail(type.Value!, title.Value!, status.Value!.Value!, detail, instance); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProblemDetail problemDetail, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, problemDetail, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ProblemDetail problemDetail, JsonSerializerOptions jsonSerializerOptions) + { + if (problemDetail.Type == null) + throw new ArgumentNullException(nameof(problemDetail.Type), "Property is required for class ProblemDetail."); + + if (problemDetail.Title == null) + throw new ArgumentNullException(nameof(problemDetail.Title), "Property is required for class ProblemDetail."); + + if (problemDetail.DetailOption.IsSet && problemDetail.Detail == null) + throw new ArgumentNullException(nameof(problemDetail.Detail), "Property is required for class ProblemDetail."); + + if (problemDetail.InstanceOption.IsSet && problemDetail.Instance == null) + throw new ArgumentNullException(nameof(problemDetail.Instance), "Property is required for class ProblemDetail."); + + writer.WriteString("type", problemDetail.Type); + + writer.WriteString("title", problemDetail.Title); + + writer.WriteNumber("status", problemDetail.Status); + + if (problemDetail.DetailOption.IsSet) + writer.WriteString("detail", problemDetail.Detail); + + if (problemDetail.InstanceOption.IsSet) + writer.WriteString("instance", problemDetail.Instance); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/ProjectTime.cs b/sdk/dotnet/Timr.Api/Model/ProjectTime.cs new file mode 100644 index 0000000..9a72acd --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/ProjectTime.cs @@ -0,0 +1,609 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// One booking on a `task`, from `start` to `end`, optionally `billable`, with `break_times`, notes and locations. + /// + public partial class ProjectTime : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// RFC 3339 date-time (ISO-8601) + /// Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + /// breakTimes + /// changed + /// user + /// task + /// billable + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// status + /// RFC 3339 date-time (ISO-8601) + /// duration + /// notes + /// startLocation + /// endLocation + /// startPlatform + /// endPlatform + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// metadata + [JsonConstructor] + public ProjectTime(string id, DateTimeOffset start, int breakTimeTotalMinutes, List breakTimes, bool changed, UserPartial user, TaskPartial task, bool billable, DateTimeOffset lastModified, ProjectTimeStatus status, DateTimeOffset? end = default, Duration? duration = default, string? notes = default, Location? startLocation = default, Location? endLocation = default, Platform? startPlatform = default, Platform? endPlatform = default, UserPartial? lastModifiedBy = default, Option?> metadata = default) + { + Id = id; + Start = start; + BreakTimeTotalMinutes = breakTimeTotalMinutes; + BreakTimes = breakTimes; + Changed = changed; + User = user; + Task = task; + Billable = billable; + LastModified = lastModified; + Status = status; + End = end; + Duration = duration; + Notes = notes; + StartLocation = startLocation; + EndLocation = endLocation; + StartPlatform = startPlatform; + EndPlatform = endPlatform; + LastModifiedBy = lastModifiedBy; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public ProjectTimeStatus Status { get; set; } + + /// + /// Gets or Sets StartPlatform + /// + [JsonPropertyName("start_platform")] + public Platform? StartPlatform { get; set; } + + /// + /// Gets or Sets EndPlatform + /// + [JsonPropertyName("end_platform")] + public Platform? EndPlatform { get; set; } + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + /* 074e7048-9097-11eb-a8b3-0242ac130003 */ + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset Start { get; set; } + + /// + /// Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + /// + /// Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + [JsonPropertyName("break_time_total_minutes")] + public int BreakTimeTotalMinutes { get; set; } + + /// + /// Gets or Sets BreakTimes + /// + [JsonPropertyName("break_times")] + public List BreakTimes { get; set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool Changed { get; set; } + + /// + /// Gets or Sets User + /// + [JsonPropertyName("user")] + public UserPartial User { get; set; } + + /// + /// Gets or Sets Task + /// + [JsonPropertyName("task")] + public TaskPartial Task { get; set; } + + /// + /// Gets or Sets Billable + /// + [JsonPropertyName("billable")] + public bool Billable { get; set; } + + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("last_modified")] + public DateTimeOffset LastModified { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get; set; } + + /// + /// Gets or Sets Duration + /// + [JsonPropertyName("duration")] + public Duration? Duration { get; set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get; set; } + + /// + /// Gets or Sets StartLocation + /// + [JsonPropertyName("start_location")] + public Location? StartLocation { get; set; } + + /// + /// Gets or Sets EndLocation + /// + [JsonPropertyName("end_location")] + public Location? EndLocation { get; set; } + + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + [JsonPropertyName("last_modified_by")] + public UserPartial? LastModifiedBy { get; set; } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ProjectTime {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" BreakTimeTotalMinutes: ").Append(BreakTimeTotalMinutes).Append("\n"); + sb.Append(" BreakTimes: ").Append(BreakTimes).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" User: ").Append(User).Append("\n"); + sb.Append(" Task: ").Append(Task).Append("\n"); + sb.Append(" Billable: ").Append(Billable).Append("\n"); + sb.Append(" LastModified: ").Append(LastModified).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" Duration: ").Append(Duration).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" StartLocation: ").Append(StartLocation).Append("\n"); + sb.Append(" EndLocation: ").Append(EndLocation).Append("\n"); + sb.Append(" StartPlatform: ").Append(StartPlatform).Append("\n"); + sb.Append(" EndPlatform: ").Append(EndPlatform).Append("\n"); + sb.Append(" LastModifiedBy: ").Append(LastModifiedBy).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ProjectTimeJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize LastModified + /// + public static string LastModifiedFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ProjectTime Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option start = default; + Option breakTimeTotalMinutes = default; + Option?> breakTimes = default; + Option changed = default; + Option user = default; + Option task = default; + Option billable = default; + Option lastModified = default; + Option status = default; + Option end = default; + Option duration = default; + Option notes = default; + Option startLocation = default; + Option endLocation = default; + Option startPlatform = default; + Option endPlatform = default; + Option lastModifiedBy = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "break_time_total_minutes": + breakTimeTotalMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "break_times": + breakTimes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "user": + user = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "task": + task = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "billable": + billable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "last_modified": + lastModified = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(ProjectTimeStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "duration": + duration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "start_location": + startLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_location": + endLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_platform": + string? startPlatformRawValue = utf8JsonReader.GetString(); + startPlatform = new Option(startPlatformRawValue == null ? null : PlatformValueConverter.FromStringOrDefault(startPlatformRawValue)); + break; + case "end_platform": + string? endPlatformRawValue = utf8JsonReader.GetString(); + endPlatform = new Option(endPlatformRawValue == null ? null : PlatformValueConverter.FromStringOrDefault(endPlatformRawValue)); + break; + case "last_modified_by": + lastModifiedBy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(id)); + + if (!start.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(start)); + + if (!breakTimeTotalMinutes.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(breakTimeTotalMinutes)); + + if (!breakTimes.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(breakTimes)); + + if (!changed.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(changed)); + + if (!user.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(user)); + + if (!task.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(task)); + + if (!billable.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(billable)); + + if (!lastModified.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(lastModified)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(status)); + + if (!end.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(end)); + + if (!duration.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(duration)); + + if (!notes.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(notes)); + + if (!startLocation.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(startLocation)); + + if (!endLocation.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(endLocation)); + + if (!startPlatform.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(startPlatform)); + + if (!endPlatform.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(endPlatform)); + + if (!lastModifiedBy.IsSet) + throw new ArgumentException("Property is required for class ProjectTime.", nameof(lastModifiedBy)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class ProjectTime."); + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class ProjectTime."); + + if (breakTimeTotalMinutes.IsSet && breakTimeTotalMinutes.Value == null) + throw new ArgumentNullException(nameof(breakTimeTotalMinutes), "Property is not nullable for class ProjectTime."); + + if (breakTimes.IsSet && breakTimes.Value == null) + throw new ArgumentNullException(nameof(breakTimes), "Property is not nullable for class ProjectTime."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class ProjectTime."); + + if (user.IsSet && user.Value == null) + throw new ArgumentNullException(nameof(user), "Property is not nullable for class ProjectTime."); + + if (task.IsSet && task.Value == null) + throw new ArgumentNullException(nameof(task), "Property is not nullable for class ProjectTime."); + + if (billable.IsSet && billable.Value == null) + throw new ArgumentNullException(nameof(billable), "Property is not nullable for class ProjectTime."); + + if (lastModified.IsSet && lastModified.Value == null) + throw new ArgumentNullException(nameof(lastModified), "Property is not nullable for class ProjectTime."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class ProjectTime."); + + return new ProjectTime(id.Value!, start.Value!.Value!, breakTimeTotalMinutes.Value!.Value!, breakTimes.Value!, changed.Value!.Value!, user.Value!, task.Value!, billable.Value!.Value!, lastModified.Value!.Value!, status.Value!.Value!, end.Value!, duration.Value!, notes.Value!, startLocation.Value!, endLocation.Value!, startPlatform.Value!, endPlatform.Value!, lastModifiedBy.Value!, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProjectTime projectTime, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, projectTime, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ProjectTime projectTime, JsonSerializerOptions jsonSerializerOptions) + { + if (projectTime.Id == null) + throw new ArgumentNullException(nameof(projectTime.Id), "Property is required for class ProjectTime."); + + if (projectTime.BreakTimes == null) + throw new ArgumentNullException(nameof(projectTime.BreakTimes), "Property is required for class ProjectTime."); + + if (projectTime.User == null) + throw new ArgumentNullException(nameof(projectTime.User), "Property is required for class ProjectTime."); + + if (projectTime.Task == null) + throw new ArgumentNullException(nameof(projectTime.Task), "Property is required for class ProjectTime."); + + writer.WriteString("id", projectTime.Id); + + writer.WriteString("start", projectTime.Start.ToString(StartFormat)); + + writer.WriteNumber("break_time_total_minutes", projectTime.BreakTimeTotalMinutes); + + writer.WritePropertyName("break_times"); + JsonSerializer.Serialize(writer, projectTime.BreakTimes, jsonSerializerOptions); + writer.WriteBoolean("changed", projectTime.Changed); + + writer.WritePropertyName("user"); + JsonSerializer.Serialize(writer, projectTime.User, jsonSerializerOptions); + writer.WritePropertyName("task"); + JsonSerializer.Serialize(writer, projectTime.Task, jsonSerializerOptions); + writer.WriteBoolean("billable", projectTime.Billable); + + writer.WriteString("last_modified", projectTime.LastModified.ToString(LastModifiedFormat)); + + var statusRawValue = ProjectTimeStatusValueConverter.ToJsonValue(projectTime.Status); + writer.WriteString("status", statusRawValue); + + if (projectTime.End != null) + writer.WriteString("end", projectTime.End.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (projectTime.Duration != null) + { + writer.WritePropertyName("duration"); + JsonSerializer.Serialize(writer, projectTime.Duration, jsonSerializerOptions); + } + else + writer.WriteNull("duration"); + if (projectTime.Notes != null) + writer.WriteString("notes", projectTime.Notes); + else + writer.WriteNull("notes"); + + if (projectTime.StartLocation != null) + { + writer.WritePropertyName("start_location"); + JsonSerializer.Serialize(writer, projectTime.StartLocation, jsonSerializerOptions); + } + else + writer.WriteNull("start_location"); + if (projectTime.EndLocation != null) + { + writer.WritePropertyName("end_location"); + JsonSerializer.Serialize(writer, projectTime.EndLocation, jsonSerializerOptions); + } + else + writer.WriteNull("end_location"); + if (projectTime.StartPlatform == null) + writer.WriteNull("start_platform"); + else + { + var startPlatformRawValue = PlatformValueConverter.ToJsonValue(projectTime.StartPlatform.Value); + if (startPlatformRawValue != null) + writer.WriteString("start_platform", startPlatformRawValue); + else + writer.WriteNull("start_platform"); + } + + if (projectTime.EndPlatform == null) + writer.WriteNull("end_platform"); + else + { + var endPlatformRawValue = PlatformValueConverter.ToJsonValue(projectTime.EndPlatform.Value); + if (endPlatformRawValue != null) + writer.WriteString("end_platform", endPlatformRawValue); + else + writer.WriteNull("end_platform"); + } + + if (projectTime.LastModifiedBy != null) + { + writer.WritePropertyName("last_modified_by"); + JsonSerializer.Serialize(writer, projectTime.LastModifiedBy, jsonSerializerOptions); + } + else + writer.WriteNull("last_modified_by"); + if (projectTime.MetadataOption.IsSet) + if (projectTime.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, projectTime.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/ProjectTimeCreate.cs b/sdk/dotnet/Timr.Api/Model/ProjectTimeCreate.cs new file mode 100644 index 0000000..99ba7a3 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/ProjectTimeCreate.cs @@ -0,0 +1,462 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// ProjectTimeCreate + /// + public partial class ProjectTimeCreate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// RFC 3339 date-time (ISO-8601) + /// changed + /// taskId + /// status + /// userId + /// RFC 3339 date-time (ISO-8601) + /// breakTimes + /// notes + /// billable + /// metadata + /// startLocation + /// endLocation + [JsonConstructor] + public ProjectTimeCreate(DateTimeOffset start, bool changed, string taskId, ProjectTimeStatus status, string userId, Option end = default, Option?> breakTimes = default, Option notes = default, Option billable = default, Option?> metadata = default, Option startLocation = default, Option endLocation = default) + { + Start = start; + Changed = changed; + TaskId = taskId; + Status = status; + UserId = userId; + EndOption = end; + BreakTimesOption = breakTimes; + NotesOption = notes; + BillableOption = billable; + MetadataOption = metadata; + StartLocationOption = startLocation; + EndLocationOption = endLocation; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public ProjectTimeStatus Status { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset Start { get; set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool Changed { get; set; } + + /// + /// Gets or Sets TaskId + /// + [JsonPropertyName("task_id")] + public string TaskId { get; set; } + + /// + /// Gets or Sets UserId + /// + [JsonPropertyName("user_id")] + public string UserId { get; set; } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of BreakTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> BreakTimesOption { get; private set; } + + /// + /// Gets or Sets BreakTimes + /// + [JsonPropertyName("break_times")] + public List? BreakTimes { get { return this.BreakTimesOption.Value; } set { this.BreakTimesOption = new(value); } } + + /// + /// Used to track the state of Notes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NotesOption { get; private set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get { return this.NotesOption.Value; } set { this.NotesOption = new(value); } } + + /// + /// Used to track the state of Billable + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BillableOption { get; private set; } + + /// + /// Gets or Sets Billable + /// + [JsonPropertyName("billable")] + public bool? Billable { get { return this.BillableOption.Value; } set { this.BillableOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Used to track the state of StartLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartLocationOption { get; private set; } + + /// + /// Gets or Sets StartLocation + /// + [JsonPropertyName("start_location")] + public LocationCreate? StartLocation { get { return this.StartLocationOption.Value; } set { this.StartLocationOption = new(value); } } + + /// + /// Used to track the state of EndLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndLocationOption { get; private set; } + + /// + /// Gets or Sets EndLocation + /// + [JsonPropertyName("end_location")] + public LocationCreate? EndLocation { get { return this.EndLocationOption.Value; } set { this.EndLocationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ProjectTimeCreate {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" TaskId: ").Append(TaskId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" UserId: ").Append(UserId).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" BreakTimes: ").Append(BreakTimes).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" Billable: ").Append(Billable).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" StartLocation: ").Append(StartLocation).Append("\n"); + sb.Append(" EndLocation: ").Append(EndLocation).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ProjectTimeCreateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ProjectTimeCreate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option changed = default; + Option taskId = default; + Option status = default; + Option userId = default; + Option end = default; + Option?> breakTimes = default; + Option notes = default; + Option billable = default; + Option?> metadata = default; + Option startLocation = default; + Option endLocation = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "task_id": + taskId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(ProjectTimeStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "user_id": + userId = new Option(utf8JsonReader.GetString()!); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "break_times": + breakTimes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "billable": + billable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_location": + startLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_location": + endLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!start.IsSet) + throw new ArgumentException("Property is required for class ProjectTimeCreate.", nameof(start)); + + if (!changed.IsSet) + throw new ArgumentException("Property is required for class ProjectTimeCreate.", nameof(changed)); + + if (!taskId.IsSet) + throw new ArgumentException("Property is required for class ProjectTimeCreate.", nameof(taskId)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class ProjectTimeCreate.", nameof(status)); + + if (!userId.IsSet) + throw new ArgumentException("Property is required for class ProjectTimeCreate.", nameof(userId)); + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class ProjectTimeCreate."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class ProjectTimeCreate."); + + if (taskId.IsSet && taskId.Value == null) + throw new ArgumentNullException(nameof(taskId), "Property is not nullable for class ProjectTimeCreate."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class ProjectTimeCreate."); + + if (userId.IsSet && userId.Value == null) + throw new ArgumentNullException(nameof(userId), "Property is not nullable for class ProjectTimeCreate."); + + if (breakTimes.IsSet && breakTimes.Value == null) + throw new ArgumentNullException(nameof(breakTimes), "Property is not nullable for class ProjectTimeCreate."); + + if (billable.IsSet && billable.Value == null) + throw new ArgumentNullException(nameof(billable), "Property is not nullable for class ProjectTimeCreate."); + + return new ProjectTimeCreate(start.Value!.Value!, changed.Value!.Value!, taskId.Value!, status.Value!.Value!, userId.Value!, end, breakTimes, notes, billable, metadata, startLocation, endLocation); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProjectTimeCreate projectTimeCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, projectTimeCreate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ProjectTimeCreate projectTimeCreate, JsonSerializerOptions jsonSerializerOptions) + { + if (projectTimeCreate.TaskId == null) + throw new ArgumentNullException(nameof(projectTimeCreate.TaskId), "Property is required for class ProjectTimeCreate."); + + if (projectTimeCreate.UserId == null) + throw new ArgumentNullException(nameof(projectTimeCreate.UserId), "Property is required for class ProjectTimeCreate."); + + if (projectTimeCreate.BreakTimesOption.IsSet && projectTimeCreate.BreakTimes == null) + throw new ArgumentNullException(nameof(projectTimeCreate.BreakTimes), "Property is required for class ProjectTimeCreate."); + + writer.WriteString("start", projectTimeCreate.Start.ToString(StartFormat)); + + writer.WriteBoolean("changed", projectTimeCreate.Changed); + + writer.WriteString("task_id", projectTimeCreate.TaskId); + + var statusRawValue = ProjectTimeStatusValueConverter.ToJsonValue(projectTimeCreate.Status); + writer.WriteString("status", statusRawValue); + + writer.WriteString("user_id", projectTimeCreate.UserId); + + if (projectTimeCreate.EndOption.IsSet) + if (projectTimeCreate.EndOption.Value != null) + writer.WriteString("end", projectTimeCreate.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (projectTimeCreate.BreakTimesOption.IsSet) + { + writer.WritePropertyName("break_times"); + JsonSerializer.Serialize(writer, projectTimeCreate.BreakTimes, jsonSerializerOptions); + } + if (projectTimeCreate.NotesOption.IsSet) + if (projectTimeCreate.NotesOption.Value != null) + writer.WriteString("notes", projectTimeCreate.Notes); + else + writer.WriteNull("notes"); + + if (projectTimeCreate.BillableOption.IsSet) + writer.WriteBoolean("billable", projectTimeCreate.BillableOption.Value!.Value); + + if (projectTimeCreate.MetadataOption.IsSet) + if (projectTimeCreate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, projectTimeCreate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + if (projectTimeCreate.StartLocationOption.IsSet) + if (projectTimeCreate.StartLocationOption.Value != null) + { + writer.WritePropertyName("start_location"); + JsonSerializer.Serialize(writer, projectTimeCreate.StartLocation, jsonSerializerOptions); + } + else + writer.WriteNull("start_location"); + if (projectTimeCreate.EndLocationOption.IsSet) + if (projectTimeCreate.EndLocationOption.Value != null) + { + writer.WritePropertyName("end_location"); + JsonSerializer.Serialize(writer, projectTimeCreate.EndLocation, jsonSerializerOptions); + } + else + writer.WriteNull("end_location"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/ProjectTimeStatus.cs b/sdk/dotnet/Timr.Api/Model/ProjectTimeStatus.cs new file mode 100644 index 0000000..011d89a --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/ProjectTimeStatus.cs @@ -0,0 +1,261 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Processing state of a Project Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + /// + /// Processing state of a Project Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + public enum ProjectTimeStatus + { + /// + /// Enum Running for value: running + /// + Running = 1, + + /// + /// Enum Paused for value: paused + /// + Paused = 2, + + /// + /// Enum Changeable for value: changeable + /// + Changeable = 3, + + /// + /// Enum Locked for value: locked + /// + Locked = 4, + + /// + /// Enum Approved for value: approved + /// + Approved = 5, + + /// + /// Enum Cleared for value: cleared + /// + Cleared = 6, + + /// + /// Enum Closed for value: closed + /// + Closed = 7, + + /// + /// Enum Archived for value: archived + /// + Archived = 8 + } + + /// + /// Converts to and from the JSON value + /// + public static class ProjectTimeStatusValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static ProjectTimeStatus FromString(string value) + { + if (value.Equals("running")) + return ProjectTimeStatus.Running; + + if (value.Equals("paused")) + return ProjectTimeStatus.Paused; + + if (value.Equals("changeable")) + return ProjectTimeStatus.Changeable; + + if (value.Equals("locked")) + return ProjectTimeStatus.Locked; + + if (value.Equals("approved")) + return ProjectTimeStatus.Approved; + + if (value.Equals("cleared")) + return ProjectTimeStatus.Cleared; + + if (value.Equals("closed")) + return ProjectTimeStatus.Closed; + + if (value.Equals("archived")) + return ProjectTimeStatus.Archived; + + throw new NotImplementedException($"Could not convert value to type ProjectTimeStatus: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static ProjectTimeStatus? FromStringOrDefault(string value) + { + if (value.Equals("running")) + return ProjectTimeStatus.Running; + + if (value.Equals("paused")) + return ProjectTimeStatus.Paused; + + if (value.Equals("changeable")) + return ProjectTimeStatus.Changeable; + + if (value.Equals("locked")) + return ProjectTimeStatus.Locked; + + if (value.Equals("approved")) + return ProjectTimeStatus.Approved; + + if (value.Equals("cleared")) + return ProjectTimeStatus.Cleared; + + if (value.Equals("closed")) + return ProjectTimeStatus.Closed; + + if (value.Equals("archived")) + return ProjectTimeStatus.Archived; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(ProjectTimeStatus value) + { + if (value == ProjectTimeStatus.Running) + return "running"; + + if (value == ProjectTimeStatus.Paused) + return "paused"; + + if (value == ProjectTimeStatus.Changeable) + return "changeable"; + + if (value == ProjectTimeStatus.Locked) + return "locked"; + + if (value == ProjectTimeStatus.Approved) + return "approved"; + + if (value == ProjectTimeStatus.Cleared) + return "cleared"; + + if (value == ProjectTimeStatus.Closed) + return "closed"; + + if (value == ProjectTimeStatus.Archived) + return "archived"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ProjectTimeStatusJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override ProjectTimeStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ProjectTimeStatus? result = rawValue == null + ? null + : ProjectTimeStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ProjectTimeStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProjectTimeStatus projectTimeStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(ProjectTimeStatusValueConverter.ToJsonValue(projectTimeStatus).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ProjectTimeStatusNullableJsonConverter : JsonConverter + { + /// + /// Returns a ProjectTimeStatus from the Json object + /// + /// + /// + /// + /// + public override ProjectTimeStatus? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ProjectTimeStatus? result = rawValue == null + ? null + : ProjectTimeStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ProjectTimeStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProjectTimeStatus? projectTimeStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(projectTimeStatus.HasValue ? ProjectTimeStatusValueConverter.ToJsonValue(projectTimeStatus.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/ProjectTimeUpdate.cs b/sdk/dotnet/Timr.Api/Model/ProjectTimeUpdate.cs new file mode 100644 index 0000000..bb41f7b --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/ProjectTimeUpdate.cs @@ -0,0 +1,459 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// ProjectTimeUpdate + /// + public partial class ProjectTimeUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// RFC 3339 date-time (ISO-8601) + /// RFC 3339 date-time (ISO-8601) + /// breakTimes + /// changed + /// notes + /// taskId + /// billable + /// status + /// metadata + /// startLocation + /// endLocation + [JsonConstructor] + public ProjectTimeUpdate(Option start = default, Option end = default, Option?> breakTimes = default, Option changed = default, Option notes = default, Option taskId = default, Option billable = default, Option status = default, Option?> metadata = default, Option startLocation = default, Option endLocation = default) + { + StartOption = start; + EndOption = end; + BreakTimesOption = breakTimes; + ChangedOption = changed; + NotesOption = notes; + TaskIdOption = taskId; + BillableOption = billable; + StatusOption = status; + MetadataOption = metadata; + StartLocationOption = startLocation; + EndLocationOption = endLocation; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public ProjectTimeStatus? Status { get { return this.StatusOption.Value; } set { this.StatusOption = new(value); } } + + /// + /// Used to track the state of Start + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset? Start { get { return this.StartOption.Value; } set { this.StartOption = new(value); } } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of BreakTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> BreakTimesOption { get; private set; } + + /// + /// Gets or Sets BreakTimes + /// + [JsonPropertyName("break_times")] + public List? BreakTimes { get { return this.BreakTimesOption.Value; } set { this.BreakTimesOption = new(value); } } + + /// + /// Used to track the state of Changed + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ChangedOption { get; private set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool? Changed { get { return this.ChangedOption.Value; } set { this.ChangedOption = new(value); } } + + /// + /// Used to track the state of Notes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NotesOption { get; private set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get { return this.NotesOption.Value; } set { this.NotesOption = new(value); } } + + /// + /// Used to track the state of TaskId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option TaskIdOption { get; private set; } + + /// + /// Gets or Sets TaskId + /// + [JsonPropertyName("task_id")] + public string? TaskId { get { return this.TaskIdOption.Value; } set { this.TaskIdOption = new(value); } } + + /// + /// Used to track the state of Billable + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BillableOption { get; private set; } + + /// + /// Gets or Sets Billable + /// + [JsonPropertyName("billable")] + public bool? Billable { get { return this.BillableOption.Value; } set { this.BillableOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Used to track the state of StartLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartLocationOption { get; private set; } + + /// + /// Gets or Sets StartLocation + /// + [JsonPropertyName("start_location")] + public LocationUpdate? StartLocation { get { return this.StartLocationOption.Value; } set { this.StartLocationOption = new(value); } } + + /// + /// Used to track the state of EndLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndLocationOption { get; private set; } + + /// + /// Gets or Sets EndLocation + /// + [JsonPropertyName("end_location")] + public LocationUpdate? EndLocation { get { return this.EndLocationOption.Value; } set { this.EndLocationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ProjectTimeUpdate {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" BreakTimes: ").Append(BreakTimes).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" TaskId: ").Append(TaskId).Append("\n"); + sb.Append(" Billable: ").Append(Billable).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" StartLocation: ").Append(StartLocation).Append("\n"); + sb.Append(" EndLocation: ").Append(EndLocation).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ProjectTimeUpdateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ProjectTimeUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option end = default; + Option?> breakTimes = default; + Option changed = default; + Option notes = default; + Option taskId = default; + Option billable = default; + Option status = default; + Option?> metadata = default; + Option startLocation = default; + Option endLocation = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "break_times": + breakTimes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "task_id": + taskId = new Option(utf8JsonReader.GetString()!); + break; + case "billable": + billable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(ProjectTimeStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_location": + startLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_location": + endLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class ProjectTimeUpdate."); + + if (breakTimes.IsSet && breakTimes.Value == null) + throw new ArgumentNullException(nameof(breakTimes), "Property is not nullable for class ProjectTimeUpdate."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class ProjectTimeUpdate."); + + if (taskId.IsSet && taskId.Value == null) + throw new ArgumentNullException(nameof(taskId), "Property is not nullable for class ProjectTimeUpdate."); + + if (billable.IsSet && billable.Value == null) + throw new ArgumentNullException(nameof(billable), "Property is not nullable for class ProjectTimeUpdate."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class ProjectTimeUpdate."); + + return new ProjectTimeUpdate(start, end, breakTimes, changed, notes, taskId, billable, status, metadata, startLocation, endLocation); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProjectTimeUpdate projectTimeUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, projectTimeUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ProjectTimeUpdate projectTimeUpdate, JsonSerializerOptions jsonSerializerOptions) + { + if (projectTimeUpdate.BreakTimesOption.IsSet && projectTimeUpdate.BreakTimes == null) + throw new ArgumentNullException(nameof(projectTimeUpdate.BreakTimes), "Property is required for class ProjectTimeUpdate."); + + if (projectTimeUpdate.TaskIdOption.IsSet && projectTimeUpdate.TaskId == null) + throw new ArgumentNullException(nameof(projectTimeUpdate.TaskId), "Property is required for class ProjectTimeUpdate."); + + if (projectTimeUpdate.StartOption.IsSet) + writer.WriteString("start", projectTimeUpdate.StartOption.Value!.Value.ToString(StartFormat)); + + if (projectTimeUpdate.EndOption.IsSet) + if (projectTimeUpdate.EndOption.Value != null) + writer.WriteString("end", projectTimeUpdate.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (projectTimeUpdate.BreakTimesOption.IsSet) + { + writer.WritePropertyName("break_times"); + JsonSerializer.Serialize(writer, projectTimeUpdate.BreakTimes, jsonSerializerOptions); + } + if (projectTimeUpdate.ChangedOption.IsSet) + writer.WriteBoolean("changed", projectTimeUpdate.ChangedOption.Value!.Value); + + if (projectTimeUpdate.NotesOption.IsSet) + if (projectTimeUpdate.NotesOption.Value != null) + writer.WriteString("notes", projectTimeUpdate.Notes); + else + writer.WriteNull("notes"); + + if (projectTimeUpdate.TaskIdOption.IsSet) + writer.WriteString("task_id", projectTimeUpdate.TaskId); + + if (projectTimeUpdate.BillableOption.IsSet) + writer.WriteBoolean("billable", projectTimeUpdate.BillableOption.Value!.Value); + + if (projectTimeUpdate.StatusOption.IsSet) + { + var statusRawValue = ProjectTimeStatusValueConverter.ToJsonValue(projectTimeUpdate.Status!.Value); + writer.WriteString("status", statusRawValue); + } + if (projectTimeUpdate.MetadataOption.IsSet) + if (projectTimeUpdate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, projectTimeUpdate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + if (projectTimeUpdate.StartLocationOption.IsSet) + if (projectTimeUpdate.StartLocationOption.Value != null) + { + writer.WritePropertyName("start_location"); + JsonSerializer.Serialize(writer, projectTimeUpdate.StartLocation, jsonSerializerOptions); + } + else + writer.WriteNull("start_location"); + if (projectTimeUpdate.EndLocationOption.IsSet) + if (projectTimeUpdate.EndLocationOption.Value != null) + { + writer.WritePropertyName("end_location"); + JsonSerializer.Serialize(writer, projectTimeUpdate.EndLocation, jsonSerializerOptions); + } + else + writer.WriteNull("end_location"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/ProjectTimeUpsert.cs b/sdk/dotnet/Timr.Api/Model/ProjectTimeUpsert.cs new file mode 100644 index 0000000..235d959 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/ProjectTimeUpsert.cs @@ -0,0 +1,403 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// ProjectTimeUpsert + /// + public partial class ProjectTimeUpsert : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// RFC 3339 date-time (ISO-8601) + /// RFC 3339 date-time (ISO-8601) + /// breakTimes + /// changed + /// notes + /// taskId + /// billable + /// status + /// metadata + [JsonConstructor] + public ProjectTimeUpsert(Option start = default, Option end = default, Option?> breakTimes = default, Option changed = default, Option notes = default, Option taskId = default, Option billable = default, Option status = default, Option?> metadata = default) + { + StartOption = start; + EndOption = end; + BreakTimesOption = breakTimes; + ChangedOption = changed; + NotesOption = notes; + TaskIdOption = taskId; + BillableOption = billable; + StatusOption = status; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public ProjectTimeStatus? Status { get { return this.StatusOption.Value; } set { this.StatusOption = new(value); } } + + /// + /// Used to track the state of Start + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset? Start { get { return this.StartOption.Value; } set { this.StartOption = new(value); } } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of BreakTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> BreakTimesOption { get; private set; } + + /// + /// Gets or Sets BreakTimes + /// + [JsonPropertyName("break_times")] + public List? BreakTimes { get { return this.BreakTimesOption.Value; } set { this.BreakTimesOption = new(value); } } + + /// + /// Used to track the state of Changed + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ChangedOption { get; private set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool? Changed { get { return this.ChangedOption.Value; } set { this.ChangedOption = new(value); } } + + /// + /// Used to track the state of Notes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NotesOption { get; private set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get { return this.NotesOption.Value; } set { this.NotesOption = new(value); } } + + /// + /// Used to track the state of TaskId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option TaskIdOption { get; private set; } + + /// + /// Gets or Sets TaskId + /// + [JsonPropertyName("task_id")] + public string? TaskId { get { return this.TaskIdOption.Value; } set { this.TaskIdOption = new(value); } } + + /// + /// Used to track the state of Billable + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BillableOption { get; private set; } + + /// + /// Gets or Sets Billable + /// + [JsonPropertyName("billable")] + public bool? Billable { get { return this.BillableOption.Value; } set { this.BillableOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ProjectTimeUpsert {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" BreakTimes: ").Append(BreakTimes).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" TaskId: ").Append(TaskId).Append("\n"); + sb.Append(" Billable: ").Append(Billable).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ProjectTimeUpsertJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ProjectTimeUpsert Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option end = default; + Option?> breakTimes = default; + Option changed = default; + Option notes = default; + Option taskId = default; + Option billable = default; + Option status = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "break_times": + breakTimes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "task_id": + taskId = new Option(utf8JsonReader.GetString()!); + break; + case "billable": + billable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(ProjectTimeStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class ProjectTimeUpsert."); + + if (breakTimes.IsSet && breakTimes.Value == null) + throw new ArgumentNullException(nameof(breakTimes), "Property is not nullable for class ProjectTimeUpsert."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class ProjectTimeUpsert."); + + if (taskId.IsSet && taskId.Value == null) + throw new ArgumentNullException(nameof(taskId), "Property is not nullable for class ProjectTimeUpsert."); + + if (billable.IsSet && billable.Value == null) + throw new ArgumentNullException(nameof(billable), "Property is not nullable for class ProjectTimeUpsert."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class ProjectTimeUpsert."); + + return new ProjectTimeUpsert(start, end, breakTimes, changed, notes, taskId, billable, status, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProjectTimeUpsert projectTimeUpsert, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, projectTimeUpsert, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ProjectTimeUpsert projectTimeUpsert, JsonSerializerOptions jsonSerializerOptions) + { + if (projectTimeUpsert.BreakTimesOption.IsSet && projectTimeUpsert.BreakTimes == null) + throw new ArgumentNullException(nameof(projectTimeUpsert.BreakTimes), "Property is required for class ProjectTimeUpsert."); + + if (projectTimeUpsert.TaskIdOption.IsSet && projectTimeUpsert.TaskId == null) + throw new ArgumentNullException(nameof(projectTimeUpsert.TaskId), "Property is required for class ProjectTimeUpsert."); + + if (projectTimeUpsert.StartOption.IsSet) + writer.WriteString("start", projectTimeUpsert.StartOption.Value!.Value.ToString(StartFormat)); + + if (projectTimeUpsert.EndOption.IsSet) + if (projectTimeUpsert.EndOption.Value != null) + writer.WriteString("end", projectTimeUpsert.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (projectTimeUpsert.BreakTimesOption.IsSet) + { + writer.WritePropertyName("break_times"); + JsonSerializer.Serialize(writer, projectTimeUpsert.BreakTimes, jsonSerializerOptions); + } + if (projectTimeUpsert.ChangedOption.IsSet) + writer.WriteBoolean("changed", projectTimeUpsert.ChangedOption.Value!.Value); + + if (projectTimeUpsert.NotesOption.IsSet) + if (projectTimeUpsert.NotesOption.Value != null) + writer.WriteString("notes", projectTimeUpsert.Notes); + else + writer.WriteNull("notes"); + + if (projectTimeUpsert.TaskIdOption.IsSet) + writer.WriteString("task_id", projectTimeUpsert.TaskId); + + if (projectTimeUpsert.BillableOption.IsSet) + writer.WriteBoolean("billable", projectTimeUpsert.BillableOption.Value!.Value); + + if (projectTimeUpsert.StatusOption.IsSet) + { + var statusRawValue = ProjectTimeStatusValueConverter.ToJsonValue(projectTimeUpsert.Status!.Value); + writer.WriteString("status", statusRawValue); + } + if (projectTimeUpsert.MetadataOption.IsSet) + if (projectTimeUpsert.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, projectTimeUpsert.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/ProjectTimesPage.cs b/sdk/dotnet/Timr.Api/Model/ProjectTimesPage.cs new file mode 100644 index 0000000..75f7b47 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/ProjectTimesPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// ProjectTimesPage + /// + public partial class ProjectTimesPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public ProjectTimesPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class ProjectTimesPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class ProjectTimesPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override ProjectTimesPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class ProjectTimesPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class ProjectTimesPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class ProjectTimesPage."); + + return new ProjectTimesPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProjectTimesPage projectTimesPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, projectTimesPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, ProjectTimesPage projectTimesPage, JsonSerializerOptions jsonSerializerOptions) + { + if (projectTimesPage.Data == null) + throw new ArgumentNullException(nameof(projectTimesPage.Data), "Property is required for class ProjectTimesPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, projectTimesPage.Data, jsonSerializerOptions); + if (projectTimesPage.NextPageToken != null) + writer.WriteString("next_page_token", projectTimesPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/ProjectTimesSortColumn.cs b/sdk/dotnet/Timr.Api/Model/ProjectTimesSortColumn.cs new file mode 100644 index 0000000..8399e15 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/ProjectTimesSortColumn.cs @@ -0,0 +1,177 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Project Times. + /// + /// Sort property for Project Times. + public enum ProjectTimesSortColumn + { + /// + /// Enum Start for value: start + /// + Start = 1, + + /// + /// Enum LastModified for value: last_modified + /// + LastModified = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class ProjectTimesSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static ProjectTimesSortColumn FromString(string value) + { + if (value.Equals("start")) + return ProjectTimesSortColumn.Start; + + if (value.Equals("last_modified")) + return ProjectTimesSortColumn.LastModified; + + throw new NotImplementedException($"Could not convert value to type ProjectTimesSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static ProjectTimesSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("start")) + return ProjectTimesSortColumn.Start; + + if (value.Equals("last_modified")) + return ProjectTimesSortColumn.LastModified; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(ProjectTimesSortColumn value) + { + if (value == ProjectTimesSortColumn.Start) + return "start"; + + if (value == ProjectTimesSortColumn.LastModified) + return "last_modified"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class ProjectTimesSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override ProjectTimesSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ProjectTimesSortColumn? result = rawValue == null + ? null + : ProjectTimesSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ProjectTimesSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProjectTimesSortColumn projectTimesSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(ProjectTimesSortColumnValueConverter.ToJsonValue(projectTimesSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class ProjectTimesSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a ProjectTimesSortColumn from the Json object + /// + /// + /// + /// + /// + public override ProjectTimesSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + ProjectTimesSortColumn? result = rawValue == null + ? null + : ProjectTimesSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the ProjectTimesSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, ProjectTimesSortColumn? projectTimesSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(projectTimesSortColumn.HasValue ? ProjectTimesSortColumnValueConverter.ToJsonValue(projectTimesSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/RecordingLockType.cs b/sdk/dotnet/Timr.Api/Model/RecordingLockType.cs new file mode 100644 index 0000000..af45e5a --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/RecordingLockType.cs @@ -0,0 +1,205 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Whether the assigned User may record on the Task, and where the lock comes from. `recordable` allows recording; `locked_automatically` follows the Task's lock date; `locked_manually` and `unlocked_manually` are explicit overrides for this assignment. + /// + /// Whether the assigned User may record on the Task, and where the lock comes from. `recordable` allows recording; `locked_automatically` follows the Task's lock date; `locked_manually` and `unlocked_manually` are explicit overrides for this assignment. + public enum RecordingLockType + { + /// + /// Enum Recordable for value: recordable + /// + Recordable = 1, + + /// + /// Enum LockedAutomatically for value: locked_automatically + /// + LockedAutomatically = 2, + + /// + /// Enum LockedManually for value: locked_manually + /// + LockedManually = 3, + + /// + /// Enum UnlockedManually for value: unlocked_manually + /// + UnlockedManually = 4 + } + + /// + /// Converts to and from the JSON value + /// + public static class RecordingLockTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static RecordingLockType FromString(string value) + { + if (value.Equals("recordable")) + return RecordingLockType.Recordable; + + if (value.Equals("locked_automatically")) + return RecordingLockType.LockedAutomatically; + + if (value.Equals("locked_manually")) + return RecordingLockType.LockedManually; + + if (value.Equals("unlocked_manually")) + return RecordingLockType.UnlockedManually; + + throw new NotImplementedException($"Could not convert value to type RecordingLockType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static RecordingLockType? FromStringOrDefault(string value) + { + if (value.Equals("recordable")) + return RecordingLockType.Recordable; + + if (value.Equals("locked_automatically")) + return RecordingLockType.LockedAutomatically; + + if (value.Equals("locked_manually")) + return RecordingLockType.LockedManually; + + if (value.Equals("unlocked_manually")) + return RecordingLockType.UnlockedManually; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(RecordingLockType value) + { + if (value == RecordingLockType.Recordable) + return "recordable"; + + if (value == RecordingLockType.LockedAutomatically) + return "locked_automatically"; + + if (value == RecordingLockType.LockedManually) + return "locked_manually"; + + if (value == RecordingLockType.UnlockedManually) + return "unlocked_manually"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class RecordingLockTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override RecordingLockType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + RecordingLockType? result = rawValue == null + ? null + : RecordingLockTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the RecordingLockType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecordingLockType recordingLockType, JsonSerializerOptions options) + { + writer.WriteStringValue(RecordingLockTypeValueConverter.ToJsonValue(recordingLockType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class RecordingLockTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a RecordingLockType from the Json object + /// + /// + /// + /// + /// + public override RecordingLockType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + RecordingLockType? result = rawValue == null + ? null + : RecordingLockTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the RecordingLockType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecordingLockType? recordingLockType, JsonSerializerOptions options) + { + writer.WriteStringValue(recordingLockType.HasValue ? RecordingLockTypeValueConverter.ToJsonValue(recordingLockType.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/RecordingModeUser.cs b/sdk/dotnet/Timr.Api/Model/RecordingModeUser.cs new file mode 100644 index 0000000..7aba485 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/RecordingModeUser.cs @@ -0,0 +1,191 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Whether a User may record this Working Time Type themselves. Only meaningful for day-based types. + /// + /// Whether a User may record this Working Time Type themselves. Only meaningful for day-based types. + public enum RecordingModeUser + { + /// + /// Enum NotAllowed for value: not_allowed + /// + NotAllowed = 1, + + /// + /// Enum Allowed for value: allowed + /// + Allowed = 2, + + /// + /// Enum ByRequest for value: by_request + /// + ByRequest = 3 + } + + /// + /// Converts to and from the JSON value + /// + public static class RecordingModeUserValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static RecordingModeUser FromString(string value) + { + if (value.Equals("not_allowed")) + return RecordingModeUser.NotAllowed; + + if (value.Equals("allowed")) + return RecordingModeUser.Allowed; + + if (value.Equals("by_request")) + return RecordingModeUser.ByRequest; + + throw new NotImplementedException($"Could not convert value to type RecordingModeUser: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static RecordingModeUser? FromStringOrDefault(string value) + { + if (value.Equals("not_allowed")) + return RecordingModeUser.NotAllowed; + + if (value.Equals("allowed")) + return RecordingModeUser.Allowed; + + if (value.Equals("by_request")) + return RecordingModeUser.ByRequest; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(RecordingModeUser value) + { + if (value == RecordingModeUser.NotAllowed) + return "not_allowed"; + + if (value == RecordingModeUser.Allowed) + return "allowed"; + + if (value == RecordingModeUser.ByRequest) + return "by_request"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class RecordingModeUserJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override RecordingModeUser Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + RecordingModeUser? result = rawValue == null + ? null + : RecordingModeUserValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the RecordingModeUser to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecordingModeUser recordingModeUser, JsonSerializerOptions options) + { + writer.WriteStringValue(RecordingModeUserValueConverter.ToJsonValue(recordingModeUser).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class RecordingModeUserNullableJsonConverter : JsonConverter + { + /// + /// Returns a RecordingModeUser from the Json object + /// + /// + /// + /// + /// + public override RecordingModeUser? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + RecordingModeUser? result = rawValue == null + ? null + : RecordingModeUserValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the RecordingModeUser to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RecordingModeUser? recordingModeUser, JsonSerializerOptions options) + { + writer.WriteStringValue(recordingModeUser.HasValue ? RecordingModeUserValueConverter.ToJsonValue(recordingModeUser.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/SortDirection.cs b/sdk/dotnet/Timr.Api/Model/SortDirection.cs new file mode 100644 index 0000000..60b3d17 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/SortDirection.cs @@ -0,0 +1,177 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort direction — `asc` for ascending, `dsc` for descending. + /// + /// Sort direction — `asc` for ascending, `dsc` for descending. + public enum SortDirection + { + /// + /// Enum Asc for value: asc + /// + Asc = 1, + + /// + /// Enum Dsc for value: dsc + /// + Dsc = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class SortDirectionValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static SortDirection FromString(string value) + { + if (value.Equals("asc")) + return SortDirection.Asc; + + if (value.Equals("dsc")) + return SortDirection.Dsc; + + throw new NotImplementedException($"Could not convert value to type SortDirection: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static SortDirection? FromStringOrDefault(string value) + { + if (value.Equals("asc")) + return SortDirection.Asc; + + if (value.Equals("dsc")) + return SortDirection.Dsc; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(SortDirection value) + { + if (value == SortDirection.Asc) + return "asc"; + + if (value == SortDirection.Dsc) + return "dsc"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class SortDirectionJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override SortDirection Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + SortDirection? result = rawValue == null + ? null + : SortDirectionValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the SortDirection to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SortDirection sortDirection, JsonSerializerOptions options) + { + writer.WriteStringValue(SortDirectionValueConverter.ToJsonValue(sortDirection).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class SortDirectionNullableJsonConverter : JsonConverter + { + /// + /// Returns a SortDirection from the Json object + /// + /// + /// + /// + /// + public override SortDirection? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + SortDirection? result = rawValue == null + ? null + : SortDirectionValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the SortDirection to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, SortDirection? sortDirection, JsonSerializerOptions options) + { + writer.WriteStringValue(sortDirection.HasValue ? SortDirectionValueConverter.ToJsonValue(sortDirection.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Task.cs b/sdk/dotnet/Timr.Api/Model/Task.cs new file mode 100644 index 0000000..da18137 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Task.cs @@ -0,0 +1,892 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// A task, placed in the tree by `parent_task`, with the full path from the root in `breadcrumbs`. `bookable` and `billable` control recording and invoicing; `lock_date`, time windows and location constrain what may be recorded. + /// + public partial class Task : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// Full path of the entry within its hierarchy, including its own name. + /// bookable + /// billable + /// projectTimeNotesRequired + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// parentTask + /// description + /// descriptionExternal + /// RFC 3339 date (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// time of day (ISO-8601) + /// time of day (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// budgetInherited + /// budgetPlanningType + /// budgetHoursPlanned + /// budgetHourlyRate + /// budgetPlanned + /// budgetIncludeNonBillableProjectTimes + /// locationInherited + /// location + /// locationRestrictionRadiusMeters + /// customField1 + /// customField2 + /// customField3 + /// metadata + [JsonConstructor] + public Task(string id, string name, string breadcrumbs, bool bookable, bool billable, bool projectTimeNotesRequired, string? externalId = default, TaskPartial? parentTask = default, string? description = default, string? descriptionExternal = default, DateOnly? startDate = default, DateOnly? endDate = default, Option lockDate = default, Option earliestStartTime = default, Option latestEndTime = default, DateOnly? activeFrom = default, DateOnly? activeTo = default, Option budgetInherited = default, Option budgetPlanningType = default, Option budgetHoursPlanned = default, Option budgetHourlyRate = default, Option budgetPlanned = default, Option budgetIncludeNonBillableProjectTimes = default, Option locationInherited = default, Option location = default, Option locationRestrictionRadiusMeters = default, string? customField1 = default, string? customField2 = default, string? customField3 = default, Option?> metadata = default) + { + Id = id; + Name = name; + Breadcrumbs = breadcrumbs; + Bookable = bookable; + Billable = billable; + ProjectTimeNotesRequired = projectTimeNotesRequired; + ExternalId = externalId; + ParentTask = parentTask; + Description = description; + DescriptionExternal = descriptionExternal; + StartDate = startDate; + EndDate = endDate; + LockDateOption = lockDate; + EarliestStartTimeOption = earliestStartTime; + LatestEndTimeOption = latestEndTime; + ActiveFrom = activeFrom; + ActiveTo = activeTo; + BudgetInheritedOption = budgetInherited; + BudgetPlanningTypeOption = budgetPlanningType; + BudgetHoursPlannedOption = budgetHoursPlanned; + BudgetHourlyRateOption = budgetHourlyRate; + BudgetPlannedOption = budgetPlanned; + BudgetIncludeNonBillableProjectTimesOption = budgetIncludeNonBillableProjectTimes; + LocationInheritedOption = locationInherited; + LocationOption = location; + LocationRestrictionRadiusMetersOption = locationRestrictionRadiusMeters; + CustomField1 = customField1; + CustomField2 = customField2; + CustomField3 = customField3; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of BudgetPlanningType + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetPlanningTypeOption { get; private set; } + + /// + /// Gets or Sets BudgetPlanningType + /// + [JsonPropertyName("budget_planning_type")] + public BudgetPlanningType? BudgetPlanningType { get { return this.BudgetPlanningTypeOption.Value; } set { this.BudgetPlanningTypeOption = new(value); } } + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Full path of the entry within its hierarchy, including its own name. + /// + /// Full path of the entry within its hierarchy, including its own name. + [JsonPropertyName("breadcrumbs")] + public string Breadcrumbs { get; set; } + + /// + /// Gets or Sets Bookable + /// + [JsonPropertyName("bookable")] + public bool Bookable { get; set; } + + /// + /// Gets or Sets Billable + /// + [JsonPropertyName("billable")] + public bool Billable { get; set; } + + /// + /// Gets or Sets ProjectTimeNotesRequired + /// + [JsonPropertyName("project_time_notes_required")] + public bool ProjectTimeNotesRequired { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Gets or Sets ParentTask + /// + [JsonPropertyName("parent_task")] + public TaskPartial? ParentTask { get; set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// Gets or Sets DescriptionExternal + /// + [JsonPropertyName("description_external")] + public string? DescriptionExternal { get; set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("start_date")] + public DateOnly? StartDate { get; set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("end_date")] + public DateOnly? EndDate { get; set; } + + /// + /// Used to track the state of LockDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LockDateOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("lock_date")] + public DateOnly? LockDate { get { return this.LockDateOption.Value; } set { this.LockDateOption = new(value); } } + + /// + /// Used to track the state of EarliestStartTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EarliestStartTimeOption { get; private set; } + + /// + /// time of day (ISO-8601) + /// + /// time of day (ISO-8601) + /* 920 */ + [JsonPropertyName("earliest_start_time")] + public string? EarliestStartTime { get { return this.EarliestStartTimeOption.Value; } set { this.EarliestStartTimeOption = new(value); } } + + /// + /// Used to track the state of LatestEndTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LatestEndTimeOption { get; private set; } + + /// + /// time of day (ISO-8601) + /// + /// time of day (ISO-8601) + /* 920 */ + [JsonPropertyName("latest_end_time")] + public string? LatestEndTime { get { return this.LatestEndTimeOption.Value; } set { this.LatestEndTimeOption = new(value); } } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("active_from")] + public DateOnly? ActiveFrom { get; set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("active_to")] + public DateOnly? ActiveTo { get; set; } + + /// + /// Used to track the state of BudgetInherited + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetInheritedOption { get; private set; } + + /// + /// Gets or Sets BudgetInherited + /// + [JsonPropertyName("budget_inherited")] + public bool? BudgetInherited { get { return this.BudgetInheritedOption.Value; } set { this.BudgetInheritedOption = new(value); } } + + /// + /// Used to track the state of BudgetHoursPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetHoursPlannedOption { get; private set; } + + /// + /// Gets or Sets BudgetHoursPlanned + /// + [JsonPropertyName("budget_hours_planned")] + public decimal? BudgetHoursPlanned { get { return this.BudgetHoursPlannedOption.Value; } set { this.BudgetHoursPlannedOption = new(value); } } + + /// + /// Used to track the state of BudgetHourlyRate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetHourlyRateOption { get; private set; } + + /// + /// Gets or Sets BudgetHourlyRate + /// + [JsonPropertyName("budget_hourly_rate")] + public decimal? BudgetHourlyRate { get { return this.BudgetHourlyRateOption.Value; } set { this.BudgetHourlyRateOption = new(value); } } + + /// + /// Used to track the state of BudgetPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetPlannedOption { get; private set; } + + /// + /// Gets or Sets BudgetPlanned + /// + [JsonPropertyName("budget_planned")] + public decimal? BudgetPlanned { get { return this.BudgetPlannedOption.Value; } set { this.BudgetPlannedOption = new(value); } } + + /// + /// Used to track the state of BudgetIncludeNonBillableProjectTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetIncludeNonBillableProjectTimesOption { get; private set; } + + /// + /// Gets or Sets BudgetIncludeNonBillableProjectTimes + /// + [JsonPropertyName("budget_include_non_billable_project_times")] + public bool? BudgetIncludeNonBillableProjectTimes { get { return this.BudgetIncludeNonBillableProjectTimesOption.Value; } set { this.BudgetIncludeNonBillableProjectTimesOption = new(value); } } + + /// + /// Used to track the state of LocationInherited + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationInheritedOption { get; private set; } + + /// + /// Gets or Sets LocationInherited + /// + [JsonPropertyName("location_inherited")] + public bool? LocationInherited { get { return this.LocationInheritedOption.Value; } set { this.LocationInheritedOption = new(value); } } + + /// + /// Used to track the state of Location + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationOption { get; private set; } + + /// + /// Gets or Sets Location + /// + [JsonPropertyName("location")] + public TaskLocation? Location { get { return this.LocationOption.Value; } set { this.LocationOption = new(value); } } + + /// + /// Used to track the state of LocationRestrictionRadiusMeters + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationRestrictionRadiusMetersOption { get; private set; } + + /// + /// Gets or Sets LocationRestrictionRadiusMeters + /// + [JsonPropertyName("location_restriction_radius_meters")] + public int? LocationRestrictionRadiusMeters { get { return this.LocationRestrictionRadiusMetersOption.Value; } set { this.LocationRestrictionRadiusMetersOption = new(value); } } + + /// + /// Gets or Sets CustomField1 + /// + [JsonPropertyName("custom_field_1")] + public string? CustomField1 { get; set; } + + /// + /// Gets or Sets CustomField2 + /// + [JsonPropertyName("custom_field_2")] + public string? CustomField2 { get; set; } + + /// + /// Gets or Sets CustomField3 + /// + [JsonPropertyName("custom_field_3")] + public string? CustomField3 { get; set; } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Task {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Breadcrumbs: ").Append(Breadcrumbs).Append("\n"); + sb.Append(" Bookable: ").Append(Bookable).Append("\n"); + sb.Append(" Billable: ").Append(Billable).Append("\n"); + sb.Append(" ProjectTimeNotesRequired: ").Append(ProjectTimeNotesRequired).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" ParentTask: ").Append(ParentTask).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DescriptionExternal: ").Append(DescriptionExternal).Append("\n"); + sb.Append(" StartDate: ").Append(StartDate).Append("\n"); + sb.Append(" EndDate: ").Append(EndDate).Append("\n"); + sb.Append(" LockDate: ").Append(LockDate).Append("\n"); + sb.Append(" EarliestStartTime: ").Append(EarliestStartTime).Append("\n"); + sb.Append(" LatestEndTime: ").Append(LatestEndTime).Append("\n"); + sb.Append(" ActiveFrom: ").Append(ActiveFrom).Append("\n"); + sb.Append(" ActiveTo: ").Append(ActiveTo).Append("\n"); + sb.Append(" BudgetInherited: ").Append(BudgetInherited).Append("\n"); + sb.Append(" BudgetPlanningType: ").Append(BudgetPlanningType).Append("\n"); + sb.Append(" BudgetHoursPlanned: ").Append(BudgetHoursPlanned).Append("\n"); + sb.Append(" BudgetHourlyRate: ").Append(BudgetHourlyRate).Append("\n"); + sb.Append(" BudgetPlanned: ").Append(BudgetPlanned).Append("\n"); + sb.Append(" BudgetIncludeNonBillableProjectTimes: ").Append(BudgetIncludeNonBillableProjectTimes).Append("\n"); + sb.Append(" LocationInherited: ").Append(LocationInherited).Append("\n"); + sb.Append(" Location: ").Append(Location).Append("\n"); + sb.Append(" LocationRestrictionRadiusMeters: ").Append(LocationRestrictionRadiusMeters).Append("\n"); + sb.Append(" CustomField1: ").Append(CustomField1).Append("\n"); + sb.Append(" CustomField2: ").Append(CustomField2).Append("\n"); + sb.Append(" CustomField3: ").Append(CustomField3).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskJsonConverter : JsonConverter + { + /// + /// The format to use to serialize StartDate + /// + public static string StartDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize EndDate + /// + public static string EndDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize LockDate + /// + public static string LockDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize ActiveFrom + /// + public static string ActiveFromFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize ActiveTo + /// + public static string ActiveToFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Task Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option breadcrumbs = default; + Option bookable = default; + Option billable = default; + Option projectTimeNotesRequired = default; + Option externalId = default; + Option parentTask = default; + Option description = default; + Option descriptionExternal = default; + Option startDate = default; + Option endDate = default; + Option lockDate = default; + Option earliestStartTime = default; + Option latestEndTime = default; + Option activeFrom = default; + Option activeTo = default; + Option budgetInherited = default; + Option budgetPlanningType = default; + Option budgetHoursPlanned = default; + Option budgetHourlyRate = default; + Option budgetPlanned = default; + Option budgetIncludeNonBillableProjectTimes = default; + Option locationInherited = default; + Option location = default; + Option locationRestrictionRadiusMeters = default; + Option customField1 = default; + Option customField2 = default; + Option customField3 = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "breadcrumbs": + breadcrumbs = new Option(utf8JsonReader.GetString()!); + break; + case "bookable": + bookable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "billable": + billable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "project_time_notes_required": + projectTimeNotesRequired = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "parent_task": + parentTask = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()); + break; + case "description_external": + descriptionExternal = new Option(utf8JsonReader.GetString()); + break; + case "start_date": + startDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_date": + endDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "lock_date": + lockDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "earliest_start_time": + earliestStartTime = new Option(utf8JsonReader.GetString()); + break; + case "latest_end_time": + latestEndTime = new Option(utf8JsonReader.GetString()); + break; + case "active_from": + activeFrom = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "active_to": + activeTo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "budget_inherited": + budgetInherited = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "budget_planning_type": + string? budgetPlanningTypeRawValue = utf8JsonReader.GetString(); + if (budgetPlanningTypeRawValue != null) + budgetPlanningType = new Option(BudgetPlanningTypeValueConverter.FromStringOrDefault(budgetPlanningTypeRawValue)); + break; + case "budget_hours_planned": + budgetHoursPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_hourly_rate": + budgetHourlyRate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_planned": + budgetPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_include_non_billable_project_times": + budgetIncludeNonBillableProjectTimes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "location_inherited": + locationInherited = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "location": + location = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "location_restriction_radius_meters": + locationRestrictionRadiusMeters = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "custom_field_1": + customField1 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_2": + customField2 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_3": + customField3 = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(name)); + + if (!breadcrumbs.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(breadcrumbs)); + + if (!bookable.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(bookable)); + + if (!billable.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(billable)); + + if (!projectTimeNotesRequired.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(projectTimeNotesRequired)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(externalId)); + + if (!parentTask.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(parentTask)); + + if (!description.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(description)); + + if (!descriptionExternal.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(descriptionExternal)); + + if (!startDate.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(startDate)); + + if (!endDate.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(endDate)); + + if (!activeFrom.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(activeFrom)); + + if (!activeTo.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(activeTo)); + + if (!customField1.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(customField1)); + + if (!customField2.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(customField2)); + + if (!customField3.IsSet) + throw new ArgumentException("Property is required for class Task.", nameof(customField3)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Task."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Task."); + + if (breadcrumbs.IsSet && breadcrumbs.Value == null) + throw new ArgumentNullException(nameof(breadcrumbs), "Property is not nullable for class Task."); + + if (bookable.IsSet && bookable.Value == null) + throw new ArgumentNullException(nameof(bookable), "Property is not nullable for class Task."); + + if (billable.IsSet && billable.Value == null) + throw new ArgumentNullException(nameof(billable), "Property is not nullable for class Task."); + + if (projectTimeNotesRequired.IsSet && projectTimeNotesRequired.Value == null) + throw new ArgumentNullException(nameof(projectTimeNotesRequired), "Property is not nullable for class Task."); + + if (budgetInherited.IsSet && budgetInherited.Value == null) + throw new ArgumentNullException(nameof(budgetInherited), "Property is not nullable for class Task."); + + if (budgetPlanningType.IsSet && budgetPlanningType.Value == null) + throw new ArgumentNullException(nameof(budgetPlanningType), "Property is not nullable for class Task."); + + if (budgetIncludeNonBillableProjectTimes.IsSet && budgetIncludeNonBillableProjectTimes.Value == null) + throw new ArgumentNullException(nameof(budgetIncludeNonBillableProjectTimes), "Property is not nullable for class Task."); + + if (locationInherited.IsSet && locationInherited.Value == null) + throw new ArgumentNullException(nameof(locationInherited), "Property is not nullable for class Task."); + + return new Task(id.Value!, name.Value!, breadcrumbs.Value!, bookable.Value!.Value!, billable.Value!.Value!, projectTimeNotesRequired.Value!.Value!, externalId.Value!, parentTask.Value!, description.Value!, descriptionExternal.Value!, startDate.Value!, endDate.Value!, lockDate, earliestStartTime, latestEndTime, activeFrom.Value!, activeTo.Value!, budgetInherited, budgetPlanningType, budgetHoursPlanned, budgetHourlyRate, budgetPlanned, budgetIncludeNonBillableProjectTimes, locationInherited, location, locationRestrictionRadiusMeters, customField1.Value!, customField2.Value!, customField3.Value!, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Task task, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, task, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Task task, JsonSerializerOptions jsonSerializerOptions) + { + if (task.Id == null) + throw new ArgumentNullException(nameof(task.Id), "Property is required for class Task."); + + if (task.Name == null) + throw new ArgumentNullException(nameof(task.Name), "Property is required for class Task."); + + if (task.Breadcrumbs == null) + throw new ArgumentNullException(nameof(task.Breadcrumbs), "Property is required for class Task."); + + writer.WriteString("id", task.Id); + + writer.WriteString("name", task.Name); + + writer.WriteString("breadcrumbs", task.Breadcrumbs); + + writer.WriteBoolean("bookable", task.Bookable); + + writer.WriteBoolean("billable", task.Billable); + + writer.WriteBoolean("project_time_notes_required", task.ProjectTimeNotesRequired); + + if (task.ExternalId != null) + writer.WriteString("external_id", task.ExternalId); + else + writer.WriteNull("external_id"); + + if (task.ParentTask != null) + { + writer.WritePropertyName("parent_task"); + JsonSerializer.Serialize(writer, task.ParentTask, jsonSerializerOptions); + } + else + writer.WriteNull("parent_task"); + if (task.Description != null) + writer.WriteString("description", task.Description); + else + writer.WriteNull("description"); + + if (task.DescriptionExternal != null) + writer.WriteString("description_external", task.DescriptionExternal); + else + writer.WriteNull("description_external"); + + if (task.StartDate != null) + writer.WriteString("start_date", task.StartDate.Value.ToString(StartDateFormat)); + else + writer.WriteNull("start_date"); + + if (task.EndDate != null) + writer.WriteString("end_date", task.EndDate.Value.ToString(EndDateFormat)); + else + writer.WriteNull("end_date"); + + if (task.LockDateOption.IsSet) + if (task.LockDateOption.Value != null) + writer.WriteString("lock_date", task.LockDateOption.Value!.Value.ToString(LockDateFormat)); + else + writer.WriteNull("lock_date"); + + if (task.EarliestStartTimeOption.IsSet) + if (task.EarliestStartTimeOption.Value != null) + writer.WriteString("earliest_start_time", task.EarliestStartTime); + else + writer.WriteNull("earliest_start_time"); + + if (task.LatestEndTimeOption.IsSet) + if (task.LatestEndTimeOption.Value != null) + writer.WriteString("latest_end_time", task.LatestEndTime); + else + writer.WriteNull("latest_end_time"); + + if (task.ActiveFrom != null) + writer.WriteString("active_from", task.ActiveFrom.Value.ToString(ActiveFromFormat)); + else + writer.WriteNull("active_from"); + + if (task.ActiveTo != null) + writer.WriteString("active_to", task.ActiveTo.Value.ToString(ActiveToFormat)); + else + writer.WriteNull("active_to"); + + if (task.BudgetInheritedOption.IsSet) + writer.WriteBoolean("budget_inherited", task.BudgetInheritedOption.Value!.Value); + + if (task.BudgetPlanningTypeOption.IsSet) + { + var budgetPlanningTypeRawValue = BudgetPlanningTypeValueConverter.ToJsonValue(task.BudgetPlanningType!.Value); + writer.WriteString("budget_planning_type", budgetPlanningTypeRawValue); + } + if (task.BudgetHoursPlannedOption.IsSet) + if (task.BudgetHoursPlannedOption.Value != null) + writer.WriteNumber("budget_hours_planned", task.BudgetHoursPlannedOption.Value!.Value); + else + writer.WriteNull("budget_hours_planned"); + + if (task.BudgetHourlyRateOption.IsSet) + if (task.BudgetHourlyRateOption.Value != null) + writer.WriteNumber("budget_hourly_rate", task.BudgetHourlyRateOption.Value!.Value); + else + writer.WriteNull("budget_hourly_rate"); + + if (task.BudgetPlannedOption.IsSet) + if (task.BudgetPlannedOption.Value != null) + writer.WriteNumber("budget_planned", task.BudgetPlannedOption.Value!.Value); + else + writer.WriteNull("budget_planned"); + + if (task.BudgetIncludeNonBillableProjectTimesOption.IsSet) + writer.WriteBoolean("budget_include_non_billable_project_times", task.BudgetIncludeNonBillableProjectTimesOption.Value!.Value); + + if (task.LocationInheritedOption.IsSet) + writer.WriteBoolean("location_inherited", task.LocationInheritedOption.Value!.Value); + + if (task.LocationOption.IsSet) + if (task.LocationOption.Value != null) + { + writer.WritePropertyName("location"); + JsonSerializer.Serialize(writer, task.Location, jsonSerializerOptions); + } + else + writer.WriteNull("location"); + if (task.LocationRestrictionRadiusMetersOption.IsSet) + if (task.LocationRestrictionRadiusMetersOption.Value != null) + writer.WriteNumber("location_restriction_radius_meters", task.LocationRestrictionRadiusMetersOption.Value!.Value); + else + writer.WriteNull("location_restriction_radius_meters"); + + if (task.CustomField1 != null) + writer.WriteString("custom_field_1", task.CustomField1); + else + writer.WriteNull("custom_field_1"); + + if (task.CustomField2 != null) + writer.WriteString("custom_field_2", task.CustomField2); + else + writer.WriteNull("custom_field_2"); + + if (task.CustomField3 != null) + writer.WriteString("custom_field_3", task.CustomField3); + else + writer.WriteNull("custom_field_3"); + + if (task.MetadataOption.IsSet) + if (task.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, task.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskBase.cs b/sdk/dotnet/Timr.Api/Model/TaskBase.cs new file mode 100644 index 0000000..c7a0390 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskBase.cs @@ -0,0 +1,838 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskBase + /// + public partial class TaskBase : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + /// returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// description + /// descriptionExternal + /// when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + /// billable + /// depending on this property project times booked on this task have to include notes or not + /// the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + /// set this property to limit the task so that it cannot be booked before this time + /// set this property to limit the task so that it cannot be booked after this time + /// when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + /// how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + /// the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// set this property to true, if you want to include not billable hours for all project times booked on this task + /// set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + /// location + /// set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// metadata + [JsonConstructor] + public TaskBase(Option name = default, Option parentTaskId = default, Option externalId = default, Option description = default, Option descriptionExternal = default, Option bookable = default, Option billable = default, Option projectTimeNotesRequired = default, Option startDate = default, Option endDate = default, Option lockDate = default, Option earliestStartTime = default, Option latestEndTime = default, Option budgetPlanningType = default, Option budgetHoursPlanned = default, Option budgetHourlyRate = default, Option budgetPlanned = default, Option budgetIncludeNonBillableProjectTimes = default, Option locationInherited = default, Option location = default, Option locationRestrictionRadiusMeters = default, Option customField1 = default, Option customField2 = default, Option customField3 = default, Option?> metadata = default) + { + NameOption = name; + ParentTaskIdOption = parentTaskId; + ExternalIdOption = externalId; + DescriptionOption = description; + DescriptionExternalOption = descriptionExternal; + BookableOption = bookable; + BillableOption = billable; + ProjectTimeNotesRequiredOption = projectTimeNotesRequired; + StartDateOption = startDate; + EndDateOption = endDate; + LockDateOption = lockDate; + EarliestStartTimeOption = earliestStartTime; + LatestEndTimeOption = latestEndTime; + BudgetPlanningTypeOption = budgetPlanningType; + BudgetHoursPlannedOption = budgetHoursPlanned; + BudgetHourlyRateOption = budgetHourlyRate; + BudgetPlannedOption = budgetPlanned; + BudgetIncludeNonBillableProjectTimesOption = budgetIncludeNonBillableProjectTimes; + LocationInheritedOption = locationInherited; + LocationOption = location; + LocationRestrictionRadiusMetersOption = locationRestrictionRadiusMeters; + CustomField1Option = customField1; + CustomField2Option = customField2; + CustomField3Option = customField3; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of BudgetPlanningType + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetPlanningTypeOption { get; private set; } + + /// + /// when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + /// + /// when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + [JsonPropertyName("budget_planning_type")] + public BudgetPlanningTypeRequest? BudgetPlanningType { get { return this.BudgetPlanningTypeOption.Value; } set { this.BudgetPlanningTypeOption = new(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string? Name { get { return this.NameOption.Value; } set { this.NameOption = new(value); } } + + /// + /// Used to track the state of ParentTaskId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ParentTaskIdOption { get; private set; } + + /// + /// returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + /// + /// returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + [JsonPropertyName("parent_task_id")] + public string? ParentTaskId { get { return this.ParentTaskIdOption.Value; } set { this.ParentTaskIdOption = new(value); } } + + /// + /// Used to track the state of ExternalId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ExternalIdOption { get; private set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get { return this.ExternalIdOption.Value; } set { this.ExternalIdOption = new(value); } } + + /// + /// Used to track the state of Description + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DescriptionOption { get; private set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string? Description { get { return this.DescriptionOption.Value; } set { this.DescriptionOption = new(value); } } + + /// + /// Used to track the state of DescriptionExternal + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DescriptionExternalOption { get; private set; } + + /// + /// Gets or Sets DescriptionExternal + /// + [JsonPropertyName("description_external")] + public string? DescriptionExternal { get { return this.DescriptionExternalOption.Value; } set { this.DescriptionExternalOption = new(value); } } + + /// + /// Used to track the state of Bookable + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BookableOption { get; private set; } + + /// + /// when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + /// + /// when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + [JsonPropertyName("bookable")] + public bool? Bookable { get { return this.BookableOption.Value; } set { this.BookableOption = new(value); } } + + /// + /// Used to track the state of Billable + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BillableOption { get; private set; } + + /// + /// Gets or Sets Billable + /// + [JsonPropertyName("billable")] + public bool? Billable { get { return this.BillableOption.Value; } set { this.BillableOption = new(value); } } + + /// + /// Used to track the state of ProjectTimeNotesRequired + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ProjectTimeNotesRequiredOption { get; private set; } + + /// + /// depending on this property project times booked on this task have to include notes or not + /// + /// depending on this property project times booked on this task have to include notes or not + [JsonPropertyName("project_time_notes_required")] + public bool? ProjectTimeNotesRequired { get { return this.ProjectTimeNotesRequiredOption.Value; } set { this.ProjectTimeNotesRequiredOption = new(value); } } + + /// + /// Used to track the state of StartDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartDateOption { get; private set; } + + /// + /// the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// + /// the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + [JsonPropertyName("start_date")] + public DateOnly? StartDate { get { return this.StartDateOption.Value; } set { this.StartDateOption = new(value); } } + + /// + /// Used to track the state of EndDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndDateOption { get; private set; } + + /// + /// the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// + /// the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + [JsonPropertyName("end_date")] + public DateOnly? EndDate { get { return this.EndDateOption.Value; } set { this.EndDateOption = new(value); } } + + /// + /// Used to track the state of LockDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LockDateOption { get; private set; } + + /// + /// with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + /// + /// with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + [JsonPropertyName("lock_date")] + public DateOnly? LockDate { get { return this.LockDateOption.Value; } set { this.LockDateOption = new(value); } } + + /// + /// Used to track the state of EarliestStartTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EarliestStartTimeOption { get; private set; } + + /// + /// set this property to limit the task so that it cannot be booked before this time + /// + /// set this property to limit the task so that it cannot be booked before this time + /* 920 */ + [JsonPropertyName("earliest_start_time")] + public string? EarliestStartTime { get { return this.EarliestStartTimeOption.Value; } set { this.EarliestStartTimeOption = new(value); } } + + /// + /// Used to track the state of LatestEndTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LatestEndTimeOption { get; private set; } + + /// + /// set this property to limit the task so that it cannot be booked after this time + /// + /// set this property to limit the task so that it cannot be booked after this time + /* 920 */ + [JsonPropertyName("latest_end_time")] + public string? LatestEndTime { get { return this.LatestEndTimeOption.Value; } set { this.LatestEndTimeOption = new(value); } } + + /// + /// Used to track the state of BudgetHoursPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetHoursPlannedOption { get; private set; } + + /// + /// how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// + /// how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + [JsonPropertyName("budget_hours_planned")] + public decimal? BudgetHoursPlanned { get { return this.BudgetHoursPlannedOption.Value; } set { this.BudgetHoursPlannedOption = new(value); } } + + /// + /// Used to track the state of BudgetHourlyRate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetHourlyRateOption { get; private set; } + + /// + /// depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + /// + /// depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + [JsonPropertyName("budget_hourly_rate")] + public decimal? BudgetHourlyRate { get { return this.BudgetHourlyRateOption.Value; } set { this.BudgetHourlyRateOption = new(value); } } + + /// + /// Used to track the state of BudgetPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetPlannedOption { get; private set; } + + /// + /// the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// + /// the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + [JsonPropertyName("budget_planned")] + public decimal? BudgetPlanned { get { return this.BudgetPlannedOption.Value; } set { this.BudgetPlannedOption = new(value); } } + + /// + /// Used to track the state of BudgetIncludeNonBillableProjectTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetIncludeNonBillableProjectTimesOption { get; private set; } + + /// + /// set this property to true, if you want to include not billable hours for all project times booked on this task + /// + /// set this property to true, if you want to include not billable hours for all project times booked on this task + [JsonPropertyName("budget_include_non_billable_project_times")] + public bool? BudgetIncludeNonBillableProjectTimes { get { return this.BudgetIncludeNonBillableProjectTimesOption.Value; } set { this.BudgetIncludeNonBillableProjectTimesOption = new(value); } } + + /// + /// Used to track the state of LocationInherited + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationInheritedOption { get; private set; } + + /// + /// set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + /// + /// set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + [JsonPropertyName("location_inherited")] + public bool? LocationInherited { get { return this.LocationInheritedOption.Value; } set { this.LocationInheritedOption = new(value); } } + + /// + /// Used to track the state of Location + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationOption { get; private set; } + + /// + /// Gets or Sets Location + /// + [JsonPropertyName("location")] + public TaskLocation? Location { get { return this.LocationOption.Value; } set { this.LocationOption = new(value); } } + + /// + /// Used to track the state of LocationRestrictionRadiusMeters + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationRestrictionRadiusMetersOption { get; private set; } + + /// + /// set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + /// + /// set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + [JsonPropertyName("location_restriction_radius_meters")] + public int? LocationRestrictionRadiusMeters { get { return this.LocationRestrictionRadiusMetersOption.Value; } set { this.LocationRestrictionRadiusMetersOption = new(value); } } + + /// + /// Used to track the state of CustomField1 + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option CustomField1Option { get; private set; } + + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + [JsonPropertyName("custom_field_1")] + public string? CustomField1 { get { return this.CustomField1Option.Value; } set { this.CustomField1Option = new(value); } } + + /// + /// Used to track the state of CustomField2 + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option CustomField2Option { get; private set; } + + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + [JsonPropertyName("custom_field_2")] + public string? CustomField2 { get { return this.CustomField2Option.Value; } set { this.CustomField2Option = new(value); } } + + /// + /// Used to track the state of CustomField3 + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option CustomField3Option { get; private set; } + + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + [JsonPropertyName("custom_field_3")] + public string? CustomField3 { get { return this.CustomField3Option.Value; } set { this.CustomField3Option = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskBase {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" ParentTaskId: ").Append(ParentTaskId).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DescriptionExternal: ").Append(DescriptionExternal).Append("\n"); + sb.Append(" Bookable: ").Append(Bookable).Append("\n"); + sb.Append(" Billable: ").Append(Billable).Append("\n"); + sb.Append(" ProjectTimeNotesRequired: ").Append(ProjectTimeNotesRequired).Append("\n"); + sb.Append(" StartDate: ").Append(StartDate).Append("\n"); + sb.Append(" EndDate: ").Append(EndDate).Append("\n"); + sb.Append(" LockDate: ").Append(LockDate).Append("\n"); + sb.Append(" EarliestStartTime: ").Append(EarliestStartTime).Append("\n"); + sb.Append(" LatestEndTime: ").Append(LatestEndTime).Append("\n"); + sb.Append(" BudgetPlanningType: ").Append(BudgetPlanningType).Append("\n"); + sb.Append(" BudgetHoursPlanned: ").Append(BudgetHoursPlanned).Append("\n"); + sb.Append(" BudgetHourlyRate: ").Append(BudgetHourlyRate).Append("\n"); + sb.Append(" BudgetPlanned: ").Append(BudgetPlanned).Append("\n"); + sb.Append(" BudgetIncludeNonBillableProjectTimes: ").Append(BudgetIncludeNonBillableProjectTimes).Append("\n"); + sb.Append(" LocationInherited: ").Append(LocationInherited).Append("\n"); + sb.Append(" Location: ").Append(Location).Append("\n"); + sb.Append(" LocationRestrictionRadiusMeters: ").Append(LocationRestrictionRadiusMeters).Append("\n"); + sb.Append(" CustomField1: ").Append(CustomField1).Append("\n"); + sb.Append(" CustomField2: ").Append(CustomField2).Append("\n"); + sb.Append(" CustomField3: ").Append(CustomField3).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskBaseJsonConverter : JsonConverter + { + /// + /// The format to use to serialize StartDate + /// + public static string StartDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize EndDate + /// + public static string EndDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize LockDate + /// + public static string LockDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskBase Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option parentTaskId = default; + Option externalId = default; + Option description = default; + Option descriptionExternal = default; + Option bookable = default; + Option billable = default; + Option projectTimeNotesRequired = default; + Option startDate = default; + Option endDate = default; + Option lockDate = default; + Option earliestStartTime = default; + Option latestEndTime = default; + Option budgetPlanningType = default; + Option budgetHoursPlanned = default; + Option budgetHourlyRate = default; + Option budgetPlanned = default; + Option budgetIncludeNonBillableProjectTimes = default; + Option locationInherited = default; + Option location = default; + Option locationRestrictionRadiusMeters = default; + Option customField1 = default; + Option customField2 = default; + Option customField3 = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "parent_task_id": + parentTaskId = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "description": + description = new Option(utf8JsonReader.GetString()); + break; + case "description_external": + descriptionExternal = new Option(utf8JsonReader.GetString()); + break; + case "bookable": + bookable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "billable": + billable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "project_time_notes_required": + projectTimeNotesRequired = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "start_date": + startDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_date": + endDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "lock_date": + lockDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "earliest_start_time": + earliestStartTime = new Option(utf8JsonReader.GetString()); + break; + case "latest_end_time": + latestEndTime = new Option(utf8JsonReader.GetString()); + break; + case "budget_planning_type": + string? budgetPlanningTypeRawValue = utf8JsonReader.GetString(); + if (budgetPlanningTypeRawValue != null) + budgetPlanningType = new Option(BudgetPlanningTypeRequestValueConverter.FromStringOrDefault(budgetPlanningTypeRawValue)); + break; + case "budget_hours_planned": + budgetHoursPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_hourly_rate": + budgetHourlyRate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_planned": + budgetPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_include_non_billable_project_times": + budgetIncludeNonBillableProjectTimes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "location_inherited": + locationInherited = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "location": + location = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "location_restriction_radius_meters": + locationRestrictionRadiusMeters = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "custom_field_1": + customField1 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_2": + customField2 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_3": + customField3 = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class TaskBase."); + + if (bookable.IsSet && bookable.Value == null) + throw new ArgumentNullException(nameof(bookable), "Property is not nullable for class TaskBase."); + + if (billable.IsSet && billable.Value == null) + throw new ArgumentNullException(nameof(billable), "Property is not nullable for class TaskBase."); + + if (projectTimeNotesRequired.IsSet && projectTimeNotesRequired.Value == null) + throw new ArgumentNullException(nameof(projectTimeNotesRequired), "Property is not nullable for class TaskBase."); + + if (budgetPlanningType.IsSet && budgetPlanningType.Value == null) + throw new ArgumentNullException(nameof(budgetPlanningType), "Property is not nullable for class TaskBase."); + + if (budgetIncludeNonBillableProjectTimes.IsSet && budgetIncludeNonBillableProjectTimes.Value == null) + throw new ArgumentNullException(nameof(budgetIncludeNonBillableProjectTimes), "Property is not nullable for class TaskBase."); + + if (locationInherited.IsSet && locationInherited.Value == null) + throw new ArgumentNullException(nameof(locationInherited), "Property is not nullable for class TaskBase."); + + return new TaskBase(name, parentTaskId, externalId, description, descriptionExternal, bookable, billable, projectTimeNotesRequired, startDate, endDate, lockDate, earliestStartTime, latestEndTime, budgetPlanningType, budgetHoursPlanned, budgetHourlyRate, budgetPlanned, budgetIncludeNonBillableProjectTimes, locationInherited, location, locationRestrictionRadiusMeters, customField1, customField2, customField3, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskBase taskBase, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskBase, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskBase taskBase, JsonSerializerOptions jsonSerializerOptions) + { + if (taskBase.NameOption.IsSet && taskBase.Name == null) + throw new ArgumentNullException(nameof(taskBase.Name), "Property is required for class TaskBase."); + + if (taskBase.NameOption.IsSet) + writer.WriteString("name", taskBase.Name); + + if (taskBase.ParentTaskIdOption.IsSet) + if (taskBase.ParentTaskIdOption.Value != null) + writer.WriteString("parent_task_id", taskBase.ParentTaskId); + else + writer.WriteNull("parent_task_id"); + + if (taskBase.ExternalIdOption.IsSet) + if (taskBase.ExternalIdOption.Value != null) + writer.WriteString("external_id", taskBase.ExternalId); + else + writer.WriteNull("external_id"); + + if (taskBase.DescriptionOption.IsSet) + if (taskBase.DescriptionOption.Value != null) + writer.WriteString("description", taskBase.Description); + else + writer.WriteNull("description"); + + if (taskBase.DescriptionExternalOption.IsSet) + if (taskBase.DescriptionExternalOption.Value != null) + writer.WriteString("description_external", taskBase.DescriptionExternal); + else + writer.WriteNull("description_external"); + + if (taskBase.BookableOption.IsSet) + writer.WriteBoolean("bookable", taskBase.BookableOption.Value!.Value); + + if (taskBase.BillableOption.IsSet) + writer.WriteBoolean("billable", taskBase.BillableOption.Value!.Value); + + if (taskBase.ProjectTimeNotesRequiredOption.IsSet) + writer.WriteBoolean("project_time_notes_required", taskBase.ProjectTimeNotesRequiredOption.Value!.Value); + + if (taskBase.StartDateOption.IsSet) + if (taskBase.StartDateOption.Value != null) + writer.WriteString("start_date", taskBase.StartDateOption.Value!.Value.ToString(StartDateFormat)); + else + writer.WriteNull("start_date"); + + if (taskBase.EndDateOption.IsSet) + if (taskBase.EndDateOption.Value != null) + writer.WriteString("end_date", taskBase.EndDateOption.Value!.Value.ToString(EndDateFormat)); + else + writer.WriteNull("end_date"); + + if (taskBase.LockDateOption.IsSet) + if (taskBase.LockDateOption.Value != null) + writer.WriteString("lock_date", taskBase.LockDateOption.Value!.Value.ToString(LockDateFormat)); + else + writer.WriteNull("lock_date"); + + if (taskBase.EarliestStartTimeOption.IsSet) + if (taskBase.EarliestStartTimeOption.Value != null) + writer.WriteString("earliest_start_time", taskBase.EarliestStartTime); + else + writer.WriteNull("earliest_start_time"); + + if (taskBase.LatestEndTimeOption.IsSet) + if (taskBase.LatestEndTimeOption.Value != null) + writer.WriteString("latest_end_time", taskBase.LatestEndTime); + else + writer.WriteNull("latest_end_time"); + + if (taskBase.BudgetPlanningTypeOption.IsSet) + { + var budgetPlanningTypeRawValue = BudgetPlanningTypeRequestValueConverter.ToJsonValue(taskBase.BudgetPlanningType!.Value); + writer.WriteString("budget_planning_type", budgetPlanningTypeRawValue); + } + if (taskBase.BudgetHoursPlannedOption.IsSet) + if (taskBase.BudgetHoursPlannedOption.Value != null) + writer.WriteNumber("budget_hours_planned", taskBase.BudgetHoursPlannedOption.Value!.Value); + else + writer.WriteNull("budget_hours_planned"); + + if (taskBase.BudgetHourlyRateOption.IsSet) + if (taskBase.BudgetHourlyRateOption.Value != null) + writer.WriteNumber("budget_hourly_rate", taskBase.BudgetHourlyRateOption.Value!.Value); + else + writer.WriteNull("budget_hourly_rate"); + + if (taskBase.BudgetPlannedOption.IsSet) + if (taskBase.BudgetPlannedOption.Value != null) + writer.WriteNumber("budget_planned", taskBase.BudgetPlannedOption.Value!.Value); + else + writer.WriteNull("budget_planned"); + + if (taskBase.BudgetIncludeNonBillableProjectTimesOption.IsSet) + writer.WriteBoolean("budget_include_non_billable_project_times", taskBase.BudgetIncludeNonBillableProjectTimesOption.Value!.Value); + + if (taskBase.LocationInheritedOption.IsSet) + writer.WriteBoolean("location_inherited", taskBase.LocationInheritedOption.Value!.Value); + + if (taskBase.LocationOption.IsSet) + if (taskBase.LocationOption.Value != null) + { + writer.WritePropertyName("location"); + JsonSerializer.Serialize(writer, taskBase.Location, jsonSerializerOptions); + } + else + writer.WriteNull("location"); + if (taskBase.LocationRestrictionRadiusMetersOption.IsSet) + if (taskBase.LocationRestrictionRadiusMetersOption.Value != null) + writer.WriteNumber("location_restriction_radius_meters", taskBase.LocationRestrictionRadiusMetersOption.Value!.Value); + else + writer.WriteNull("location_restriction_radius_meters"); + + if (taskBase.CustomField1Option.IsSet) + if (taskBase.CustomField1Option.Value != null) + writer.WriteString("custom_field_1", taskBase.CustomField1); + else + writer.WriteNull("custom_field_1"); + + if (taskBase.CustomField2Option.IsSet) + if (taskBase.CustomField2Option.Value != null) + writer.WriteString("custom_field_2", taskBase.CustomField2); + else + writer.WriteNull("custom_field_2"); + + if (taskBase.CustomField3Option.IsSet) + if (taskBase.CustomField3Option.Value != null) + writer.WriteString("custom_field_3", taskBase.CustomField3); + else + writer.WriteNull("custom_field_3"); + + if (taskBase.MetadataOption.IsSet) + if (taskBase.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, taskBase.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskCreate.cs b/sdk/dotnet/Timr.Api/Model/TaskCreate.cs new file mode 100644 index 0000000..faf79d2 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskCreate.cs @@ -0,0 +1,823 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskCreate + /// + public partial class TaskCreate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + /// when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + /// billable + /// returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// description + /// descriptionExternal + /// depending on this property project times booked on this task have to include notes or not + /// the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + /// set this property to limit the task so that it cannot be booked before this time + /// set this property to limit the task so that it cannot be booked after this time + /// when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + /// how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + /// the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// set this property to true, if you want to include not billable hours for all project times booked on this task + /// set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + /// location + /// set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// metadata + [JsonConstructor] + public TaskCreate(string name, bool bookable, bool billable, Option parentTaskId = default, Option externalId = default, Option description = default, Option descriptionExternal = default, Option projectTimeNotesRequired = default, Option startDate = default, Option endDate = default, Option lockDate = default, Option earliestStartTime = default, Option latestEndTime = default, Option budgetPlanningType = default, Option budgetHoursPlanned = default, Option budgetHourlyRate = default, Option budgetPlanned = default, Option budgetIncludeNonBillableProjectTimes = default, Option locationInherited = default, Option location = default, Option locationRestrictionRadiusMeters = default, Option customField1 = default, Option customField2 = default, Option customField3 = default, Option?> metadata = default) + { + Name = name; + Bookable = bookable; + Billable = billable; + ParentTaskIdOption = parentTaskId; + ExternalIdOption = externalId; + DescriptionOption = description; + DescriptionExternalOption = descriptionExternal; + ProjectTimeNotesRequiredOption = projectTimeNotesRequired; + StartDateOption = startDate; + EndDateOption = endDate; + LockDateOption = lockDate; + EarliestStartTimeOption = earliestStartTime; + LatestEndTimeOption = latestEndTime; + BudgetPlanningTypeOption = budgetPlanningType; + BudgetHoursPlannedOption = budgetHoursPlanned; + BudgetHourlyRateOption = budgetHourlyRate; + BudgetPlannedOption = budgetPlanned; + BudgetIncludeNonBillableProjectTimesOption = budgetIncludeNonBillableProjectTimes; + LocationInheritedOption = locationInherited; + LocationOption = location; + LocationRestrictionRadiusMetersOption = locationRestrictionRadiusMeters; + CustomField1Option = customField1; + CustomField2Option = customField2; + CustomField3Option = customField3; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of BudgetPlanningType + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetPlanningTypeOption { get; private set; } + + /// + /// when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + /// + /// when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + [JsonPropertyName("budget_planning_type")] + public BudgetPlanningTypeRequest? BudgetPlanningType { get { return this.BudgetPlanningTypeOption.Value; } set { this.BudgetPlanningTypeOption = new(value); } } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + /// + /// when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + [JsonPropertyName("bookable")] + public bool Bookable { get; set; } + + /// + /// Gets or Sets Billable + /// + [JsonPropertyName("billable")] + public bool Billable { get; set; } + + /// + /// Used to track the state of ParentTaskId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ParentTaskIdOption { get; private set; } + + /// + /// returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + /// + /// returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + [JsonPropertyName("parent_task_id")] + public string? ParentTaskId { get { return this.ParentTaskIdOption.Value; } set { this.ParentTaskIdOption = new(value); } } + + /// + /// Used to track the state of ExternalId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ExternalIdOption { get; private set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get { return this.ExternalIdOption.Value; } set { this.ExternalIdOption = new(value); } } + + /// + /// Used to track the state of Description + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DescriptionOption { get; private set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string? Description { get { return this.DescriptionOption.Value; } set { this.DescriptionOption = new(value); } } + + /// + /// Used to track the state of DescriptionExternal + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DescriptionExternalOption { get; private set; } + + /// + /// Gets or Sets DescriptionExternal + /// + [JsonPropertyName("description_external")] + public string? DescriptionExternal { get { return this.DescriptionExternalOption.Value; } set { this.DescriptionExternalOption = new(value); } } + + /// + /// Used to track the state of ProjectTimeNotesRequired + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ProjectTimeNotesRequiredOption { get; private set; } + + /// + /// depending on this property project times booked on this task have to include notes or not + /// + /// depending on this property project times booked on this task have to include notes or not + [JsonPropertyName("project_time_notes_required")] + public bool? ProjectTimeNotesRequired { get { return this.ProjectTimeNotesRequiredOption.Value; } set { this.ProjectTimeNotesRequiredOption = new(value); } } + + /// + /// Used to track the state of StartDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartDateOption { get; private set; } + + /// + /// the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// + /// the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + [JsonPropertyName("start_date")] + public DateOnly? StartDate { get { return this.StartDateOption.Value; } set { this.StartDateOption = new(value); } } + + /// + /// Used to track the state of EndDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndDateOption { get; private set; } + + /// + /// the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// + /// the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + [JsonPropertyName("end_date")] + public DateOnly? EndDate { get { return this.EndDateOption.Value; } set { this.EndDateOption = new(value); } } + + /// + /// Used to track the state of LockDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LockDateOption { get; private set; } + + /// + /// with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + /// + /// with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + [JsonPropertyName("lock_date")] + public DateOnly? LockDate { get { return this.LockDateOption.Value; } set { this.LockDateOption = new(value); } } + + /// + /// Used to track the state of EarliestStartTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EarliestStartTimeOption { get; private set; } + + /// + /// set this property to limit the task so that it cannot be booked before this time + /// + /// set this property to limit the task so that it cannot be booked before this time + /* 920 */ + [JsonPropertyName("earliest_start_time")] + public string? EarliestStartTime { get { return this.EarliestStartTimeOption.Value; } set { this.EarliestStartTimeOption = new(value); } } + + /// + /// Used to track the state of LatestEndTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LatestEndTimeOption { get; private set; } + + /// + /// set this property to limit the task so that it cannot be booked after this time + /// + /// set this property to limit the task so that it cannot be booked after this time + /* 920 */ + [JsonPropertyName("latest_end_time")] + public string? LatestEndTime { get { return this.LatestEndTimeOption.Value; } set { this.LatestEndTimeOption = new(value); } } + + /// + /// Used to track the state of BudgetHoursPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetHoursPlannedOption { get; private set; } + + /// + /// how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// + /// how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + [JsonPropertyName("budget_hours_planned")] + public decimal? BudgetHoursPlanned { get { return this.BudgetHoursPlannedOption.Value; } set { this.BudgetHoursPlannedOption = new(value); } } + + /// + /// Used to track the state of BudgetHourlyRate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetHourlyRateOption { get; private set; } + + /// + /// depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + /// + /// depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + [JsonPropertyName("budget_hourly_rate")] + public decimal? BudgetHourlyRate { get { return this.BudgetHourlyRateOption.Value; } set { this.BudgetHourlyRateOption = new(value); } } + + /// + /// Used to track the state of BudgetPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetPlannedOption { get; private set; } + + /// + /// the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// + /// the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + [JsonPropertyName("budget_planned")] + public decimal? BudgetPlanned { get { return this.BudgetPlannedOption.Value; } set { this.BudgetPlannedOption = new(value); } } + + /// + /// Used to track the state of BudgetIncludeNonBillableProjectTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetIncludeNonBillableProjectTimesOption { get; private set; } + + /// + /// set this property to true, if you want to include not billable hours for all project times booked on this task + /// + /// set this property to true, if you want to include not billable hours for all project times booked on this task + [JsonPropertyName("budget_include_non_billable_project_times")] + public bool? BudgetIncludeNonBillableProjectTimes { get { return this.BudgetIncludeNonBillableProjectTimesOption.Value; } set { this.BudgetIncludeNonBillableProjectTimesOption = new(value); } } + + /// + /// Used to track the state of LocationInherited + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationInheritedOption { get; private set; } + + /// + /// set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + /// + /// set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + [JsonPropertyName("location_inherited")] + public bool? LocationInherited { get { return this.LocationInheritedOption.Value; } set { this.LocationInheritedOption = new(value); } } + + /// + /// Used to track the state of Location + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationOption { get; private set; } + + /// + /// Gets or Sets Location + /// + [JsonPropertyName("location")] + public TaskLocation? Location { get { return this.LocationOption.Value; } set { this.LocationOption = new(value); } } + + /// + /// Used to track the state of LocationRestrictionRadiusMeters + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationRestrictionRadiusMetersOption { get; private set; } + + /// + /// set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + /// + /// set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + [JsonPropertyName("location_restriction_radius_meters")] + public int? LocationRestrictionRadiusMeters { get { return this.LocationRestrictionRadiusMetersOption.Value; } set { this.LocationRestrictionRadiusMetersOption = new(value); } } + + /// + /// Used to track the state of CustomField1 + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option CustomField1Option { get; private set; } + + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + [JsonPropertyName("custom_field_1")] + public string? CustomField1 { get { return this.CustomField1Option.Value; } set { this.CustomField1Option = new(value); } } + + /// + /// Used to track the state of CustomField2 + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option CustomField2Option { get; private set; } + + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + [JsonPropertyName("custom_field_2")] + public string? CustomField2 { get { return this.CustomField2Option.Value; } set { this.CustomField2Option = new(value); } } + + /// + /// Used to track the state of CustomField3 + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option CustomField3Option { get; private set; } + + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + [JsonPropertyName("custom_field_3")] + public string? CustomField3 { get { return this.CustomField3Option.Value; } set { this.CustomField3Option = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskCreate {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Bookable: ").Append(Bookable).Append("\n"); + sb.Append(" Billable: ").Append(Billable).Append("\n"); + sb.Append(" ParentTaskId: ").Append(ParentTaskId).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DescriptionExternal: ").Append(DescriptionExternal).Append("\n"); + sb.Append(" ProjectTimeNotesRequired: ").Append(ProjectTimeNotesRequired).Append("\n"); + sb.Append(" StartDate: ").Append(StartDate).Append("\n"); + sb.Append(" EndDate: ").Append(EndDate).Append("\n"); + sb.Append(" LockDate: ").Append(LockDate).Append("\n"); + sb.Append(" EarliestStartTime: ").Append(EarliestStartTime).Append("\n"); + sb.Append(" LatestEndTime: ").Append(LatestEndTime).Append("\n"); + sb.Append(" BudgetPlanningType: ").Append(BudgetPlanningType).Append("\n"); + sb.Append(" BudgetHoursPlanned: ").Append(BudgetHoursPlanned).Append("\n"); + sb.Append(" BudgetHourlyRate: ").Append(BudgetHourlyRate).Append("\n"); + sb.Append(" BudgetPlanned: ").Append(BudgetPlanned).Append("\n"); + sb.Append(" BudgetIncludeNonBillableProjectTimes: ").Append(BudgetIncludeNonBillableProjectTimes).Append("\n"); + sb.Append(" LocationInherited: ").Append(LocationInherited).Append("\n"); + sb.Append(" Location: ").Append(Location).Append("\n"); + sb.Append(" LocationRestrictionRadiusMeters: ").Append(LocationRestrictionRadiusMeters).Append("\n"); + sb.Append(" CustomField1: ").Append(CustomField1).Append("\n"); + sb.Append(" CustomField2: ").Append(CustomField2).Append("\n"); + sb.Append(" CustomField3: ").Append(CustomField3).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskCreateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize StartDate + /// + public static string StartDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize EndDate + /// + public static string EndDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize LockDate + /// + public static string LockDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskCreate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option bookable = default; + Option billable = default; + Option parentTaskId = default; + Option externalId = default; + Option description = default; + Option descriptionExternal = default; + Option projectTimeNotesRequired = default; + Option startDate = default; + Option endDate = default; + Option lockDate = default; + Option earliestStartTime = default; + Option latestEndTime = default; + Option budgetPlanningType = default; + Option budgetHoursPlanned = default; + Option budgetHourlyRate = default; + Option budgetPlanned = default; + Option budgetIncludeNonBillableProjectTimes = default; + Option locationInherited = default; + Option location = default; + Option locationRestrictionRadiusMeters = default; + Option customField1 = default; + Option customField2 = default; + Option customField3 = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "bookable": + bookable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "billable": + billable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "parent_task_id": + parentTaskId = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "description": + description = new Option(utf8JsonReader.GetString()); + break; + case "description_external": + descriptionExternal = new Option(utf8JsonReader.GetString()); + break; + case "project_time_notes_required": + projectTimeNotesRequired = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "start_date": + startDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_date": + endDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "lock_date": + lockDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "earliest_start_time": + earliestStartTime = new Option(utf8JsonReader.GetString()); + break; + case "latest_end_time": + latestEndTime = new Option(utf8JsonReader.GetString()); + break; + case "budget_planning_type": + string? budgetPlanningTypeRawValue = utf8JsonReader.GetString(); + if (budgetPlanningTypeRawValue != null) + budgetPlanningType = new Option(BudgetPlanningTypeRequestValueConverter.FromStringOrDefault(budgetPlanningTypeRawValue)); + break; + case "budget_hours_planned": + budgetHoursPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_hourly_rate": + budgetHourlyRate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_planned": + budgetPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_include_non_billable_project_times": + budgetIncludeNonBillableProjectTimes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "location_inherited": + locationInherited = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "location": + location = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "location_restriction_radius_meters": + locationRestrictionRadiusMeters = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "custom_field_1": + customField1 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_2": + customField2 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_3": + customField3 = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!name.IsSet) + throw new ArgumentException("Property is required for class TaskCreate.", nameof(name)); + + if (!bookable.IsSet) + throw new ArgumentException("Property is required for class TaskCreate.", nameof(bookable)); + + if (!billable.IsSet) + throw new ArgumentException("Property is required for class TaskCreate.", nameof(billable)); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class TaskCreate."); + + if (bookable.IsSet && bookable.Value == null) + throw new ArgumentNullException(nameof(bookable), "Property is not nullable for class TaskCreate."); + + if (billable.IsSet && billable.Value == null) + throw new ArgumentNullException(nameof(billable), "Property is not nullable for class TaskCreate."); + + if (projectTimeNotesRequired.IsSet && projectTimeNotesRequired.Value == null) + throw new ArgumentNullException(nameof(projectTimeNotesRequired), "Property is not nullable for class TaskCreate."); + + if (budgetPlanningType.IsSet && budgetPlanningType.Value == null) + throw new ArgumentNullException(nameof(budgetPlanningType), "Property is not nullable for class TaskCreate."); + + if (budgetIncludeNonBillableProjectTimes.IsSet && budgetIncludeNonBillableProjectTimes.Value == null) + throw new ArgumentNullException(nameof(budgetIncludeNonBillableProjectTimes), "Property is not nullable for class TaskCreate."); + + if (locationInherited.IsSet && locationInherited.Value == null) + throw new ArgumentNullException(nameof(locationInherited), "Property is not nullable for class TaskCreate."); + + return new TaskCreate(name.Value!, bookable.Value!.Value!, billable.Value!.Value!, parentTaskId, externalId, description, descriptionExternal, projectTimeNotesRequired, startDate, endDate, lockDate, earliestStartTime, latestEndTime, budgetPlanningType, budgetHoursPlanned, budgetHourlyRate, budgetPlanned, budgetIncludeNonBillableProjectTimes, locationInherited, location, locationRestrictionRadiusMeters, customField1, customField2, customField3, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskCreate taskCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskCreate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskCreate taskCreate, JsonSerializerOptions jsonSerializerOptions) + { + if (taskCreate.Name == null) + throw new ArgumentNullException(nameof(taskCreate.Name), "Property is required for class TaskCreate."); + + writer.WriteString("name", taskCreate.Name); + + writer.WriteBoolean("bookable", taskCreate.Bookable); + + writer.WriteBoolean("billable", taskCreate.Billable); + + if (taskCreate.ParentTaskIdOption.IsSet) + if (taskCreate.ParentTaskIdOption.Value != null) + writer.WriteString("parent_task_id", taskCreate.ParentTaskId); + else + writer.WriteNull("parent_task_id"); + + if (taskCreate.ExternalIdOption.IsSet) + if (taskCreate.ExternalIdOption.Value != null) + writer.WriteString("external_id", taskCreate.ExternalId); + else + writer.WriteNull("external_id"); + + if (taskCreate.DescriptionOption.IsSet) + if (taskCreate.DescriptionOption.Value != null) + writer.WriteString("description", taskCreate.Description); + else + writer.WriteNull("description"); + + if (taskCreate.DescriptionExternalOption.IsSet) + if (taskCreate.DescriptionExternalOption.Value != null) + writer.WriteString("description_external", taskCreate.DescriptionExternal); + else + writer.WriteNull("description_external"); + + if (taskCreate.ProjectTimeNotesRequiredOption.IsSet) + writer.WriteBoolean("project_time_notes_required", taskCreate.ProjectTimeNotesRequiredOption.Value!.Value); + + if (taskCreate.StartDateOption.IsSet) + if (taskCreate.StartDateOption.Value != null) + writer.WriteString("start_date", taskCreate.StartDateOption.Value!.Value.ToString(StartDateFormat)); + else + writer.WriteNull("start_date"); + + if (taskCreate.EndDateOption.IsSet) + if (taskCreate.EndDateOption.Value != null) + writer.WriteString("end_date", taskCreate.EndDateOption.Value!.Value.ToString(EndDateFormat)); + else + writer.WriteNull("end_date"); + + if (taskCreate.LockDateOption.IsSet) + if (taskCreate.LockDateOption.Value != null) + writer.WriteString("lock_date", taskCreate.LockDateOption.Value!.Value.ToString(LockDateFormat)); + else + writer.WriteNull("lock_date"); + + if (taskCreate.EarliestStartTimeOption.IsSet) + if (taskCreate.EarliestStartTimeOption.Value != null) + writer.WriteString("earliest_start_time", taskCreate.EarliestStartTime); + else + writer.WriteNull("earliest_start_time"); + + if (taskCreate.LatestEndTimeOption.IsSet) + if (taskCreate.LatestEndTimeOption.Value != null) + writer.WriteString("latest_end_time", taskCreate.LatestEndTime); + else + writer.WriteNull("latest_end_time"); + + if (taskCreate.BudgetPlanningTypeOption.IsSet) + { + var budgetPlanningTypeRawValue = BudgetPlanningTypeRequestValueConverter.ToJsonValue(taskCreate.BudgetPlanningType!.Value); + writer.WriteString("budget_planning_type", budgetPlanningTypeRawValue); + } + if (taskCreate.BudgetHoursPlannedOption.IsSet) + if (taskCreate.BudgetHoursPlannedOption.Value != null) + writer.WriteNumber("budget_hours_planned", taskCreate.BudgetHoursPlannedOption.Value!.Value); + else + writer.WriteNull("budget_hours_planned"); + + if (taskCreate.BudgetHourlyRateOption.IsSet) + if (taskCreate.BudgetHourlyRateOption.Value != null) + writer.WriteNumber("budget_hourly_rate", taskCreate.BudgetHourlyRateOption.Value!.Value); + else + writer.WriteNull("budget_hourly_rate"); + + if (taskCreate.BudgetPlannedOption.IsSet) + if (taskCreate.BudgetPlannedOption.Value != null) + writer.WriteNumber("budget_planned", taskCreate.BudgetPlannedOption.Value!.Value); + else + writer.WriteNull("budget_planned"); + + if (taskCreate.BudgetIncludeNonBillableProjectTimesOption.IsSet) + writer.WriteBoolean("budget_include_non_billable_project_times", taskCreate.BudgetIncludeNonBillableProjectTimesOption.Value!.Value); + + if (taskCreate.LocationInheritedOption.IsSet) + writer.WriteBoolean("location_inherited", taskCreate.LocationInheritedOption.Value!.Value); + + if (taskCreate.LocationOption.IsSet) + if (taskCreate.LocationOption.Value != null) + { + writer.WritePropertyName("location"); + JsonSerializer.Serialize(writer, taskCreate.Location, jsonSerializerOptions); + } + else + writer.WriteNull("location"); + if (taskCreate.LocationRestrictionRadiusMetersOption.IsSet) + if (taskCreate.LocationRestrictionRadiusMetersOption.Value != null) + writer.WriteNumber("location_restriction_radius_meters", taskCreate.LocationRestrictionRadiusMetersOption.Value!.Value); + else + writer.WriteNull("location_restriction_radius_meters"); + + if (taskCreate.CustomField1Option.IsSet) + if (taskCreate.CustomField1Option.Value != null) + writer.WriteString("custom_field_1", taskCreate.CustomField1); + else + writer.WriteNull("custom_field_1"); + + if (taskCreate.CustomField2Option.IsSet) + if (taskCreate.CustomField2Option.Value != null) + writer.WriteString("custom_field_2", taskCreate.CustomField2); + else + writer.WriteNull("custom_field_2"); + + if (taskCreate.CustomField3Option.IsSet) + if (taskCreate.CustomField3Option.Value != null) + writer.WriteString("custom_field_3", taskCreate.CustomField3); + else + writer.WriteNull("custom_field_3"); + + if (taskCreate.MetadataOption.IsSet) + if (taskCreate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, taskCreate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskLocation.cs b/sdk/dotnet/Timr.Api/Model/TaskLocation.cs new file mode 100644 index 0000000..df1d6f7 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskLocation.cs @@ -0,0 +1,291 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// You can define the location of a task by setting this property. If the task has a parent task, the location is inherited if nothing else is explicitly defined. If you set this property to null, the location will be deleted. + /// + public partial class TaskLocation : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Latitude in decimal degrees. + /// Longitude in decimal degrees. + /// address + /// city + /// zipCode + /// state + /// the country's international country code + [JsonConstructor] + public TaskLocation(float? lat = default, float? lon = default, string? address = default, string? city = default, string? zipCode = default, string? state = default, string? country = default) + { + Lat = lat; + Lon = lon; + Address = address; + City = city; + ZipCode = zipCode; + State = state; + Country = country; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Latitude in decimal degrees. + /// + /// Latitude in decimal degrees. + [JsonPropertyName("lat")] + public float? Lat { get; set; } + + /// + /// Longitude in decimal degrees. + /// + /// Longitude in decimal degrees. + [JsonPropertyName("lon")] + public float? Lon { get; set; } + + /// + /// Gets or Sets Address + /// + [JsonPropertyName("address")] + public string? Address { get; set; } + + /// + /// Gets or Sets City + /// + [JsonPropertyName("city")] + public string? City { get; set; } + + /// + /// Gets or Sets ZipCode + /// + [JsonPropertyName("zip_code")] + public string? ZipCode { get; set; } + + /// + /// Gets or Sets State + /// + [JsonPropertyName("state")] + public string? State { get; set; } + + /// + /// the country's international country code + /// + /// the country's international country code + /* AT, DE, ES */ + [JsonPropertyName("country")] + public string? Country { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskLocation {\n"); + sb.Append(" Lat: ").Append(Lat).Append("\n"); + sb.Append(" Lon: ").Append(Lon).Append("\n"); + sb.Append(" Address: ").Append(Address).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" ZipCode: ").Append(ZipCode).Append("\n"); + sb.Append(" State: ").Append(State).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskLocationJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskLocation Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option lat = default; + Option lon = default; + Option address = default; + Option city = default; + Option zipCode = default; + Option state = default; + Option country = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "lat": + lat = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + case "lon": + lon = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + case "address": + address = new Option(utf8JsonReader.GetString()); + break; + case "city": + city = new Option(utf8JsonReader.GetString()); + break; + case "zip_code": + zipCode = new Option(utf8JsonReader.GetString()); + break; + case "state": + state = new Option(utf8JsonReader.GetString()); + break; + case "country": + country = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!lat.IsSet) + throw new ArgumentException("Property is required for class TaskLocation.", nameof(lat)); + + if (!lon.IsSet) + throw new ArgumentException("Property is required for class TaskLocation.", nameof(lon)); + + if (!address.IsSet) + throw new ArgumentException("Property is required for class TaskLocation.", nameof(address)); + + if (!city.IsSet) + throw new ArgumentException("Property is required for class TaskLocation.", nameof(city)); + + if (!zipCode.IsSet) + throw new ArgumentException("Property is required for class TaskLocation.", nameof(zipCode)); + + if (!state.IsSet) + throw new ArgumentException("Property is required for class TaskLocation.", nameof(state)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class TaskLocation.", nameof(country)); + + return new TaskLocation(lat.Value!, lon.Value!, address.Value!, city.Value!, zipCode.Value!, state.Value!, country.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskLocation taskLocation, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskLocation, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskLocation taskLocation, JsonSerializerOptions jsonSerializerOptions) + { + if (taskLocation.Lat != null) + writer.WriteNumber("lat", taskLocation.Lat.Value); + else + writer.WriteNull("lat"); + + if (taskLocation.Lon != null) + writer.WriteNumber("lon", taskLocation.Lon.Value); + else + writer.WriteNull("lon"); + + if (taskLocation.Address != null) + writer.WriteString("address", taskLocation.Address); + else + writer.WriteNull("address"); + + if (taskLocation.City != null) + writer.WriteString("city", taskLocation.City); + else + writer.WriteNull("city"); + + if (taskLocation.ZipCode != null) + writer.WriteString("zip_code", taskLocation.ZipCode); + else + writer.WriteNull("zip_code"); + + if (taskLocation.State != null) + writer.WriteString("state", taskLocation.State); + else + writer.WriteNull("state"); + + if (taskLocation.Country != null) + writer.WriteString("country", taskLocation.Country); + else + writer.WriteNull("country"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskPartial.cs b/sdk/dotnet/Timr.Api/Model/TaskPartial.cs new file mode 100644 index 0000000..da570d0 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskPartial.cs @@ -0,0 +1,236 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskPartial + /// + public partial class TaskPartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// Full path of the entry within its hierarchy, including its own name. + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonConstructor] + public TaskPartial(string id, string name, string breadcrumbs, string? externalId = default) + { + Id = id; + Name = name; + Breadcrumbs = breadcrumbs; + ExternalId = externalId; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Full path of the entry within its hierarchy, including its own name. + /// + /// Full path of the entry within its hierarchy, including its own name. + [JsonPropertyName("breadcrumbs")] + public string Breadcrumbs { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskPartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Breadcrumbs: ").Append(Breadcrumbs).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskPartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskPartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option breadcrumbs = default; + Option externalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "breadcrumbs": + breadcrumbs = new Option(utf8JsonReader.GetString()!); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class TaskPartial.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class TaskPartial.", nameof(name)); + + if (!breadcrumbs.IsSet) + throw new ArgumentException("Property is required for class TaskPartial.", nameof(breadcrumbs)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class TaskPartial.", nameof(externalId)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class TaskPartial."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class TaskPartial."); + + if (breadcrumbs.IsSet && breadcrumbs.Value == null) + throw new ArgumentNullException(nameof(breadcrumbs), "Property is not nullable for class TaskPartial."); + + return new TaskPartial(id.Value!, name.Value!, breadcrumbs.Value!, externalId.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskPartial taskPartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskPartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskPartial taskPartial, JsonSerializerOptions jsonSerializerOptions) + { + if (taskPartial.Id == null) + throw new ArgumentNullException(nameof(taskPartial.Id), "Property is required for class TaskPartial."); + + if (taskPartial.Name == null) + throw new ArgumentNullException(nameof(taskPartial.Name), "Property is required for class TaskPartial."); + + if (taskPartial.Breadcrumbs == null) + throw new ArgumentNullException(nameof(taskPartial.Breadcrumbs), "Property is required for class TaskPartial."); + + writer.WriteString("id", taskPartial.Id); + + writer.WriteString("name", taskPartial.Name); + + writer.WriteString("breadcrumbs", taskPartial.Breadcrumbs); + + if (taskPartial.ExternalId != null) + writer.WriteString("external_id", taskPartial.ExternalId); + else + writer.WriteNull("external_id"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskReduced.cs b/sdk/dotnet/Timr.Api/Model/TaskReduced.cs new file mode 100644 index 0000000..150ceed --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskReduced.cs @@ -0,0 +1,658 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskReduced + /// + public partial class TaskReduced : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// Full path of the entry within its hierarchy, including its own name. + /// bookable + /// billable + /// projectTimeNotesRequired + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// parentTask + /// description + /// RFC 3339 date (ISO-8601) + /// time of day (ISO-8601) + /// time of day (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// budgetPlanningType + /// locationInherited + /// location + /// locationRestrictionRadiusMeters + /// customField1 + /// customField2 + /// customField3 + [JsonConstructor] + public TaskReduced(string id, string name, string breadcrumbs, bool bookable, bool billable, bool projectTimeNotesRequired, string? externalId = default, TaskPartial? parentTask = default, string? description = default, Option lockDate = default, Option earliestStartTime = default, Option latestEndTime = default, DateOnly? activeFrom = default, DateOnly? activeTo = default, Option budgetPlanningType = default, Option locationInherited = default, Option location = default, Option locationRestrictionRadiusMeters = default, string? customField1 = default, string? customField2 = default, string? customField3 = default) + { + Id = id; + Name = name; + Breadcrumbs = breadcrumbs; + Bookable = bookable; + Billable = billable; + ProjectTimeNotesRequired = projectTimeNotesRequired; + ExternalId = externalId; + ParentTask = parentTask; + Description = description; + LockDateOption = lockDate; + EarliestStartTimeOption = earliestStartTime; + LatestEndTimeOption = latestEndTime; + ActiveFrom = activeFrom; + ActiveTo = activeTo; + BudgetPlanningTypeOption = budgetPlanningType; + LocationInheritedOption = locationInherited; + LocationOption = location; + LocationRestrictionRadiusMetersOption = locationRestrictionRadiusMeters; + CustomField1 = customField1; + CustomField2 = customField2; + CustomField3 = customField3; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of BudgetPlanningType + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetPlanningTypeOption { get; private set; } + + /// + /// Gets or Sets BudgetPlanningType + /// + [JsonPropertyName("budget_planning_type")] + public BudgetPlanningType? BudgetPlanningType { get { return this.BudgetPlanningTypeOption.Value; } set { this.BudgetPlanningTypeOption = new(value); } } + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Full path of the entry within its hierarchy, including its own name. + /// + /// Full path of the entry within its hierarchy, including its own name. + [JsonPropertyName("breadcrumbs")] + public string Breadcrumbs { get; set; } + + /// + /// Gets or Sets Bookable + /// + [JsonPropertyName("bookable")] + public bool Bookable { get; set; } + + /// + /// Gets or Sets Billable + /// + [JsonPropertyName("billable")] + public bool Billable { get; set; } + + /// + /// Gets or Sets ProjectTimeNotesRequired + /// + [JsonPropertyName("project_time_notes_required")] + public bool ProjectTimeNotesRequired { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Gets or Sets ParentTask + /// + [JsonPropertyName("parent_task")] + public TaskPartial? ParentTask { get; set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// Used to track the state of LockDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LockDateOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("lock_date")] + public DateOnly? LockDate { get { return this.LockDateOption.Value; } set { this.LockDateOption = new(value); } } + + /// + /// Used to track the state of EarliestStartTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EarliestStartTimeOption { get; private set; } + + /// + /// time of day (ISO-8601) + /// + /// time of day (ISO-8601) + /* 920 */ + [JsonPropertyName("earliest_start_time")] + public string? EarliestStartTime { get { return this.EarliestStartTimeOption.Value; } set { this.EarliestStartTimeOption = new(value); } } + + /// + /// Used to track the state of LatestEndTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LatestEndTimeOption { get; private set; } + + /// + /// time of day (ISO-8601) + /// + /// time of day (ISO-8601) + /* 920 */ + [JsonPropertyName("latest_end_time")] + public string? LatestEndTime { get { return this.LatestEndTimeOption.Value; } set { this.LatestEndTimeOption = new(value); } } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("active_from")] + public DateOnly? ActiveFrom { get; set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("active_to")] + public DateOnly? ActiveTo { get; set; } + + /// + /// Used to track the state of LocationInherited + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationInheritedOption { get; private set; } + + /// + /// Gets or Sets LocationInherited + /// + [JsonPropertyName("location_inherited")] + public bool? LocationInherited { get { return this.LocationInheritedOption.Value; } set { this.LocationInheritedOption = new(value); } } + + /// + /// Used to track the state of Location + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationOption { get; private set; } + + /// + /// Gets or Sets Location + /// + [JsonPropertyName("location")] + public TaskLocation? Location { get { return this.LocationOption.Value; } set { this.LocationOption = new(value); } } + + /// + /// Used to track the state of LocationRestrictionRadiusMeters + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationRestrictionRadiusMetersOption { get; private set; } + + /// + /// Gets or Sets LocationRestrictionRadiusMeters + /// + [JsonPropertyName("location_restriction_radius_meters")] + public int? LocationRestrictionRadiusMeters { get { return this.LocationRestrictionRadiusMetersOption.Value; } set { this.LocationRestrictionRadiusMetersOption = new(value); } } + + /// + /// Gets or Sets CustomField1 + /// + [JsonPropertyName("custom_field_1")] + public string? CustomField1 { get; set; } + + /// + /// Gets or Sets CustomField2 + /// + [JsonPropertyName("custom_field_2")] + public string? CustomField2 { get; set; } + + /// + /// Gets or Sets CustomField3 + /// + [JsonPropertyName("custom_field_3")] + public string? CustomField3 { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskReduced {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Breadcrumbs: ").Append(Breadcrumbs).Append("\n"); + sb.Append(" Bookable: ").Append(Bookable).Append("\n"); + sb.Append(" Billable: ").Append(Billable).Append("\n"); + sb.Append(" ProjectTimeNotesRequired: ").Append(ProjectTimeNotesRequired).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" ParentTask: ").Append(ParentTask).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" LockDate: ").Append(LockDate).Append("\n"); + sb.Append(" EarliestStartTime: ").Append(EarliestStartTime).Append("\n"); + sb.Append(" LatestEndTime: ").Append(LatestEndTime).Append("\n"); + sb.Append(" ActiveFrom: ").Append(ActiveFrom).Append("\n"); + sb.Append(" ActiveTo: ").Append(ActiveTo).Append("\n"); + sb.Append(" BudgetPlanningType: ").Append(BudgetPlanningType).Append("\n"); + sb.Append(" LocationInherited: ").Append(LocationInherited).Append("\n"); + sb.Append(" Location: ").Append(Location).Append("\n"); + sb.Append(" LocationRestrictionRadiusMeters: ").Append(LocationRestrictionRadiusMeters).Append("\n"); + sb.Append(" CustomField1: ").Append(CustomField1).Append("\n"); + sb.Append(" CustomField2: ").Append(CustomField2).Append("\n"); + sb.Append(" CustomField3: ").Append(CustomField3).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskReducedJsonConverter : JsonConverter + { + /// + /// The format to use to serialize LockDate + /// + public static string LockDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize ActiveFrom + /// + public static string ActiveFromFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize ActiveTo + /// + public static string ActiveToFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskReduced Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option breadcrumbs = default; + Option bookable = default; + Option billable = default; + Option projectTimeNotesRequired = default; + Option externalId = default; + Option parentTask = default; + Option description = default; + Option lockDate = default; + Option earliestStartTime = default; + Option latestEndTime = default; + Option activeFrom = default; + Option activeTo = default; + Option budgetPlanningType = default; + Option locationInherited = default; + Option location = default; + Option locationRestrictionRadiusMeters = default; + Option customField1 = default; + Option customField2 = default; + Option customField3 = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "breadcrumbs": + breadcrumbs = new Option(utf8JsonReader.GetString()!); + break; + case "bookable": + bookable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "billable": + billable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "project_time_notes_required": + projectTimeNotesRequired = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "parent_task": + parentTask = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "description": + description = new Option(utf8JsonReader.GetString()); + break; + case "lock_date": + lockDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "earliest_start_time": + earliestStartTime = new Option(utf8JsonReader.GetString()); + break; + case "latest_end_time": + latestEndTime = new Option(utf8JsonReader.GetString()); + break; + case "active_from": + activeFrom = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "active_to": + activeTo = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "budget_planning_type": + string? budgetPlanningTypeRawValue = utf8JsonReader.GetString(); + if (budgetPlanningTypeRawValue != null) + budgetPlanningType = new Option(BudgetPlanningTypeValueConverter.FromStringOrDefault(budgetPlanningTypeRawValue)); + break; + case "location_inherited": + locationInherited = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "location": + location = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "location_restriction_radius_meters": + locationRestrictionRadiusMeters = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "custom_field_1": + customField1 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_2": + customField2 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_3": + customField3 = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(name)); + + if (!breadcrumbs.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(breadcrumbs)); + + if (!bookable.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(bookable)); + + if (!billable.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(billable)); + + if (!projectTimeNotesRequired.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(projectTimeNotesRequired)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(externalId)); + + if (!parentTask.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(parentTask)); + + if (!description.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(description)); + + if (!activeFrom.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(activeFrom)); + + if (!activeTo.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(activeTo)); + + if (!customField1.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(customField1)); + + if (!customField2.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(customField2)); + + if (!customField3.IsSet) + throw new ArgumentException("Property is required for class TaskReduced.", nameof(customField3)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class TaskReduced."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class TaskReduced."); + + if (breadcrumbs.IsSet && breadcrumbs.Value == null) + throw new ArgumentNullException(nameof(breadcrumbs), "Property is not nullable for class TaskReduced."); + + if (bookable.IsSet && bookable.Value == null) + throw new ArgumentNullException(nameof(bookable), "Property is not nullable for class TaskReduced."); + + if (billable.IsSet && billable.Value == null) + throw new ArgumentNullException(nameof(billable), "Property is not nullable for class TaskReduced."); + + if (projectTimeNotesRequired.IsSet && projectTimeNotesRequired.Value == null) + throw new ArgumentNullException(nameof(projectTimeNotesRequired), "Property is not nullable for class TaskReduced."); + + if (budgetPlanningType.IsSet && budgetPlanningType.Value == null) + throw new ArgumentNullException(nameof(budgetPlanningType), "Property is not nullable for class TaskReduced."); + + if (locationInherited.IsSet && locationInherited.Value == null) + throw new ArgumentNullException(nameof(locationInherited), "Property is not nullable for class TaskReduced."); + + return new TaskReduced(id.Value!, name.Value!, breadcrumbs.Value!, bookable.Value!.Value!, billable.Value!.Value!, projectTimeNotesRequired.Value!.Value!, externalId.Value!, parentTask.Value!, description.Value!, lockDate, earliestStartTime, latestEndTime, activeFrom.Value!, activeTo.Value!, budgetPlanningType, locationInherited, location, locationRestrictionRadiusMeters, customField1.Value!, customField2.Value!, customField3.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskReduced taskReduced, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskReduced, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskReduced taskReduced, JsonSerializerOptions jsonSerializerOptions) + { + if (taskReduced.Id == null) + throw new ArgumentNullException(nameof(taskReduced.Id), "Property is required for class TaskReduced."); + + if (taskReduced.Name == null) + throw new ArgumentNullException(nameof(taskReduced.Name), "Property is required for class TaskReduced."); + + if (taskReduced.Breadcrumbs == null) + throw new ArgumentNullException(nameof(taskReduced.Breadcrumbs), "Property is required for class TaskReduced."); + + writer.WriteString("id", taskReduced.Id); + + writer.WriteString("name", taskReduced.Name); + + writer.WriteString("breadcrumbs", taskReduced.Breadcrumbs); + + writer.WriteBoolean("bookable", taskReduced.Bookable); + + writer.WriteBoolean("billable", taskReduced.Billable); + + writer.WriteBoolean("project_time_notes_required", taskReduced.ProjectTimeNotesRequired); + + if (taskReduced.ExternalId != null) + writer.WriteString("external_id", taskReduced.ExternalId); + else + writer.WriteNull("external_id"); + + if (taskReduced.ParentTask != null) + { + writer.WritePropertyName("parent_task"); + JsonSerializer.Serialize(writer, taskReduced.ParentTask, jsonSerializerOptions); + } + else + writer.WriteNull("parent_task"); + if (taskReduced.Description != null) + writer.WriteString("description", taskReduced.Description); + else + writer.WriteNull("description"); + + if (taskReduced.LockDateOption.IsSet) + if (taskReduced.LockDateOption.Value != null) + writer.WriteString("lock_date", taskReduced.LockDateOption.Value!.Value.ToString(LockDateFormat)); + else + writer.WriteNull("lock_date"); + + if (taskReduced.EarliestStartTimeOption.IsSet) + if (taskReduced.EarliestStartTimeOption.Value != null) + writer.WriteString("earliest_start_time", taskReduced.EarliestStartTime); + else + writer.WriteNull("earliest_start_time"); + + if (taskReduced.LatestEndTimeOption.IsSet) + if (taskReduced.LatestEndTimeOption.Value != null) + writer.WriteString("latest_end_time", taskReduced.LatestEndTime); + else + writer.WriteNull("latest_end_time"); + + if (taskReduced.ActiveFrom != null) + writer.WriteString("active_from", taskReduced.ActiveFrom.Value.ToString(ActiveFromFormat)); + else + writer.WriteNull("active_from"); + + if (taskReduced.ActiveTo != null) + writer.WriteString("active_to", taskReduced.ActiveTo.Value.ToString(ActiveToFormat)); + else + writer.WriteNull("active_to"); + + if (taskReduced.BudgetPlanningTypeOption.IsSet) + { + var budgetPlanningTypeRawValue = BudgetPlanningTypeValueConverter.ToJsonValue(taskReduced.BudgetPlanningType!.Value); + writer.WriteString("budget_planning_type", budgetPlanningTypeRawValue); + } + if (taskReduced.LocationInheritedOption.IsSet) + writer.WriteBoolean("location_inherited", taskReduced.LocationInheritedOption.Value!.Value); + + if (taskReduced.LocationOption.IsSet) + if (taskReduced.LocationOption.Value != null) + { + writer.WritePropertyName("location"); + JsonSerializer.Serialize(writer, taskReduced.Location, jsonSerializerOptions); + } + else + writer.WriteNull("location"); + if (taskReduced.LocationRestrictionRadiusMetersOption.IsSet) + if (taskReduced.LocationRestrictionRadiusMetersOption.Value != null) + writer.WriteNumber("location_restriction_radius_meters", taskReduced.LocationRestrictionRadiusMetersOption.Value!.Value); + else + writer.WriteNull("location_restriction_radius_meters"); + + if (taskReduced.CustomField1 != null) + writer.WriteString("custom_field_1", taskReduced.CustomField1); + else + writer.WriteNull("custom_field_1"); + + if (taskReduced.CustomField2 != null) + writer.WriteString("custom_field_2", taskReduced.CustomField2); + else + writer.WriteNull("custom_field_2"); + + if (taskReduced.CustomField3 != null) + writer.WriteString("custom_field_3", taskReduced.CustomField3); + else + writer.WriteNull("custom_field_3"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToLeaderAssignment.cs b/sdk/dotnet/Timr.Api/Model/TaskToLeaderAssignment.cs new file mode 100644 index 0000000..7394ae4 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToLeaderAssignment.cs @@ -0,0 +1,185 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskToLeaderAssignment + /// + public partial class TaskToLeaderAssignment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// user + /// automaticallyAssigned + [JsonConstructor] + public TaskToLeaderAssignment(UserPartial user, bool automaticallyAssigned) + { + User = user; + AutomaticallyAssigned = automaticallyAssigned; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets User + /// + [JsonPropertyName("user")] + public UserPartial User { get; set; } + + /// + /// Gets or Sets AutomaticallyAssigned + /// + [JsonPropertyName("automatically_assigned")] + public bool AutomaticallyAssigned { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskToLeaderAssignment {\n"); + sb.Append(" User: ").Append(User).Append("\n"); + sb.Append(" AutomaticallyAssigned: ").Append(AutomaticallyAssigned).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskToLeaderAssignmentJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskToLeaderAssignment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option user = default; + Option automaticallyAssigned = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "user": + user = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "automatically_assigned": + automaticallyAssigned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!user.IsSet) + throw new ArgumentException("Property is required for class TaskToLeaderAssignment.", nameof(user)); + + if (!automaticallyAssigned.IsSet) + throw new ArgumentException("Property is required for class TaskToLeaderAssignment.", nameof(automaticallyAssigned)); + + if (user.IsSet && user.Value == null) + throw new ArgumentNullException(nameof(user), "Property is not nullable for class TaskToLeaderAssignment."); + + if (automaticallyAssigned.IsSet && automaticallyAssigned.Value == null) + throw new ArgumentNullException(nameof(automaticallyAssigned), "Property is not nullable for class TaskToLeaderAssignment."); + + return new TaskToLeaderAssignment(user.Value!, automaticallyAssigned.Value!.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToLeaderAssignment taskToLeaderAssignment, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskToLeaderAssignment, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskToLeaderAssignment taskToLeaderAssignment, JsonSerializerOptions jsonSerializerOptions) + { + if (taskToLeaderAssignment.User == null) + throw new ArgumentNullException(nameof(taskToLeaderAssignment.User), "Property is required for class TaskToLeaderAssignment."); + + writer.WritePropertyName("user"); + JsonSerializer.Serialize(writer, taskToLeaderAssignment.User, jsonSerializerOptions); + writer.WriteBoolean("automatically_assigned", taskToLeaderAssignment.AutomaticallyAssigned); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToLeaderAssignmentsPage.cs b/sdk/dotnet/Timr.Api/Model/TaskToLeaderAssignmentsPage.cs new file mode 100644 index 0000000..7c6e3a3 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToLeaderAssignmentsPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskToLeaderAssignmentsPage + /// + public partial class TaskToLeaderAssignmentsPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public TaskToLeaderAssignmentsPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskToLeaderAssignmentsPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskToLeaderAssignmentsPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskToLeaderAssignmentsPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TaskToLeaderAssignmentsPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class TaskToLeaderAssignmentsPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class TaskToLeaderAssignmentsPage."); + + return new TaskToLeaderAssignmentsPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToLeaderAssignmentsPage taskToLeaderAssignmentsPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskToLeaderAssignmentsPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskToLeaderAssignmentsPage taskToLeaderAssignmentsPage, JsonSerializerOptions jsonSerializerOptions) + { + if (taskToLeaderAssignmentsPage.Data == null) + throw new ArgumentNullException(nameof(taskToLeaderAssignmentsPage.Data), "Property is required for class TaskToLeaderAssignmentsPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, taskToLeaderAssignmentsPage.Data, jsonSerializerOptions); + if (taskToLeaderAssignmentsPage.NextPageToken != null) + writer.WriteString("next_page_token", taskToLeaderAssignmentsPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToLeaderAssignmentsSortColumn.cs b/sdk/dotnet/Timr.Api/Model/TaskToLeaderAssignmentsSortColumn.cs new file mode 100644 index 0000000..b9ad44d --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToLeaderAssignmentsSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Task to Leader Assignments. `user_name` orders by the assigned User's last name, then first name. + /// + /// Sort property for Task to Leader Assignments. `user_name` orders by the assigned User's last name, then first name. + public enum TaskToLeaderAssignmentsSortColumn + { + /// + /// Enum UserName for value: user_name + /// + UserName = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class TaskToLeaderAssignmentsSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static TaskToLeaderAssignmentsSortColumn FromString(string value) + { + if (value.Equals("user_name")) + return TaskToLeaderAssignmentsSortColumn.UserName; + + throw new NotImplementedException($"Could not convert value to type TaskToLeaderAssignmentsSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static TaskToLeaderAssignmentsSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("user_name")) + return TaskToLeaderAssignmentsSortColumn.UserName; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(TaskToLeaderAssignmentsSortColumn value) + { + if (value == TaskToLeaderAssignmentsSortColumn.UserName) + return "user_name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class TaskToLeaderAssignmentsSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override TaskToLeaderAssignmentsSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TaskToLeaderAssignmentsSortColumn? result = rawValue == null + ? null + : TaskToLeaderAssignmentsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TaskToLeaderAssignmentsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToLeaderAssignmentsSortColumn taskToLeaderAssignmentsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(TaskToLeaderAssignmentsSortColumnValueConverter.ToJsonValue(taskToLeaderAssignmentsSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class TaskToLeaderAssignmentsSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a TaskToLeaderAssignmentsSortColumn from the Json object + /// + /// + /// + /// + /// + public override TaskToLeaderAssignmentsSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TaskToLeaderAssignmentsSortColumn? result = rawValue == null + ? null + : TaskToLeaderAssignmentsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TaskToLeaderAssignmentsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToLeaderAssignmentsSortColumn? taskToLeaderAssignmentsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(taskToLeaderAssignmentsSortColumn.HasValue ? TaskToLeaderAssignmentsSortColumnValueConverter.ToJsonValue(taskToLeaderAssignmentsSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToTeamAssignment.cs b/sdk/dotnet/Timr.Api/Model/TaskToTeamAssignment.cs new file mode 100644 index 0000000..0fbb463 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToTeamAssignment.cs @@ -0,0 +1,185 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskToTeamAssignment + /// + public partial class TaskToTeamAssignment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// team + /// automaticallyAssigned + [JsonConstructor] + public TaskToTeamAssignment(TeamPartial team, bool automaticallyAssigned) + { + Team = team; + AutomaticallyAssigned = automaticallyAssigned; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Team + /// + [JsonPropertyName("team")] + public TeamPartial Team { get; set; } + + /// + /// Gets or Sets AutomaticallyAssigned + /// + [JsonPropertyName("automatically_assigned")] + public bool AutomaticallyAssigned { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskToTeamAssignment {\n"); + sb.Append(" Team: ").Append(Team).Append("\n"); + sb.Append(" AutomaticallyAssigned: ").Append(AutomaticallyAssigned).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskToTeamAssignmentJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskToTeamAssignment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option team = default; + Option automaticallyAssigned = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "team": + team = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "automatically_assigned": + automaticallyAssigned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!team.IsSet) + throw new ArgumentException("Property is required for class TaskToTeamAssignment.", nameof(team)); + + if (!automaticallyAssigned.IsSet) + throw new ArgumentException("Property is required for class TaskToTeamAssignment.", nameof(automaticallyAssigned)); + + if (team.IsSet && team.Value == null) + throw new ArgumentNullException(nameof(team), "Property is not nullable for class TaskToTeamAssignment."); + + if (automaticallyAssigned.IsSet && automaticallyAssigned.Value == null) + throw new ArgumentNullException(nameof(automaticallyAssigned), "Property is not nullable for class TaskToTeamAssignment."); + + return new TaskToTeamAssignment(team.Value!, automaticallyAssigned.Value!.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToTeamAssignment taskToTeamAssignment, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskToTeamAssignment, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskToTeamAssignment taskToTeamAssignment, JsonSerializerOptions jsonSerializerOptions) + { + if (taskToTeamAssignment.Team == null) + throw new ArgumentNullException(nameof(taskToTeamAssignment.Team), "Property is required for class TaskToTeamAssignment."); + + writer.WritePropertyName("team"); + JsonSerializer.Serialize(writer, taskToTeamAssignment.Team, jsonSerializerOptions); + writer.WriteBoolean("automatically_assigned", taskToTeamAssignment.AutomaticallyAssigned); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToTeamAssignmentsPage.cs b/sdk/dotnet/Timr.Api/Model/TaskToTeamAssignmentsPage.cs new file mode 100644 index 0000000..5e5876e --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToTeamAssignmentsPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskToTeamAssignmentsPage + /// + public partial class TaskToTeamAssignmentsPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public TaskToTeamAssignmentsPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskToTeamAssignmentsPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskToTeamAssignmentsPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskToTeamAssignmentsPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TaskToTeamAssignmentsPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class TaskToTeamAssignmentsPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class TaskToTeamAssignmentsPage."); + + return new TaskToTeamAssignmentsPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToTeamAssignmentsPage taskToTeamAssignmentsPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskToTeamAssignmentsPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskToTeamAssignmentsPage taskToTeamAssignmentsPage, JsonSerializerOptions jsonSerializerOptions) + { + if (taskToTeamAssignmentsPage.Data == null) + throw new ArgumentNullException(nameof(taskToTeamAssignmentsPage.Data), "Property is required for class TaskToTeamAssignmentsPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, taskToTeamAssignmentsPage.Data, jsonSerializerOptions); + if (taskToTeamAssignmentsPage.NextPageToken != null) + writer.WriteString("next_page_token", taskToTeamAssignmentsPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToTeamAssignmentsSortColumn.cs b/sdk/dotnet/Timr.Api/Model/TaskToTeamAssignmentsSortColumn.cs new file mode 100644 index 0000000..016602c --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToTeamAssignmentsSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Task to Team Assignments. `team_name` orders by the assigned Team's name. + /// + /// Sort property for Task to Team Assignments. `team_name` orders by the assigned Team's name. + public enum TaskToTeamAssignmentsSortColumn + { + /// + /// Enum TeamName for value: team_name + /// + TeamName = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class TaskToTeamAssignmentsSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static TaskToTeamAssignmentsSortColumn FromString(string value) + { + if (value.Equals("team_name")) + return TaskToTeamAssignmentsSortColumn.TeamName; + + throw new NotImplementedException($"Could not convert value to type TaskToTeamAssignmentsSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static TaskToTeamAssignmentsSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("team_name")) + return TaskToTeamAssignmentsSortColumn.TeamName; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(TaskToTeamAssignmentsSortColumn value) + { + if (value == TaskToTeamAssignmentsSortColumn.TeamName) + return "team_name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class TaskToTeamAssignmentsSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override TaskToTeamAssignmentsSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TaskToTeamAssignmentsSortColumn? result = rawValue == null + ? null + : TaskToTeamAssignmentsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TaskToTeamAssignmentsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToTeamAssignmentsSortColumn taskToTeamAssignmentsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(TaskToTeamAssignmentsSortColumnValueConverter.ToJsonValue(taskToTeamAssignmentsSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class TaskToTeamAssignmentsSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a TaskToTeamAssignmentsSortColumn from the Json object + /// + /// + /// + /// + /// + public override TaskToTeamAssignmentsSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TaskToTeamAssignmentsSortColumn? result = rawValue == null + ? null + : TaskToTeamAssignmentsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TaskToTeamAssignmentsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToTeamAssignmentsSortColumn? taskToTeamAssignmentsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(taskToTeamAssignmentsSortColumn.HasValue ? TaskToTeamAssignmentsSortColumnValueConverter.ToJsonValue(taskToTeamAssignmentsSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToUserAssignment.cs b/sdk/dotnet/Timr.Api/Model/TaskToUserAssignment.cs new file mode 100644 index 0000000..fdcf694 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToUserAssignment.cs @@ -0,0 +1,235 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskToUserAssignment + /// + public partial class TaskToUserAssignment : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// user + /// recordingLock + /// automaticallyAssigned + /// hoursPlanned + [JsonConstructor] + public TaskToUserAssignment(UserPartial user, RecordingLockType recordingLock, bool automaticallyAssigned, Option hoursPlanned = default) + { + User = user; + RecordingLock = recordingLock; + AutomaticallyAssigned = automaticallyAssigned; + HoursPlannedOption = hoursPlanned; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets RecordingLock + /// + [JsonPropertyName("recording_lock")] + public RecordingLockType RecordingLock { get; set; } + + /// + /// Gets or Sets User + /// + [JsonPropertyName("user")] + public UserPartial User { get; set; } + + /// + /// Gets or Sets AutomaticallyAssigned + /// + [JsonPropertyName("automatically_assigned")] + public bool AutomaticallyAssigned { get; set; } + + /// + /// Used to track the state of HoursPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option HoursPlannedOption { get; private set; } + + /// + /// Gets or Sets HoursPlanned + /// + [JsonPropertyName("hours_planned")] + public decimal? HoursPlanned { get { return this.HoursPlannedOption.Value; } set { this.HoursPlannedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskToUserAssignment {\n"); + sb.Append(" User: ").Append(User).Append("\n"); + sb.Append(" RecordingLock: ").Append(RecordingLock).Append("\n"); + sb.Append(" AutomaticallyAssigned: ").Append(AutomaticallyAssigned).Append("\n"); + sb.Append(" HoursPlanned: ").Append(HoursPlanned).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskToUserAssignmentJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskToUserAssignment Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option user = default; + Option recordingLock = default; + Option automaticallyAssigned = default; + Option hoursPlanned = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "user": + user = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "recording_lock": + string? recordingLockRawValue = utf8JsonReader.GetString(); + if (recordingLockRawValue != null) + recordingLock = new Option(RecordingLockTypeValueConverter.FromStringOrDefault(recordingLockRawValue)); + break; + case "automatically_assigned": + automaticallyAssigned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "hours_planned": + hoursPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + default: + break; + } + } + } + + if (!user.IsSet) + throw new ArgumentException("Property is required for class TaskToUserAssignment.", nameof(user)); + + if (!recordingLock.IsSet) + throw new ArgumentException("Property is required for class TaskToUserAssignment.", nameof(recordingLock)); + + if (!automaticallyAssigned.IsSet) + throw new ArgumentException("Property is required for class TaskToUserAssignment.", nameof(automaticallyAssigned)); + + if (user.IsSet && user.Value == null) + throw new ArgumentNullException(nameof(user), "Property is not nullable for class TaskToUserAssignment."); + + if (recordingLock.IsSet && recordingLock.Value == null) + throw new ArgumentNullException(nameof(recordingLock), "Property is not nullable for class TaskToUserAssignment."); + + if (automaticallyAssigned.IsSet && automaticallyAssigned.Value == null) + throw new ArgumentNullException(nameof(automaticallyAssigned), "Property is not nullable for class TaskToUserAssignment."); + + return new TaskToUserAssignment(user.Value!, recordingLock.Value!.Value!, automaticallyAssigned.Value!.Value!, hoursPlanned); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToUserAssignment taskToUserAssignment, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskToUserAssignment, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskToUserAssignment taskToUserAssignment, JsonSerializerOptions jsonSerializerOptions) + { + if (taskToUserAssignment.User == null) + throw new ArgumentNullException(nameof(taskToUserAssignment.User), "Property is required for class TaskToUserAssignment."); + + writer.WritePropertyName("user"); + JsonSerializer.Serialize(writer, taskToUserAssignment.User, jsonSerializerOptions); + var recordingLockRawValue = RecordingLockTypeValueConverter.ToJsonValue(taskToUserAssignment.RecordingLock); + writer.WriteString("recording_lock", recordingLockRawValue); + + writer.WriteBoolean("automatically_assigned", taskToUserAssignment.AutomaticallyAssigned); + + if (taskToUserAssignment.HoursPlannedOption.IsSet) + if (taskToUserAssignment.HoursPlannedOption.Value != null) + writer.WriteNumber("hours_planned", taskToUserAssignment.HoursPlannedOption.Value!.Value); + else + writer.WriteNull("hours_planned"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToUserAssignmentUpsert.cs b/sdk/dotnet/Timr.Api/Model/TaskToUserAssignmentUpsert.cs new file mode 100644 index 0000000..b548bc6 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToUserAssignmentUpsert.cs @@ -0,0 +1,196 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskToUserAssignmentUpsert + /// + public partial class TaskToUserAssignmentUpsert : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// hoursPlanned + /// recordingLock + [JsonConstructor] + public TaskToUserAssignmentUpsert(Option hoursPlanned = default, Option recordingLock = default) + { + HoursPlannedOption = hoursPlanned; + RecordingLockOption = recordingLock; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of RecordingLock + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option RecordingLockOption { get; private set; } + + /// + /// Gets or Sets RecordingLock + /// + [JsonPropertyName("recording_lock")] + public RecordingLockType? RecordingLock { get { return this.RecordingLockOption.Value; } set { this.RecordingLockOption = new(value); } } + + /// + /// Used to track the state of HoursPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option HoursPlannedOption { get; private set; } + + /// + /// Gets or Sets HoursPlanned + /// + [JsonPropertyName("hours_planned")] + public decimal? HoursPlanned { get { return this.HoursPlannedOption.Value; } set { this.HoursPlannedOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskToUserAssignmentUpsert {\n"); + sb.Append(" HoursPlanned: ").Append(HoursPlanned).Append("\n"); + sb.Append(" RecordingLock: ").Append(RecordingLock).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskToUserAssignmentUpsertJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskToUserAssignmentUpsert Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option hoursPlanned = default; + Option recordingLock = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "hours_planned": + hoursPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "recording_lock": + string? recordingLockRawValue = utf8JsonReader.GetString(); + recordingLock = new Option(recordingLockRawValue == null ? null : RecordingLockTypeValueConverter.FromStringOrDefault(recordingLockRawValue)); + break; + default: + break; + } + } + } + + return new TaskToUserAssignmentUpsert(hoursPlanned, recordingLock); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskToUserAssignmentUpsert, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert, JsonSerializerOptions jsonSerializerOptions) + { + if (taskToUserAssignmentUpsert.HoursPlannedOption.IsSet) + if (taskToUserAssignmentUpsert.HoursPlannedOption.Value != null) + writer.WriteNumber("hours_planned", taskToUserAssignmentUpsert.HoursPlannedOption.Value!.Value); + else + writer.WriteNull("hours_planned"); + + if (taskToUserAssignmentUpsert.RecordingLockOption.IsSet) + if (taskToUserAssignmentUpsert.RecordingLockOption!.Value != null) + { + var recordingLockRawValue = RecordingLockTypeValueConverter.ToJsonValue(taskToUserAssignmentUpsert.RecordingLockOption.Value!.Value); + writer.WriteString("recording_lock", recordingLockRawValue); + } + else + writer.WriteNull("recording_lock"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToUserAssignmentsPage.cs b/sdk/dotnet/Timr.Api/Model/TaskToUserAssignmentsPage.cs new file mode 100644 index 0000000..2ca2815 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToUserAssignmentsPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskToUserAssignmentsPage + /// + public partial class TaskToUserAssignmentsPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public TaskToUserAssignmentsPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskToUserAssignmentsPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskToUserAssignmentsPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskToUserAssignmentsPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TaskToUserAssignmentsPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class TaskToUserAssignmentsPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class TaskToUserAssignmentsPage."); + + return new TaskToUserAssignmentsPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToUserAssignmentsPage taskToUserAssignmentsPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskToUserAssignmentsPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskToUserAssignmentsPage taskToUserAssignmentsPage, JsonSerializerOptions jsonSerializerOptions) + { + if (taskToUserAssignmentsPage.Data == null) + throw new ArgumentNullException(nameof(taskToUserAssignmentsPage.Data), "Property is required for class TaskToUserAssignmentsPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, taskToUserAssignmentsPage.Data, jsonSerializerOptions); + if (taskToUserAssignmentsPage.NextPageToken != null) + writer.WriteString("next_page_token", taskToUserAssignmentsPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskToUserAssignmentsSortColumn.cs b/sdk/dotnet/Timr.Api/Model/TaskToUserAssignmentsSortColumn.cs new file mode 100644 index 0000000..6e209c3 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskToUserAssignmentsSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Task to User Assignments. `user_name` orders by the assigned User's last name, then first name. + /// + /// Sort property for Task to User Assignments. `user_name` orders by the assigned User's last name, then first name. + public enum TaskToUserAssignmentsSortColumn + { + /// + /// Enum UserName for value: user_name + /// + UserName = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class TaskToUserAssignmentsSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static TaskToUserAssignmentsSortColumn FromString(string value) + { + if (value.Equals("user_name")) + return TaskToUserAssignmentsSortColumn.UserName; + + throw new NotImplementedException($"Could not convert value to type TaskToUserAssignmentsSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static TaskToUserAssignmentsSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("user_name")) + return TaskToUserAssignmentsSortColumn.UserName; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(TaskToUserAssignmentsSortColumn value) + { + if (value == TaskToUserAssignmentsSortColumn.UserName) + return "user_name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class TaskToUserAssignmentsSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override TaskToUserAssignmentsSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TaskToUserAssignmentsSortColumn? result = rawValue == null + ? null + : TaskToUserAssignmentsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TaskToUserAssignmentsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToUserAssignmentsSortColumn taskToUserAssignmentsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(TaskToUserAssignmentsSortColumnValueConverter.ToJsonValue(taskToUserAssignmentsSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class TaskToUserAssignmentsSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a TaskToUserAssignmentsSortColumn from the Json object + /// + /// + /// + /// + /// + public override TaskToUserAssignmentsSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TaskToUserAssignmentsSortColumn? result = rawValue == null + ? null + : TaskToUserAssignmentsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TaskToUserAssignmentsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskToUserAssignmentsSortColumn? taskToUserAssignmentsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(taskToUserAssignmentsSortColumn.HasValue ? TaskToUserAssignmentsSortColumnValueConverter.ToJsonValue(taskToUserAssignmentsSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TaskUpdate.cs b/sdk/dotnet/Timr.Api/Model/TaskUpdate.cs new file mode 100644 index 0000000..ac662d2 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TaskUpdate.cs @@ -0,0 +1,864 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TaskUpdate + /// + public partial class TaskUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + /// returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// description + /// descriptionExternal + /// when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + /// billable + /// depending on this property project times booked on this task have to include notes or not + /// the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + /// set this property to limit the task so that it cannot be booked before this time + /// set this property to limit the task so that it cannot be booked after this time + /// when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + /// how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + /// the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// set this property to true, if you want to include not billable hours for all project times booked on this task + /// set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + /// location + /// set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// metadata + /// this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. + [JsonConstructor] + public TaskUpdate(Option name = default, Option parentTaskId = default, Option externalId = default, Option description = default, Option descriptionExternal = default, Option bookable = default, Option billable = default, Option projectTimeNotesRequired = default, Option startDate = default, Option endDate = default, Option lockDate = default, Option earliestStartTime = default, Option latestEndTime = default, Option budgetPlanningType = default, Option budgetHoursPlanned = default, Option budgetHourlyRate = default, Option budgetPlanned = default, Option budgetIncludeNonBillableProjectTimes = default, Option locationInherited = default, Option location = default, Option locationRestrictionRadiusMeters = default, Option customField1 = default, Option customField2 = default, Option customField3 = default, Option?> metadata = default, Option budgetUpdateProjectTimes = default) + { + NameOption = name; + ParentTaskIdOption = parentTaskId; + ExternalIdOption = externalId; + DescriptionOption = description; + DescriptionExternalOption = descriptionExternal; + BookableOption = bookable; + BillableOption = billable; + ProjectTimeNotesRequiredOption = projectTimeNotesRequired; + StartDateOption = startDate; + EndDateOption = endDate; + LockDateOption = lockDate; + EarliestStartTimeOption = earliestStartTime; + LatestEndTimeOption = latestEndTime; + BudgetPlanningTypeOption = budgetPlanningType; + BudgetHoursPlannedOption = budgetHoursPlanned; + BudgetHourlyRateOption = budgetHourlyRate; + BudgetPlannedOption = budgetPlanned; + BudgetIncludeNonBillableProjectTimesOption = budgetIncludeNonBillableProjectTimes; + LocationInheritedOption = locationInherited; + LocationOption = location; + LocationRestrictionRadiusMetersOption = locationRestrictionRadiusMeters; + CustomField1Option = customField1; + CustomField2Option = customField2; + CustomField3Option = customField3; + MetadataOption = metadata; + BudgetUpdateProjectTimesOption = budgetUpdateProjectTimes; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of BudgetPlanningType + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetPlanningTypeOption { get; private set; } + + /// + /// when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + /// + /// when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + [JsonPropertyName("budget_planning_type")] + public BudgetPlanningTypeRequest? BudgetPlanningType { get { return this.BudgetPlanningTypeOption.Value; } set { this.BudgetPlanningTypeOption = new(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string? Name { get { return this.NameOption.Value; } set { this.NameOption = new(value); } } + + /// + /// Used to track the state of ParentTaskId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ParentTaskIdOption { get; private set; } + + /// + /// returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + /// + /// returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + [JsonPropertyName("parent_task_id")] + public string? ParentTaskId { get { return this.ParentTaskIdOption.Value; } set { this.ParentTaskIdOption = new(value); } } + + /// + /// Used to track the state of ExternalId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ExternalIdOption { get; private set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get { return this.ExternalIdOption.Value; } set { this.ExternalIdOption = new(value); } } + + /// + /// Used to track the state of Description + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DescriptionOption { get; private set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string? Description { get { return this.DescriptionOption.Value; } set { this.DescriptionOption = new(value); } } + + /// + /// Used to track the state of DescriptionExternal + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DescriptionExternalOption { get; private set; } + + /// + /// Gets or Sets DescriptionExternal + /// + [JsonPropertyName("description_external")] + public string? DescriptionExternal { get { return this.DescriptionExternalOption.Value; } set { this.DescriptionExternalOption = new(value); } } + + /// + /// Used to track the state of Bookable + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BookableOption { get; private set; } + + /// + /// when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + /// + /// when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + [JsonPropertyName("bookable")] + public bool? Bookable { get { return this.BookableOption.Value; } set { this.BookableOption = new(value); } } + + /// + /// Used to track the state of Billable + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BillableOption { get; private set; } + + /// + /// Gets or Sets Billable + /// + [JsonPropertyName("billable")] + public bool? Billable { get { return this.BillableOption.Value; } set { this.BillableOption = new(value); } } + + /// + /// Used to track the state of ProjectTimeNotesRequired + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ProjectTimeNotesRequiredOption { get; private set; } + + /// + /// depending on this property project times booked on this task have to include notes or not + /// + /// depending on this property project times booked on this task have to include notes or not + [JsonPropertyName("project_time_notes_required")] + public bool? ProjectTimeNotesRequired { get { return this.ProjectTimeNotesRequiredOption.Value; } set { this.ProjectTimeNotesRequiredOption = new(value); } } + + /// + /// Used to track the state of StartDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartDateOption { get; private set; } + + /// + /// the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// + /// the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + [JsonPropertyName("start_date")] + public DateOnly? StartDate { get { return this.StartDateOption.Value; } set { this.StartDateOption = new(value); } } + + /// + /// Used to track the state of EndDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndDateOption { get; private set; } + + /// + /// the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + /// + /// the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + [JsonPropertyName("end_date")] + public DateOnly? EndDate { get { return this.EndDateOption.Value; } set { this.EndDateOption = new(value); } } + + /// + /// Used to track the state of LockDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LockDateOption { get; private set; } + + /// + /// with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + /// + /// with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + [JsonPropertyName("lock_date")] + public DateOnly? LockDate { get { return this.LockDateOption.Value; } set { this.LockDateOption = new(value); } } + + /// + /// Used to track the state of EarliestStartTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EarliestStartTimeOption { get; private set; } + + /// + /// set this property to limit the task so that it cannot be booked before this time + /// + /// set this property to limit the task so that it cannot be booked before this time + /* 920 */ + [JsonPropertyName("earliest_start_time")] + public string? EarliestStartTime { get { return this.EarliestStartTimeOption.Value; } set { this.EarliestStartTimeOption = new(value); } } + + /// + /// Used to track the state of LatestEndTime + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LatestEndTimeOption { get; private set; } + + /// + /// set this property to limit the task so that it cannot be booked after this time + /// + /// set this property to limit the task so that it cannot be booked after this time + /* 920 */ + [JsonPropertyName("latest_end_time")] + public string? LatestEndTime { get { return this.LatestEndTimeOption.Value; } set { this.LatestEndTimeOption = new(value); } } + + /// + /// Used to track the state of BudgetHoursPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetHoursPlannedOption { get; private set; } + + /// + /// how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// + /// how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + [JsonPropertyName("budget_hours_planned")] + public decimal? BudgetHoursPlanned { get { return this.BudgetHoursPlannedOption.Value; } set { this.BudgetHoursPlannedOption = new(value); } } + + /// + /// Used to track the state of BudgetHourlyRate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetHourlyRateOption { get; private set; } + + /// + /// depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + /// + /// depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + [JsonPropertyName("budget_hourly_rate")] + public decimal? BudgetHourlyRate { get { return this.BudgetHourlyRateOption.Value; } set { this.BudgetHourlyRateOption = new(value); } } + + /// + /// Used to track the state of BudgetPlanned + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetPlannedOption { get; private set; } + + /// + /// the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + /// + /// the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + [JsonPropertyName("budget_planned")] + public decimal? BudgetPlanned { get { return this.BudgetPlannedOption.Value; } set { this.BudgetPlannedOption = new(value); } } + + /// + /// Used to track the state of BudgetIncludeNonBillableProjectTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetIncludeNonBillableProjectTimesOption { get; private set; } + + /// + /// set this property to true, if you want to include not billable hours for all project times booked on this task + /// + /// set this property to true, if you want to include not billable hours for all project times booked on this task + [JsonPropertyName("budget_include_non_billable_project_times")] + public bool? BudgetIncludeNonBillableProjectTimes { get { return this.BudgetIncludeNonBillableProjectTimesOption.Value; } set { this.BudgetIncludeNonBillableProjectTimesOption = new(value); } } + + /// + /// Used to track the state of LocationInherited + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationInheritedOption { get; private set; } + + /// + /// set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + /// + /// set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + [JsonPropertyName("location_inherited")] + public bool? LocationInherited { get { return this.LocationInheritedOption.Value; } set { this.LocationInheritedOption = new(value); } } + + /// + /// Used to track the state of Location + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationOption { get; private set; } + + /// + /// Gets or Sets Location + /// + [JsonPropertyName("location")] + public TaskLocation? Location { get { return this.LocationOption.Value; } set { this.LocationOption = new(value); } } + + /// + /// Used to track the state of LocationRestrictionRadiusMeters + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LocationRestrictionRadiusMetersOption { get; private set; } + + /// + /// set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + /// + /// set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + [JsonPropertyName("location_restriction_radius_meters")] + public int? LocationRestrictionRadiusMeters { get { return this.LocationRestrictionRadiusMetersOption.Value; } set { this.LocationRestrictionRadiusMetersOption = new(value); } } + + /// + /// Used to track the state of CustomField1 + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option CustomField1Option { get; private set; } + + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + [JsonPropertyName("custom_field_1")] + public string? CustomField1 { get { return this.CustomField1Option.Value; } set { this.CustomField1Option = new(value); } } + + /// + /// Used to track the state of CustomField2 + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option CustomField2Option { get; private set; } + + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + [JsonPropertyName("custom_field_2")] + public string? CustomField2 { get { return this.CustomField2Option.Value; } set { this.CustomField2Option = new(value); } } + + /// + /// Used to track the state of CustomField3 + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option CustomField3Option { get; private set; } + + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + /// + /// you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + [JsonPropertyName("custom_field_3")] + public string? CustomField3 { get { return this.CustomField3Option.Value; } set { this.CustomField3Option = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Used to track the state of BudgetUpdateProjectTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BudgetUpdateProjectTimesOption { get; private set; } + + /// + /// this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. + /// + /// this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. + [JsonPropertyName("budget_update_project_times")] + public bool? BudgetUpdateProjectTimes { get { return this.BudgetUpdateProjectTimesOption.Value; } set { this.BudgetUpdateProjectTimesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TaskUpdate {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" ParentTaskId: ").Append(ParentTaskId).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" DescriptionExternal: ").Append(DescriptionExternal).Append("\n"); + sb.Append(" Bookable: ").Append(Bookable).Append("\n"); + sb.Append(" Billable: ").Append(Billable).Append("\n"); + sb.Append(" ProjectTimeNotesRequired: ").Append(ProjectTimeNotesRequired).Append("\n"); + sb.Append(" StartDate: ").Append(StartDate).Append("\n"); + sb.Append(" EndDate: ").Append(EndDate).Append("\n"); + sb.Append(" LockDate: ").Append(LockDate).Append("\n"); + sb.Append(" EarliestStartTime: ").Append(EarliestStartTime).Append("\n"); + sb.Append(" LatestEndTime: ").Append(LatestEndTime).Append("\n"); + sb.Append(" BudgetPlanningType: ").Append(BudgetPlanningType).Append("\n"); + sb.Append(" BudgetHoursPlanned: ").Append(BudgetHoursPlanned).Append("\n"); + sb.Append(" BudgetHourlyRate: ").Append(BudgetHourlyRate).Append("\n"); + sb.Append(" BudgetPlanned: ").Append(BudgetPlanned).Append("\n"); + sb.Append(" BudgetIncludeNonBillableProjectTimes: ").Append(BudgetIncludeNonBillableProjectTimes).Append("\n"); + sb.Append(" LocationInherited: ").Append(LocationInherited).Append("\n"); + sb.Append(" Location: ").Append(Location).Append("\n"); + sb.Append(" LocationRestrictionRadiusMeters: ").Append(LocationRestrictionRadiusMeters).Append("\n"); + sb.Append(" CustomField1: ").Append(CustomField1).Append("\n"); + sb.Append(" CustomField2: ").Append(CustomField2).Append("\n"); + sb.Append(" CustomField3: ").Append(CustomField3).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" BudgetUpdateProjectTimes: ").Append(BudgetUpdateProjectTimes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TaskUpdateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize StartDate + /// + public static string StartDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize EndDate + /// + public static string EndDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize LockDate + /// + public static string LockDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TaskUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option parentTaskId = default; + Option externalId = default; + Option description = default; + Option descriptionExternal = default; + Option bookable = default; + Option billable = default; + Option projectTimeNotesRequired = default; + Option startDate = default; + Option endDate = default; + Option lockDate = default; + Option earliestStartTime = default; + Option latestEndTime = default; + Option budgetPlanningType = default; + Option budgetHoursPlanned = default; + Option budgetHourlyRate = default; + Option budgetPlanned = default; + Option budgetIncludeNonBillableProjectTimes = default; + Option locationInherited = default; + Option location = default; + Option locationRestrictionRadiusMeters = default; + Option customField1 = default; + Option customField2 = default; + Option customField3 = default; + Option?> metadata = default; + Option budgetUpdateProjectTimes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "parent_task_id": + parentTaskId = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "description": + description = new Option(utf8JsonReader.GetString()); + break; + case "description_external": + descriptionExternal = new Option(utf8JsonReader.GetString()); + break; + case "bookable": + bookable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "billable": + billable = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "project_time_notes_required": + projectTimeNotesRequired = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "start_date": + startDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_date": + endDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "lock_date": + lockDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "earliest_start_time": + earliestStartTime = new Option(utf8JsonReader.GetString()); + break; + case "latest_end_time": + latestEndTime = new Option(utf8JsonReader.GetString()); + break; + case "budget_planning_type": + string? budgetPlanningTypeRawValue = utf8JsonReader.GetString(); + if (budgetPlanningTypeRawValue != null) + budgetPlanningType = new Option(BudgetPlanningTypeRequestValueConverter.FromStringOrDefault(budgetPlanningTypeRawValue)); + break; + case "budget_hours_planned": + budgetHoursPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_hourly_rate": + budgetHourlyRate = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_planned": + budgetPlanned = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "budget_include_non_billable_project_times": + budgetIncludeNonBillableProjectTimes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "location_inherited": + locationInherited = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "location": + location = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "location_restriction_radius_meters": + locationRestrictionRadiusMeters = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "custom_field_1": + customField1 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_2": + customField2 = new Option(utf8JsonReader.GetString()); + break; + case "custom_field_3": + customField3 = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "budget_update_project_times": + budgetUpdateProjectTimes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class TaskUpdate."); + + if (bookable.IsSet && bookable.Value == null) + throw new ArgumentNullException(nameof(bookable), "Property is not nullable for class TaskUpdate."); + + if (billable.IsSet && billable.Value == null) + throw new ArgumentNullException(nameof(billable), "Property is not nullable for class TaskUpdate."); + + if (projectTimeNotesRequired.IsSet && projectTimeNotesRequired.Value == null) + throw new ArgumentNullException(nameof(projectTimeNotesRequired), "Property is not nullable for class TaskUpdate."); + + if (budgetPlanningType.IsSet && budgetPlanningType.Value == null) + throw new ArgumentNullException(nameof(budgetPlanningType), "Property is not nullable for class TaskUpdate."); + + if (budgetIncludeNonBillableProjectTimes.IsSet && budgetIncludeNonBillableProjectTimes.Value == null) + throw new ArgumentNullException(nameof(budgetIncludeNonBillableProjectTimes), "Property is not nullable for class TaskUpdate."); + + if (locationInherited.IsSet && locationInherited.Value == null) + throw new ArgumentNullException(nameof(locationInherited), "Property is not nullable for class TaskUpdate."); + + if (budgetUpdateProjectTimes.IsSet && budgetUpdateProjectTimes.Value == null) + throw new ArgumentNullException(nameof(budgetUpdateProjectTimes), "Property is not nullable for class TaskUpdate."); + + return new TaskUpdate(name, parentTaskId, externalId, description, descriptionExternal, bookable, billable, projectTimeNotesRequired, startDate, endDate, lockDate, earliestStartTime, latestEndTime, budgetPlanningType, budgetHoursPlanned, budgetHourlyRate, budgetPlanned, budgetIncludeNonBillableProjectTimes, locationInherited, location, locationRestrictionRadiusMeters, customField1, customField2, customField3, metadata, budgetUpdateProjectTimes); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TaskUpdate taskUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, taskUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TaskUpdate taskUpdate, JsonSerializerOptions jsonSerializerOptions) + { + if (taskUpdate.NameOption.IsSet && taskUpdate.Name == null) + throw new ArgumentNullException(nameof(taskUpdate.Name), "Property is required for class TaskUpdate."); + + if (taskUpdate.NameOption.IsSet) + writer.WriteString("name", taskUpdate.Name); + + if (taskUpdate.ParentTaskIdOption.IsSet) + if (taskUpdate.ParentTaskIdOption.Value != null) + writer.WriteString("parent_task_id", taskUpdate.ParentTaskId); + else + writer.WriteNull("parent_task_id"); + + if (taskUpdate.ExternalIdOption.IsSet) + if (taskUpdate.ExternalIdOption.Value != null) + writer.WriteString("external_id", taskUpdate.ExternalId); + else + writer.WriteNull("external_id"); + + if (taskUpdate.DescriptionOption.IsSet) + if (taskUpdate.DescriptionOption.Value != null) + writer.WriteString("description", taskUpdate.Description); + else + writer.WriteNull("description"); + + if (taskUpdate.DescriptionExternalOption.IsSet) + if (taskUpdate.DescriptionExternalOption.Value != null) + writer.WriteString("description_external", taskUpdate.DescriptionExternal); + else + writer.WriteNull("description_external"); + + if (taskUpdate.BookableOption.IsSet) + writer.WriteBoolean("bookable", taskUpdate.BookableOption.Value!.Value); + + if (taskUpdate.BillableOption.IsSet) + writer.WriteBoolean("billable", taskUpdate.BillableOption.Value!.Value); + + if (taskUpdate.ProjectTimeNotesRequiredOption.IsSet) + writer.WriteBoolean("project_time_notes_required", taskUpdate.ProjectTimeNotesRequiredOption.Value!.Value); + + if (taskUpdate.StartDateOption.IsSet) + if (taskUpdate.StartDateOption.Value != null) + writer.WriteString("start_date", taskUpdate.StartDateOption.Value!.Value.ToString(StartDateFormat)); + else + writer.WriteNull("start_date"); + + if (taskUpdate.EndDateOption.IsSet) + if (taskUpdate.EndDateOption.Value != null) + writer.WriteString("end_date", taskUpdate.EndDateOption.Value!.Value.ToString(EndDateFormat)); + else + writer.WriteNull("end_date"); + + if (taskUpdate.LockDateOption.IsSet) + if (taskUpdate.LockDateOption.Value != null) + writer.WriteString("lock_date", taskUpdate.LockDateOption.Value!.Value.ToString(LockDateFormat)); + else + writer.WriteNull("lock_date"); + + if (taskUpdate.EarliestStartTimeOption.IsSet) + if (taskUpdate.EarliestStartTimeOption.Value != null) + writer.WriteString("earliest_start_time", taskUpdate.EarliestStartTime); + else + writer.WriteNull("earliest_start_time"); + + if (taskUpdate.LatestEndTimeOption.IsSet) + if (taskUpdate.LatestEndTimeOption.Value != null) + writer.WriteString("latest_end_time", taskUpdate.LatestEndTime); + else + writer.WriteNull("latest_end_time"); + + if (taskUpdate.BudgetPlanningTypeOption.IsSet) + { + var budgetPlanningTypeRawValue = BudgetPlanningTypeRequestValueConverter.ToJsonValue(taskUpdate.BudgetPlanningType!.Value); + writer.WriteString("budget_planning_type", budgetPlanningTypeRawValue); + } + if (taskUpdate.BudgetHoursPlannedOption.IsSet) + if (taskUpdate.BudgetHoursPlannedOption.Value != null) + writer.WriteNumber("budget_hours_planned", taskUpdate.BudgetHoursPlannedOption.Value!.Value); + else + writer.WriteNull("budget_hours_planned"); + + if (taskUpdate.BudgetHourlyRateOption.IsSet) + if (taskUpdate.BudgetHourlyRateOption.Value != null) + writer.WriteNumber("budget_hourly_rate", taskUpdate.BudgetHourlyRateOption.Value!.Value); + else + writer.WriteNull("budget_hourly_rate"); + + if (taskUpdate.BudgetPlannedOption.IsSet) + if (taskUpdate.BudgetPlannedOption.Value != null) + writer.WriteNumber("budget_planned", taskUpdate.BudgetPlannedOption.Value!.Value); + else + writer.WriteNull("budget_planned"); + + if (taskUpdate.BudgetIncludeNonBillableProjectTimesOption.IsSet) + writer.WriteBoolean("budget_include_non_billable_project_times", taskUpdate.BudgetIncludeNonBillableProjectTimesOption.Value!.Value); + + if (taskUpdate.LocationInheritedOption.IsSet) + writer.WriteBoolean("location_inherited", taskUpdate.LocationInheritedOption.Value!.Value); + + if (taskUpdate.LocationOption.IsSet) + if (taskUpdate.LocationOption.Value != null) + { + writer.WritePropertyName("location"); + JsonSerializer.Serialize(writer, taskUpdate.Location, jsonSerializerOptions); + } + else + writer.WriteNull("location"); + if (taskUpdate.LocationRestrictionRadiusMetersOption.IsSet) + if (taskUpdate.LocationRestrictionRadiusMetersOption.Value != null) + writer.WriteNumber("location_restriction_radius_meters", taskUpdate.LocationRestrictionRadiusMetersOption.Value!.Value); + else + writer.WriteNull("location_restriction_radius_meters"); + + if (taskUpdate.CustomField1Option.IsSet) + if (taskUpdate.CustomField1Option.Value != null) + writer.WriteString("custom_field_1", taskUpdate.CustomField1); + else + writer.WriteNull("custom_field_1"); + + if (taskUpdate.CustomField2Option.IsSet) + if (taskUpdate.CustomField2Option.Value != null) + writer.WriteString("custom_field_2", taskUpdate.CustomField2); + else + writer.WriteNull("custom_field_2"); + + if (taskUpdate.CustomField3Option.IsSet) + if (taskUpdate.CustomField3Option.Value != null) + writer.WriteString("custom_field_3", taskUpdate.CustomField3); + else + writer.WriteNull("custom_field_3"); + + if (taskUpdate.MetadataOption.IsSet) + if (taskUpdate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, taskUpdate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + if (taskUpdate.BudgetUpdateProjectTimesOption.IsSet) + writer.WriteBoolean("budget_update_project_times", taskUpdate.BudgetUpdateProjectTimesOption.Value!.Value); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TasksPage.cs b/sdk/dotnet/Timr.Api/Model/TasksPage.cs new file mode 100644 index 0000000..340842f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TasksPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TasksPage + /// + public partial class TasksPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public TasksPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TasksPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TasksPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TasksPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TasksPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class TasksPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class TasksPage."); + + return new TasksPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TasksPage tasksPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, tasksPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TasksPage tasksPage, JsonSerializerOptions jsonSerializerOptions) + { + if (tasksPage.Data == null) + throw new ArgumentNullException(nameof(tasksPage.Data), "Property is required for class TasksPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, tasksPage.Data, jsonSerializerOptions); + if (tasksPage.NextPageToken != null) + writer.WriteString("next_page_token", tasksPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TasksReducedPage.cs b/sdk/dotnet/Timr.Api/Model/TasksReducedPage.cs new file mode 100644 index 0000000..a109ef4 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TasksReducedPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TasksReducedPage + /// + public partial class TasksReducedPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public TasksReducedPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TasksReducedPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TasksReducedPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TasksReducedPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TasksReducedPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class TasksReducedPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class TasksReducedPage."); + + return new TasksReducedPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TasksReducedPage tasksReducedPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, tasksReducedPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TasksReducedPage tasksReducedPage, JsonSerializerOptions jsonSerializerOptions) + { + if (tasksReducedPage.Data == null) + throw new ArgumentNullException(nameof(tasksReducedPage.Data), "Property is required for class TasksReducedPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, tasksReducedPage.Data, jsonSerializerOptions); + if (tasksReducedPage.NextPageToken != null) + writer.WriteString("next_page_token", tasksReducedPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TasksSortColumn.cs b/sdk/dotnet/Timr.Api/Model/TasksSortColumn.cs new file mode 100644 index 0000000..df01dae --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TasksSortColumn.cs @@ -0,0 +1,177 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Tasks. `breadcrumbs` orders by the Task's full path, `name` by its own name only. + /// + /// Sort property for Tasks. `breadcrumbs` orders by the Task's full path, `name` by its own name only. + public enum TasksSortColumn + { + /// + /// Enum Breadcrumbs for value: breadcrumbs + /// + Breadcrumbs = 1, + + /// + /// Enum Name for value: name + /// + Name = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class TasksSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static TasksSortColumn FromString(string value) + { + if (value.Equals("breadcrumbs")) + return TasksSortColumn.Breadcrumbs; + + if (value.Equals("name")) + return TasksSortColumn.Name; + + throw new NotImplementedException($"Could not convert value to type TasksSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static TasksSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("breadcrumbs")) + return TasksSortColumn.Breadcrumbs; + + if (value.Equals("name")) + return TasksSortColumn.Name; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(TasksSortColumn value) + { + if (value == TasksSortColumn.Breadcrumbs) + return "breadcrumbs"; + + if (value == TasksSortColumn.Name) + return "name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class TasksSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override TasksSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TasksSortColumn? result = rawValue == null + ? null + : TasksSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TasksSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TasksSortColumn tasksSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(TasksSortColumnValueConverter.ToJsonValue(tasksSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class TasksSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a TasksSortColumn from the Json object + /// + /// + /// + /// + /// + public override TasksSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TasksSortColumn? result = rawValue == null + ? null + : TasksSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TasksSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TasksSortColumn? tasksSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(tasksSortColumn.HasValue ? TasksSortColumnValueConverter.ToJsonValue(tasksSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Team.cs b/sdk/dotnet/Timr.Api/Model/Team.cs new file mode 100644 index 0000000..e03ae77 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Team.cs @@ -0,0 +1,281 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// A team, placed in the hierarchy by `parent_team`, with the full path from the root in `breadcrumbs`. + /// + public partial class Team : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// Full path of the entry within its hierarchy, including its own name. + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// description + /// parentTeam + [JsonConstructor] + public Team(string id, string name, string breadcrumbs, string? externalId = default, string? description = default, TeamPartial? parentTeam = default) + { + Id = id; + Name = name; + Breadcrumbs = breadcrumbs; + ExternalId = externalId; + Description = description; + ParentTeam = parentTeam; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Full path of the entry within its hierarchy, including its own name. + /// + /// Full path of the entry within its hierarchy, including its own name. + [JsonPropertyName("breadcrumbs")] + public string Breadcrumbs { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// Gets or Sets ParentTeam + /// + [JsonPropertyName("parent_team")] + public TeamPartial? ParentTeam { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Team {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Breadcrumbs: ").Append(Breadcrumbs).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ParentTeam: ").Append(ParentTeam).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TeamJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Team Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option breadcrumbs = default; + Option externalId = default; + Option description = default; + Option parentTeam = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "breadcrumbs": + breadcrumbs = new Option(utf8JsonReader.GetString()!); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "description": + description = new Option(utf8JsonReader.GetString()); + break; + case "parent_team": + parentTeam = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class Team.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class Team.", nameof(name)); + + if (!breadcrumbs.IsSet) + throw new ArgumentException("Property is required for class Team.", nameof(breadcrumbs)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class Team.", nameof(externalId)); + + if (!description.IsSet) + throw new ArgumentException("Property is required for class Team.", nameof(description)); + + if (!parentTeam.IsSet) + throw new ArgumentException("Property is required for class Team.", nameof(parentTeam)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Team."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Team."); + + if (breadcrumbs.IsSet && breadcrumbs.Value == null) + throw new ArgumentNullException(nameof(breadcrumbs), "Property is not nullable for class Team."); + + return new Team(id.Value!, name.Value!, breadcrumbs.Value!, externalId.Value!, description.Value!, parentTeam.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Team team, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, team, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Team team, JsonSerializerOptions jsonSerializerOptions) + { + if (team.Id == null) + throw new ArgumentNullException(nameof(team.Id), "Property is required for class Team."); + + if (team.Name == null) + throw new ArgumentNullException(nameof(team.Name), "Property is required for class Team."); + + if (team.Breadcrumbs == null) + throw new ArgumentNullException(nameof(team.Breadcrumbs), "Property is required for class Team."); + + writer.WriteString("id", team.Id); + + writer.WriteString("name", team.Name); + + writer.WriteString("breadcrumbs", team.Breadcrumbs); + + if (team.ExternalId != null) + writer.WriteString("external_id", team.ExternalId); + else + writer.WriteNull("external_id"); + + if (team.Description != null) + writer.WriteString("description", team.Description); + else + writer.WriteNull("description"); + + if (team.ParentTeam != null) + { + writer.WritePropertyName("parent_team"); + JsonSerializer.Serialize(writer, team.ParentTeam, jsonSerializerOptions); + } + else + writer.WriteNull("parent_team"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TeamCreate.cs b/sdk/dotnet/Timr.Api/Model/TeamCreate.cs new file mode 100644 index 0000000..f3cff72 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TeamCreate.cs @@ -0,0 +1,243 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TeamCreate + /// + public partial class TeamCreate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + /// description + /// parentTeamId + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonConstructor] + public TeamCreate(string name, Option description = default, Option parentTeamId = default, Option externalId = default) + { + Name = name; + DescriptionOption = description; + ParentTeamIdOption = parentTeamId; + ExternalIdOption = externalId; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Used to track the state of Description + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DescriptionOption { get; private set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string? Description { get { return this.DescriptionOption.Value; } set { this.DescriptionOption = new(value); } } + + /// + /// Used to track the state of ParentTeamId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ParentTeamIdOption { get; private set; } + + /// + /// Gets or Sets ParentTeamId + /// + [JsonPropertyName("parent_team_id")] + public string? ParentTeamId { get { return this.ParentTeamIdOption.Value; } set { this.ParentTeamIdOption = new(value); } } + + /// + /// Used to track the state of ExternalId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ExternalIdOption { get; private set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get { return this.ExternalIdOption.Value; } set { this.ExternalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TeamCreate {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ParentTeamId: ").Append(ParentTeamId).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TeamCreateJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TeamCreate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option description = default; + Option parentTeamId = default; + Option externalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()); + break; + case "parent_team_id": + parentTeamId = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!name.IsSet) + throw new ArgumentException("Property is required for class TeamCreate.", nameof(name)); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class TeamCreate."); + + return new TeamCreate(name.Value!, description, parentTeamId, externalId); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TeamCreate teamCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, teamCreate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TeamCreate teamCreate, JsonSerializerOptions jsonSerializerOptions) + { + if (teamCreate.Name == null) + throw new ArgumentNullException(nameof(teamCreate.Name), "Property is required for class TeamCreate."); + + writer.WriteString("name", teamCreate.Name); + + if (teamCreate.DescriptionOption.IsSet) + if (teamCreate.DescriptionOption.Value != null) + writer.WriteString("description", teamCreate.Description); + else + writer.WriteNull("description"); + + if (teamCreate.ParentTeamIdOption.IsSet) + if (teamCreate.ParentTeamIdOption.Value != null) + writer.WriteString("parent_team_id", teamCreate.ParentTeamId); + else + writer.WriteNull("parent_team_id"); + + if (teamCreate.ExternalIdOption.IsSet) + if (teamCreate.ExternalIdOption.Value != null) + writer.WriteString("external_id", teamCreate.ExternalId); + else + writer.WriteNull("external_id"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TeamPartial.cs b/sdk/dotnet/Timr.Api/Model/TeamPartial.cs new file mode 100644 index 0000000..e04df7e --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TeamPartial.cs @@ -0,0 +1,236 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TeamPartial + /// + public partial class TeamPartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// Full path of the entry within its hierarchy, including its own name. + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonConstructor] + public TeamPartial(string id, string name, string breadcrumbs, string? externalId = default) + { + Id = id; + Name = name; + Breadcrumbs = breadcrumbs; + ExternalId = externalId; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Full path of the entry within its hierarchy, including its own name. + /// + /// Full path of the entry within its hierarchy, including its own name. + [JsonPropertyName("breadcrumbs")] + public string Breadcrumbs { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TeamPartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Breadcrumbs: ").Append(Breadcrumbs).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TeamPartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TeamPartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option breadcrumbs = default; + Option externalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "breadcrumbs": + breadcrumbs = new Option(utf8JsonReader.GetString()!); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class TeamPartial.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class TeamPartial.", nameof(name)); + + if (!breadcrumbs.IsSet) + throw new ArgumentException("Property is required for class TeamPartial.", nameof(breadcrumbs)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class TeamPartial.", nameof(externalId)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class TeamPartial."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class TeamPartial."); + + if (breadcrumbs.IsSet && breadcrumbs.Value == null) + throw new ArgumentNullException(nameof(breadcrumbs), "Property is not nullable for class TeamPartial."); + + return new TeamPartial(id.Value!, name.Value!, breadcrumbs.Value!, externalId.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TeamPartial teamPartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, teamPartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TeamPartial teamPartial, JsonSerializerOptions jsonSerializerOptions) + { + if (teamPartial.Id == null) + throw new ArgumentNullException(nameof(teamPartial.Id), "Property is required for class TeamPartial."); + + if (teamPartial.Name == null) + throw new ArgumentNullException(nameof(teamPartial.Name), "Property is required for class TeamPartial."); + + if (teamPartial.Breadcrumbs == null) + throw new ArgumentNullException(nameof(teamPartial.Breadcrumbs), "Property is required for class TeamPartial."); + + writer.WriteString("id", teamPartial.Id); + + writer.WriteString("name", teamPartial.Name); + + writer.WriteString("breadcrumbs", teamPartial.Breadcrumbs); + + if (teamPartial.ExternalId != null) + writer.WriteString("external_id", teamPartial.ExternalId); + else + writer.WriteNull("external_id"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TeamUpdate.cs b/sdk/dotnet/Timr.Api/Model/TeamUpdate.cs new file mode 100644 index 0000000..0e53d14 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TeamUpdate.cs @@ -0,0 +1,248 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TeamUpdate + /// + public partial class TeamUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name + /// description + /// parentTeamId + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonConstructor] + public TeamUpdate(Option name = default, Option description = default, Option parentTeamId = default, Option externalId = default) + { + NameOption = name; + DescriptionOption = description; + ParentTeamIdOption = parentTeamId; + ExternalIdOption = externalId; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string? Name { get { return this.NameOption.Value; } set { this.NameOption = new(value); } } + + /// + /// Used to track the state of Description + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DescriptionOption { get; private set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string? Description { get { return this.DescriptionOption.Value; } set { this.DescriptionOption = new(value); } } + + /// + /// Used to track the state of ParentTeamId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ParentTeamIdOption { get; private set; } + + /// + /// Gets or Sets ParentTeamId + /// + [JsonPropertyName("parent_team_id")] + public string? ParentTeamId { get { return this.ParentTeamIdOption.Value; } set { this.ParentTeamIdOption = new(value); } } + + /// + /// Used to track the state of ExternalId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ExternalIdOption { get; private set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get { return this.ExternalIdOption.Value; } set { this.ExternalIdOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TeamUpdate {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ParentTeamId: ").Append(ParentTeamId).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TeamUpdateJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TeamUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option name = default; + Option description = default; + Option parentTeamId = default; + Option externalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "description": + description = new Option(utf8JsonReader.GetString()); + break; + case "parent_team_id": + parentTeamId = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class TeamUpdate."); + + return new TeamUpdate(name, description, parentTeamId, externalId); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TeamUpdate teamUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, teamUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TeamUpdate teamUpdate, JsonSerializerOptions jsonSerializerOptions) + { + if (teamUpdate.NameOption.IsSet && teamUpdate.Name == null) + throw new ArgumentNullException(nameof(teamUpdate.Name), "Property is required for class TeamUpdate."); + + if (teamUpdate.NameOption.IsSet) + writer.WriteString("name", teamUpdate.Name); + + if (teamUpdate.DescriptionOption.IsSet) + if (teamUpdate.DescriptionOption.Value != null) + writer.WriteString("description", teamUpdate.Description); + else + writer.WriteNull("description"); + + if (teamUpdate.ParentTeamIdOption.IsSet) + if (teamUpdate.ParentTeamIdOption.Value != null) + writer.WriteString("parent_team_id", teamUpdate.ParentTeamId); + else + writer.WriteNull("parent_team_id"); + + if (teamUpdate.ExternalIdOption.IsSet) + if (teamUpdate.ExternalIdOption.Value != null) + writer.WriteString("external_id", teamUpdate.ExternalId); + else + writer.WriteNull("external_id"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TeamsPage.cs b/sdk/dotnet/Timr.Api/Model/TeamsPage.cs new file mode 100644 index 0000000..1386bd6 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TeamsPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TeamsPage + /// + public partial class TeamsPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public TeamsPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TeamsPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TeamsPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TeamsPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TeamsPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class TeamsPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class TeamsPage."); + + return new TeamsPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TeamsPage teamsPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, teamsPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TeamsPage teamsPage, JsonSerializerOptions jsonSerializerOptions) + { + if (teamsPage.Data == null) + throw new ArgumentNullException(nameof(teamsPage.Data), "Property is required for class TeamsPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, teamsPage.Data, jsonSerializerOptions); + if (teamsPage.NextPageToken != null) + writer.WriteString("next_page_token", teamsPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TeamsPartialPage.cs b/sdk/dotnet/Timr.Api/Model/TeamsPartialPage.cs new file mode 100644 index 0000000..490ab09 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TeamsPartialPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TeamsPartialPage + /// + public partial class TeamsPartialPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public TeamsPartialPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TeamsPartialPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TeamsPartialPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TeamsPartialPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class TeamsPartialPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class TeamsPartialPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class TeamsPartialPage."); + + return new TeamsPartialPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TeamsPartialPage teamsPartialPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, teamsPartialPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TeamsPartialPage teamsPartialPage, JsonSerializerOptions jsonSerializerOptions) + { + if (teamsPartialPage.Data == null) + throw new ArgumentNullException(nameof(teamsPartialPage.Data), "Property is required for class TeamsPartialPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, teamsPartialPage.Data, jsonSerializerOptions); + if (teamsPartialPage.NextPageToken != null) + writer.WriteString("next_page_token", teamsPartialPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TeamsSortColumn.cs b/sdk/dotnet/Timr.Api/Model/TeamsSortColumn.cs new file mode 100644 index 0000000..234641c --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TeamsSortColumn.cs @@ -0,0 +1,177 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Teams. `breadcrumbs` orders by the Team's full path, `name` by its own name only. + /// + /// Sort property for Teams. `breadcrumbs` orders by the Team's full path, `name` by its own name only. + public enum TeamsSortColumn + { + /// + /// Enum Breadcrumbs for value: breadcrumbs + /// + Breadcrumbs = 1, + + /// + /// Enum Name for value: name + /// + Name = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class TeamsSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static TeamsSortColumn FromString(string value) + { + if (value.Equals("breadcrumbs")) + return TeamsSortColumn.Breadcrumbs; + + if (value.Equals("name")) + return TeamsSortColumn.Name; + + throw new NotImplementedException($"Could not convert value to type TeamsSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static TeamsSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("breadcrumbs")) + return TeamsSortColumn.Breadcrumbs; + + if (value.Equals("name")) + return TeamsSortColumn.Name; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(TeamsSortColumn value) + { + if (value == TeamsSortColumn.Breadcrumbs) + return "breadcrumbs"; + + if (value == TeamsSortColumn.Name) + return "name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class TeamsSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override TeamsSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TeamsSortColumn? result = rawValue == null + ? null + : TeamsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TeamsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TeamsSortColumn teamsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(TeamsSortColumnValueConverter.ToJsonValue(teamsSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class TeamsSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a TeamsSortColumn from the Json object + /// + /// + /// + /// + /// + public override TeamsSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + TeamsSortColumn? result = rawValue == null + ? null + : TeamsSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the TeamsSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TeamsSortColumn? teamsSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(teamsSortColumn.HasValue ? TeamsSortColumnValueConverter.ToJsonValue(teamsSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/TimeAccount.cs b/sdk/dotnet/Timr.Api/Model/TimeAccount.cs new file mode 100644 index 0000000..0133fe9 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/TimeAccount.cs @@ -0,0 +1,323 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// TimeAccount + /// + public partial class TimeAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// balanceLastPeriodMinutes + /// sum of durations in current period + /// target duration in current period + /// difference between target duration and actual duration + /// total duration until balancing date + /// complete days worked from home in current period + /// partial days worked from home in current period + /// flexTimeIndicator + [JsonConstructor] + public TimeAccount(int? balanceLastPeriodMinutes = default, int? durationActualMinutes = default, int? durationTargetMinutes = default, int? balanceCurrentPeriodMinutes = default, int? balanceTotalMinutes = default, int? workFromHomeDaysFull = default, int? workFromHomeDaysPartial = default, Option flexTimeIndicator = default) + { + BalanceLastPeriodMinutes = balanceLastPeriodMinutes; + DurationActualMinutes = durationActualMinutes; + DurationTargetMinutes = durationTargetMinutes; + BalanceCurrentPeriodMinutes = balanceCurrentPeriodMinutes; + BalanceTotalMinutes = balanceTotalMinutes; + WorkFromHomeDaysFull = workFromHomeDaysFull; + WorkFromHomeDaysPartial = workFromHomeDaysPartial; + FlexTimeIndicatorOption = flexTimeIndicator; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of FlexTimeIndicator + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option FlexTimeIndicatorOption { get; private set; } + + /// + /// Gets or Sets FlexTimeIndicator + /// + [JsonPropertyName("flex_time_indicator")] + public FlexTimeIndicator? FlexTimeIndicator { get { return this.FlexTimeIndicatorOption.Value; } set { this.FlexTimeIndicatorOption = new(value); } } + + /// + /// Gets or Sets BalanceLastPeriodMinutes + /// + [JsonPropertyName("balance_last_period_minutes")] + public int? BalanceLastPeriodMinutes { get; set; } + + /// + /// sum of durations in current period + /// + /// sum of durations in current period + [JsonPropertyName("duration_actual_minutes")] + public int? DurationActualMinutes { get; set; } + + /// + /// target duration in current period + /// + /// target duration in current period + [JsonPropertyName("duration_target_minutes")] + public int? DurationTargetMinutes { get; set; } + + /// + /// difference between target duration and actual duration + /// + /// difference between target duration and actual duration + [JsonPropertyName("balance_current_period_minutes")] + public int? BalanceCurrentPeriodMinutes { get; set; } + + /// + /// total duration until balancing date + /// + /// total duration until balancing date + [JsonPropertyName("balance_total_minutes")] + public int? BalanceTotalMinutes { get; set; } + + /// + /// complete days worked from home in current period + /// + /// complete days worked from home in current period + [JsonPropertyName("work_from_home_days_full")] + public int? WorkFromHomeDaysFull { get; set; } + + /// + /// partial days worked from home in current period + /// + /// partial days worked from home in current period + [JsonPropertyName("work_from_home_days_partial")] + public int? WorkFromHomeDaysPartial { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class TimeAccount {\n"); + sb.Append(" BalanceLastPeriodMinutes: ").Append(BalanceLastPeriodMinutes).Append("\n"); + sb.Append(" DurationActualMinutes: ").Append(DurationActualMinutes).Append("\n"); + sb.Append(" DurationTargetMinutes: ").Append(DurationTargetMinutes).Append("\n"); + sb.Append(" BalanceCurrentPeriodMinutes: ").Append(BalanceCurrentPeriodMinutes).Append("\n"); + sb.Append(" BalanceTotalMinutes: ").Append(BalanceTotalMinutes).Append("\n"); + sb.Append(" WorkFromHomeDaysFull: ").Append(WorkFromHomeDaysFull).Append("\n"); + sb.Append(" WorkFromHomeDaysPartial: ").Append(WorkFromHomeDaysPartial).Append("\n"); + sb.Append(" FlexTimeIndicator: ").Append(FlexTimeIndicator).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class TimeAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override TimeAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option balanceLastPeriodMinutes = default; + Option durationActualMinutes = default; + Option durationTargetMinutes = default; + Option balanceCurrentPeriodMinutes = default; + Option balanceTotalMinutes = default; + Option workFromHomeDaysFull = default; + Option workFromHomeDaysPartial = default; + Option flexTimeIndicator = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "balance_last_period_minutes": + balanceLastPeriodMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "duration_actual_minutes": + durationActualMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "duration_target_minutes": + durationTargetMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "balance_current_period_minutes": + balanceCurrentPeriodMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "balance_total_minutes": + balanceTotalMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "work_from_home_days_full": + workFromHomeDaysFull = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "work_from_home_days_partial": + workFromHomeDaysPartial = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "flex_time_indicator": + string? flexTimeIndicatorRawValue = utf8JsonReader.GetString(); + flexTimeIndicator = new Option(flexTimeIndicatorRawValue == null ? null : FlexTimeIndicatorValueConverter.FromStringOrDefault(flexTimeIndicatorRawValue)); + break; + default: + break; + } + } + } + + if (!balanceLastPeriodMinutes.IsSet) + throw new ArgumentException("Property is required for class TimeAccount.", nameof(balanceLastPeriodMinutes)); + + if (!durationActualMinutes.IsSet) + throw new ArgumentException("Property is required for class TimeAccount.", nameof(durationActualMinutes)); + + if (!durationTargetMinutes.IsSet) + throw new ArgumentException("Property is required for class TimeAccount.", nameof(durationTargetMinutes)); + + if (!balanceCurrentPeriodMinutes.IsSet) + throw new ArgumentException("Property is required for class TimeAccount.", nameof(balanceCurrentPeriodMinutes)); + + if (!balanceTotalMinutes.IsSet) + throw new ArgumentException("Property is required for class TimeAccount.", nameof(balanceTotalMinutes)); + + if (!workFromHomeDaysFull.IsSet) + throw new ArgumentException("Property is required for class TimeAccount.", nameof(workFromHomeDaysFull)); + + if (!workFromHomeDaysPartial.IsSet) + throw new ArgumentException("Property is required for class TimeAccount.", nameof(workFromHomeDaysPartial)); + + return new TimeAccount(balanceLastPeriodMinutes.Value!, durationActualMinutes.Value!, durationTargetMinutes.Value!, balanceCurrentPeriodMinutes.Value!, balanceTotalMinutes.Value!, workFromHomeDaysFull.Value!, workFromHomeDaysPartial.Value!, flexTimeIndicator); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, TimeAccount timeAccount, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, timeAccount, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, TimeAccount timeAccount, JsonSerializerOptions jsonSerializerOptions) + { + if (timeAccount.BalanceLastPeriodMinutes != null) + writer.WriteNumber("balance_last_period_minutes", timeAccount.BalanceLastPeriodMinutes.Value); + else + writer.WriteNull("balance_last_period_minutes"); + + if (timeAccount.DurationActualMinutes != null) + writer.WriteNumber("duration_actual_minutes", timeAccount.DurationActualMinutes.Value); + else + writer.WriteNull("duration_actual_minutes"); + + if (timeAccount.DurationTargetMinutes != null) + writer.WriteNumber("duration_target_minutes", timeAccount.DurationTargetMinutes.Value); + else + writer.WriteNull("duration_target_minutes"); + + if (timeAccount.BalanceCurrentPeriodMinutes != null) + writer.WriteNumber("balance_current_period_minutes", timeAccount.BalanceCurrentPeriodMinutes.Value); + else + writer.WriteNull("balance_current_period_minutes"); + + if (timeAccount.BalanceTotalMinutes != null) + writer.WriteNumber("balance_total_minutes", timeAccount.BalanceTotalMinutes.Value); + else + writer.WriteNull("balance_total_minutes"); + + if (timeAccount.WorkFromHomeDaysFull != null) + writer.WriteNumber("work_from_home_days_full", timeAccount.WorkFromHomeDaysFull.Value); + else + writer.WriteNull("work_from_home_days_full"); + + if (timeAccount.WorkFromHomeDaysPartial != null) + writer.WriteNumber("work_from_home_days_partial", timeAccount.WorkFromHomeDaysPartial.Value); + else + writer.WriteNull("work_from_home_days_partial"); + + if (timeAccount.FlexTimeIndicatorOption.IsSet) + if (timeAccount.FlexTimeIndicatorOption!.Value != null) + { + var flexTimeIndicatorRawValue = FlexTimeIndicatorValueConverter.ToJsonValue(timeAccount.FlexTimeIndicatorOption.Value!.Value); + writer.WriteString("flex_time_indicator", flexTimeIndicatorRawValue); + } + else + writer.WriteNull("flex_time_indicator"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/User.cs b/sdk/dotnet/Timr.Api/Model/User.cs new file mode 100644 index 0000000..2e8cd79 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/User.cs @@ -0,0 +1,529 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// A user's identity (`firstname`, `lastname`, `email`), employment dates (`entry_date`, `resign_date`), and the assigned `work_schedule_model` and `holiday_calendar`. + /// + public partial class User : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// firstname + /// lastname + /// fullname + /// Email address must be either valid or null. + /// employeeNumber + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// login + /// RFC 3339 date (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// workScheduleModel + /// holidayCalendar + /// recurring month and day on which the user's vacation year starts + /// metadata + [JsonConstructor] + public User(string id, string? firstname = default, string? lastname = default, string? fullname = default, string? email = default, string? employeeNumber = default, string? externalId = default, Option login = default, Option entryDate = default, Option resignDate = default, Option workScheduleModel = default, Option holidayCalendar = default, Option vacationYearStart = default, Option?> metadata = default) + { + Id = id; + Firstname = firstname; + Lastname = lastname; + Fullname = fullname; + Email = email; + EmployeeNumber = employeeNumber; + ExternalId = externalId; + LoginOption = login; + EntryDateOption = entryDate; + ResignDateOption = resignDate; + WorkScheduleModelOption = workScheduleModel; + HolidayCalendarOption = holidayCalendar; + VacationYearStartOption = vacationYearStart; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Firstname + /// + [JsonPropertyName("firstname")] + public string? Firstname { get; set; } + + /// + /// Gets or Sets Lastname + /// + [JsonPropertyName("lastname")] + public string? Lastname { get; set; } + + /// + /// Gets or Sets Fullname + /// + [JsonPropertyName("fullname")] + public string? Fullname { get; set; } + + /// + /// Email address must be either valid or null. + /// + /// Email address must be either valid or null. + /* user@example.com */ + [JsonPropertyName("email")] + public string? Email { get; set; } + + /// + /// Gets or Sets EmployeeNumber + /// + [JsonPropertyName("employee_number")] + public string? EmployeeNumber { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Used to track the state of Login + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LoginOption { get; private set; } + + /// + /// Gets or Sets Login + /// + [JsonPropertyName("login")] + public string? Login { get { return this.LoginOption.Value; } set { this.LoginOption = new(value); } } + + /// + /// Used to track the state of EntryDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EntryDateOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("entry_date")] + public DateOnly? EntryDate { get { return this.EntryDateOption.Value; } set { this.EntryDateOption = new(value); } } + + /// + /// Used to track the state of ResignDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ResignDateOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("resign_date")] + public DateOnly? ResignDate { get { return this.ResignDateOption.Value; } set { this.ResignDateOption = new(value); } } + + /// + /// Used to track the state of WorkScheduleModel + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option WorkScheduleModelOption { get; private set; } + + /// + /// Gets or Sets WorkScheduleModel + /// + [JsonPropertyName("work_schedule_model")] + public WorkScheduleModelPartial? WorkScheduleModel { get { return this.WorkScheduleModelOption.Value; } set { this.WorkScheduleModelOption = new(value); } } + + /// + /// Used to track the state of HolidayCalendar + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option HolidayCalendarOption { get; private set; } + + /// + /// Gets or Sets HolidayCalendar + /// + [JsonPropertyName("holiday_calendar")] + public HolidayCalendarPartial? HolidayCalendar { get { return this.HolidayCalendarOption.Value; } set { this.HolidayCalendarOption = new(value); } } + + /// + /// Used to track the state of VacationYearStart + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option VacationYearStartOption { get; private set; } + + /// + /// recurring month and day on which the user's vacation year starts + /// + /// recurring month and day on which the user's vacation year starts + /* --05-20 */ + [JsonPropertyName("vacation_year_start")] + public string? VacationYearStart { get { return this.VacationYearStartOption.Value; } set { this.VacationYearStartOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class User {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Firstname: ").Append(Firstname).Append("\n"); + sb.Append(" Lastname: ").Append(Lastname).Append("\n"); + sb.Append(" Fullname: ").Append(Fullname).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" EmployeeNumber: ").Append(EmployeeNumber).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Login: ").Append(Login).Append("\n"); + sb.Append(" EntryDate: ").Append(EntryDate).Append("\n"); + sb.Append(" ResignDate: ").Append(ResignDate).Append("\n"); + sb.Append(" WorkScheduleModel: ").Append(WorkScheduleModel).Append("\n"); + sb.Append(" HolidayCalendar: ").Append(HolidayCalendar).Append("\n"); + sb.Append(" VacationYearStart: ").Append(VacationYearStart).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Email (string) minLength + if (this.Email != null && this.Email.Length < 1) + { + yield return new ValidationResult("Invalid value for Email, length must be greater than 1.", new [] { "Email" }); + } + + if (this.LoginOption.Value != null) { + // Login (string) pattern + Regex regexLogin = new Regex(@"^[A-Za-z0-9!#$%&'*+/=@\.?^_`{|}~-]*$", RegexOptions.CultureInvariant); + + if (this.LoginOption.Value != null &&!regexLogin.Match(this.LoginOption.Value).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Login, must match a pattern of " + regexLogin, new [] { "Login" }); + } + } + + if (this.VacationYearStartOption.Value != null) { + // VacationYearStart (string) pattern + Regex regexVacationYearStart = new Regex(@"^--(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$", RegexOptions.CultureInvariant); + + if (this.VacationYearStartOption.Value != null &&!regexVacationYearStart.Match(this.VacationYearStartOption.Value).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VacationYearStart, must match a pattern of " + regexVacationYearStart, new [] { "VacationYearStart" }); + } + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UserJsonConverter : JsonConverter + { + /// + /// The format to use to serialize EntryDate + /// + public static string EntryDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize ResignDate + /// + public static string ResignDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option firstname = default; + Option lastname = default; + Option fullname = default; + Option email = default; + Option employeeNumber = default; + Option externalId = default; + Option login = default; + Option entryDate = default; + Option resignDate = default; + Option workScheduleModel = default; + Option holidayCalendar = default; + Option vacationYearStart = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "firstname": + firstname = new Option(utf8JsonReader.GetString()); + break; + case "lastname": + lastname = new Option(utf8JsonReader.GetString()); + break; + case "fullname": + fullname = new Option(utf8JsonReader.GetString()); + break; + case "email": + email = new Option(utf8JsonReader.GetString()); + break; + case "employee_number": + employeeNumber = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "login": + login = new Option(utf8JsonReader.GetString()!); + break; + case "entry_date": + entryDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "resign_date": + resignDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "work_schedule_model": + workScheduleModel = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "holiday_calendar": + holidayCalendar = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "vacation_year_start": + vacationYearStart = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(id)); + + if (!firstname.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(firstname)); + + if (!lastname.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(lastname)); + + if (!fullname.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(fullname)); + + if (!email.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(email)); + + if (!employeeNumber.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(employeeNumber)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class User.", nameof(externalId)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class User."); + + if (login.IsSet && login.Value == null) + throw new ArgumentNullException(nameof(login), "Property is not nullable for class User."); + + if (holidayCalendar.IsSet && holidayCalendar.Value == null) + throw new ArgumentNullException(nameof(holidayCalendar), "Property is not nullable for class User."); + + return new User(id.Value!, firstname.Value!, lastname.Value!, fullname.Value!, email.Value!, employeeNumber.Value!, externalId.Value!, login, entryDate, resignDate, workScheduleModel, holidayCalendar, vacationYearStart, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, user, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) + { + if (user.Id == null) + throw new ArgumentNullException(nameof(user.Id), "Property is required for class User."); + + if (user.LoginOption.IsSet && user.Login == null) + throw new ArgumentNullException(nameof(user.Login), "Property is required for class User."); + + if (user.HolidayCalendarOption.IsSet && user.HolidayCalendar == null) + throw new ArgumentNullException(nameof(user.HolidayCalendar), "Property is required for class User."); + + writer.WriteString("id", user.Id); + + if (user.Firstname != null) + writer.WriteString("firstname", user.Firstname); + else + writer.WriteNull("firstname"); + + if (user.Lastname != null) + writer.WriteString("lastname", user.Lastname); + else + writer.WriteNull("lastname"); + + if (user.Fullname != null) + writer.WriteString("fullname", user.Fullname); + else + writer.WriteNull("fullname"); + + if (user.Email != null) + writer.WriteString("email", user.Email); + else + writer.WriteNull("email"); + + if (user.EmployeeNumber != null) + writer.WriteString("employee_number", user.EmployeeNumber); + else + writer.WriteNull("employee_number"); + + if (user.ExternalId != null) + writer.WriteString("external_id", user.ExternalId); + else + writer.WriteNull("external_id"); + + if (user.LoginOption.IsSet) + writer.WriteString("login", user.Login); + + if (user.EntryDateOption.IsSet) + if (user.EntryDateOption.Value != null) + writer.WriteString("entry_date", user.EntryDateOption.Value!.Value.ToString(EntryDateFormat)); + else + writer.WriteNull("entry_date"); + + if (user.ResignDateOption.IsSet) + if (user.ResignDateOption.Value != null) + writer.WriteString("resign_date", user.ResignDateOption.Value!.Value.ToString(ResignDateFormat)); + else + writer.WriteNull("resign_date"); + + if (user.WorkScheduleModelOption.IsSet) + if (user.WorkScheduleModelOption.Value != null) + { + writer.WritePropertyName("work_schedule_model"); + JsonSerializer.Serialize(writer, user.WorkScheduleModel, jsonSerializerOptions); + } + else + writer.WriteNull("work_schedule_model"); + if (user.HolidayCalendarOption.IsSet) + { + writer.WritePropertyName("holiday_calendar"); + JsonSerializer.Serialize(writer, user.HolidayCalendar, jsonSerializerOptions); + } + if (user.VacationYearStartOption.IsSet) + if (user.VacationYearStartOption.Value != null) + writer.WriteString("vacation_year_start", user.VacationYearStart); + else + writer.WriteNull("vacation_year_start"); + + if (user.MetadataOption.IsSet) + if (user.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, user.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/UserCreate.cs b/sdk/dotnet/Timr.Api/Model/UserCreate.cs new file mode 100644 index 0000000..543ca20 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/UserCreate.cs @@ -0,0 +1,461 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// UserCreate + /// + public partial class UserCreate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// login + /// firstname + /// lastname + /// email + /// RFC 3339 date (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// employeeNumber + /// externalId + /// metadata + /// authProvider + /// authIdentifier + [JsonConstructor] + public UserCreate(string login, Option firstname = default, Option lastname = default, Option email = default, Option entryDate = default, Option resignDate = default, Option employeeNumber = default, Option externalId = default, Option?> metadata = default, Option authProvider = default, Option authIdentifier = default) + { + Login = login; + FirstnameOption = firstname; + LastnameOption = lastname; + EmailOption = email; + EntryDateOption = entryDate; + ResignDateOption = resignDate; + EmployeeNumberOption = employeeNumber; + ExternalIdOption = externalId; + MetadataOption = metadata; + AuthProviderOption = authProvider; + AuthIdentifierOption = authIdentifier; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Login + /// + [JsonPropertyName("login")] + public string Login { get; set; } + + /// + /// Used to track the state of Firstname + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option FirstnameOption { get; private set; } + + /// + /// Gets or Sets Firstname + /// + [JsonPropertyName("firstname")] + public string? Firstname { get { return this.FirstnameOption.Value; } set { this.FirstnameOption = new(value); } } + + /// + /// Used to track the state of Lastname + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LastnameOption { get; private set; } + + /// + /// Gets or Sets Lastname + /// + [JsonPropertyName("lastname")] + public string? Lastname { get { return this.LastnameOption.Value; } set { this.LastnameOption = new(value); } } + + /// + /// Used to track the state of Email + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EmailOption { get; private set; } + + /// + /// Gets or Sets Email + /// + [JsonPropertyName("email")] + public string? Email { get { return this.EmailOption.Value; } set { this.EmailOption = new(value); } } + + /// + /// Used to track the state of EntryDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EntryDateOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("entry_date")] + public DateOnly? EntryDate { get { return this.EntryDateOption.Value; } set { this.EntryDateOption = new(value); } } + + /// + /// Used to track the state of ResignDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ResignDateOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("resign_date")] + public DateOnly? ResignDate { get { return this.ResignDateOption.Value; } set { this.ResignDateOption = new(value); } } + + /// + /// Used to track the state of EmployeeNumber + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EmployeeNumberOption { get; private set; } + + /// + /// Gets or Sets EmployeeNumber + /// + [JsonPropertyName("employee_number")] + public string? EmployeeNumber { get { return this.EmployeeNumberOption.Value; } set { this.EmployeeNumberOption = new(value); } } + + /// + /// Used to track the state of ExternalId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ExternalIdOption { get; private set; } + + /// + /// Gets or Sets ExternalId + /// + [JsonPropertyName("external_id")] + public string? ExternalId { get { return this.ExternalIdOption.Value; } set { this.ExternalIdOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Used to track the state of AuthProvider + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option AuthProviderOption { get; private set; } + + /// + /// Gets or Sets AuthProvider + /// + /* azure|google */ + [JsonPropertyName("auth_provider")] + public string? AuthProvider { get { return this.AuthProviderOption.Value; } set { this.AuthProviderOption = new(value); } } + + /// + /// Used to track the state of AuthIdentifier + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option AuthIdentifierOption { get; private set; } + + /// + /// Gets or Sets AuthIdentifier + /// + [JsonPropertyName("auth_identifier")] + public string? AuthIdentifier { get { return this.AuthIdentifierOption.Value; } set { this.AuthIdentifierOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UserCreate {\n"); + sb.Append(" Login: ").Append(Login).Append("\n"); + sb.Append(" Firstname: ").Append(Firstname).Append("\n"); + sb.Append(" Lastname: ").Append(Lastname).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" EntryDate: ").Append(EntryDate).Append("\n"); + sb.Append(" ResignDate: ").Append(ResignDate).Append("\n"); + sb.Append(" EmployeeNumber: ").Append(EmployeeNumber).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" AuthProvider: ").Append(AuthProvider).Append("\n"); + sb.Append(" AuthIdentifier: ").Append(AuthIdentifier).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Login (string) minLength + if (this.Login != null && this.Login.Length < 1) + { + yield return new ValidationResult("Invalid value for Login, length must be greater than 1.", new [] { "Login" }); + } + + if (this.Login != null) { + // Login (string) pattern + Regex regexLogin = new Regex(@"^[A-Za-z0-9!#$%&'*+/=@\.?^_`{|}~-]*$", RegexOptions.CultureInvariant); + + if (!regexLogin.Match(this.Login).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Login, must match a pattern of " + regexLogin, new [] { "Login" }); + } + } + + // Email (string) minLength + if (this.Email != null && this.Email.Length < 1) + { + yield return new ValidationResult("Invalid value for Email, length must be greater than 1.", new [] { "Email" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UserCreateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize EntryDate + /// + public static string EntryDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize ResignDate + /// + public static string ResignDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override UserCreate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option login = default; + Option firstname = default; + Option lastname = default; + Option email = default; + Option entryDate = default; + Option resignDate = default; + Option employeeNumber = default; + Option externalId = default; + Option?> metadata = default; + Option authProvider = default; + Option authIdentifier = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "login": + login = new Option(utf8JsonReader.GetString()!); + break; + case "firstname": + firstname = new Option(utf8JsonReader.GetString()); + break; + case "lastname": + lastname = new Option(utf8JsonReader.GetString()); + break; + case "email": + email = new Option(utf8JsonReader.GetString()); + break; + case "entry_date": + entryDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "resign_date": + resignDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "employee_number": + employeeNumber = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "auth_provider": + authProvider = new Option(utf8JsonReader.GetString()); + break; + case "auth_identifier": + authIdentifier = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!login.IsSet) + throw new ArgumentException("Property is required for class UserCreate.", nameof(login)); + + if (login.IsSet && login.Value == null) + throw new ArgumentNullException(nameof(login), "Property is not nullable for class UserCreate."); + + return new UserCreate(login.Value!, firstname, lastname, email, entryDate, resignDate, employeeNumber, externalId, metadata, authProvider, authIdentifier); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UserCreate userCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, userCreate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UserCreate userCreate, JsonSerializerOptions jsonSerializerOptions) + { + if (userCreate.Login == null) + throw new ArgumentNullException(nameof(userCreate.Login), "Property is required for class UserCreate."); + + writer.WriteString("login", userCreate.Login); + + if (userCreate.FirstnameOption.IsSet) + if (userCreate.FirstnameOption.Value != null) + writer.WriteString("firstname", userCreate.Firstname); + else + writer.WriteNull("firstname"); + + if (userCreate.LastnameOption.IsSet) + if (userCreate.LastnameOption.Value != null) + writer.WriteString("lastname", userCreate.Lastname); + else + writer.WriteNull("lastname"); + + if (userCreate.EmailOption.IsSet) + if (userCreate.EmailOption.Value != null) + writer.WriteString("email", userCreate.Email); + else + writer.WriteNull("email"); + + if (userCreate.EntryDateOption.IsSet) + if (userCreate.EntryDateOption.Value != null) + writer.WriteString("entry_date", userCreate.EntryDateOption.Value!.Value.ToString(EntryDateFormat)); + else + writer.WriteNull("entry_date"); + + if (userCreate.ResignDateOption.IsSet) + if (userCreate.ResignDateOption.Value != null) + writer.WriteString("resign_date", userCreate.ResignDateOption.Value!.Value.ToString(ResignDateFormat)); + else + writer.WriteNull("resign_date"); + + if (userCreate.EmployeeNumberOption.IsSet) + if (userCreate.EmployeeNumberOption.Value != null) + writer.WriteString("employee_number", userCreate.EmployeeNumber); + else + writer.WriteNull("employee_number"); + + if (userCreate.ExternalIdOption.IsSet) + if (userCreate.ExternalIdOption.Value != null) + writer.WriteString("external_id", userCreate.ExternalId); + else + writer.WriteNull("external_id"); + + if (userCreate.MetadataOption.IsSet) + if (userCreate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, userCreate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + if (userCreate.AuthProviderOption.IsSet) + if (userCreate.AuthProviderOption.Value != null) + writer.WriteString("auth_provider", userCreate.AuthProvider); + else + writer.WriteNull("auth_provider"); + + if (userCreate.AuthIdentifierOption.IsSet) + if (userCreate.AuthIdentifierOption.Value != null) + writer.WriteString("auth_identifier", userCreate.AuthIdentifier); + else + writer.WriteNull("auth_identifier"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/UserPartial.cs b/sdk/dotnet/Timr.Api/Model/UserPartial.cs new file mode 100644 index 0000000..8e87f6a --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/UserPartial.cs @@ -0,0 +1,300 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// UserPartial + /// + public partial class UserPartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// firstname + /// lastname + /// fullname + /// Email address must be either valid or null. + /// employeeNumber + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonConstructor] + public UserPartial(string id, string? firstname = default, string? lastname = default, string? fullname = default, string? email = default, string? employeeNumber = default, string? externalId = default) + { + Id = id; + Firstname = firstname; + Lastname = lastname; + Fullname = fullname; + Email = email; + EmployeeNumber = employeeNumber; + ExternalId = externalId; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Firstname + /// + [JsonPropertyName("firstname")] + public string? Firstname { get; set; } + + /// + /// Gets or Sets Lastname + /// + [JsonPropertyName("lastname")] + public string? Lastname { get; set; } + + /// + /// Gets or Sets Fullname + /// + [JsonPropertyName("fullname")] + public string? Fullname { get; set; } + + /// + /// Email address must be either valid or null. + /// + /// Email address must be either valid or null. + /* user@example.com */ + [JsonPropertyName("email")] + public string? Email { get; set; } + + /// + /// Gets or Sets EmployeeNumber + /// + [JsonPropertyName("employee_number")] + public string? EmployeeNumber { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UserPartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Firstname: ").Append(Firstname).Append("\n"); + sb.Append(" Lastname: ").Append(Lastname).Append("\n"); + sb.Append(" Fullname: ").Append(Fullname).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" EmployeeNumber: ").Append(EmployeeNumber).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Email (string) minLength + if (this.Email != null && this.Email.Length < 1) + { + yield return new ValidationResult("Invalid value for Email, length must be greater than 1.", new [] { "Email" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UserPartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override UserPartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option firstname = default; + Option lastname = default; + Option fullname = default; + Option email = default; + Option employeeNumber = default; + Option externalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "firstname": + firstname = new Option(utf8JsonReader.GetString()); + break; + case "lastname": + lastname = new Option(utf8JsonReader.GetString()); + break; + case "fullname": + fullname = new Option(utf8JsonReader.GetString()); + break; + case "email": + email = new Option(utf8JsonReader.GetString()); + break; + case "employee_number": + employeeNumber = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class UserPartial.", nameof(id)); + + if (!firstname.IsSet) + throw new ArgumentException("Property is required for class UserPartial.", nameof(firstname)); + + if (!lastname.IsSet) + throw new ArgumentException("Property is required for class UserPartial.", nameof(lastname)); + + if (!fullname.IsSet) + throw new ArgumentException("Property is required for class UserPartial.", nameof(fullname)); + + if (!email.IsSet) + throw new ArgumentException("Property is required for class UserPartial.", nameof(email)); + + if (!employeeNumber.IsSet) + throw new ArgumentException("Property is required for class UserPartial.", nameof(employeeNumber)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class UserPartial.", nameof(externalId)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class UserPartial."); + + return new UserPartial(id.Value!, firstname.Value!, lastname.Value!, fullname.Value!, email.Value!, employeeNumber.Value!, externalId.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UserPartial userPartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, userPartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UserPartial userPartial, JsonSerializerOptions jsonSerializerOptions) + { + if (userPartial.Id == null) + throw new ArgumentNullException(nameof(userPartial.Id), "Property is required for class UserPartial."); + + writer.WriteString("id", userPartial.Id); + + if (userPartial.Firstname != null) + writer.WriteString("firstname", userPartial.Firstname); + else + writer.WriteNull("firstname"); + + if (userPartial.Lastname != null) + writer.WriteString("lastname", userPartial.Lastname); + else + writer.WriteNull("lastname"); + + if (userPartial.Fullname != null) + writer.WriteString("fullname", userPartial.Fullname); + else + writer.WriteNull("fullname"); + + if (userPartial.Email != null) + writer.WriteString("email", userPartial.Email); + else + writer.WriteNull("email"); + + if (userPartial.EmployeeNumber != null) + writer.WriteString("employee_number", userPartial.EmployeeNumber); + else + writer.WriteNull("employee_number"); + + if (userPartial.ExternalId != null) + writer.WriteString("external_id", userPartial.ExternalId); + else + writer.WriteNull("external_id"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/UserUpdate.cs b/sdk/dotnet/Timr.Api/Model/UserUpdate.cs new file mode 100644 index 0000000..49215b5 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/UserUpdate.cs @@ -0,0 +1,414 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// UserUpdate + /// + public partial class UserUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// login + /// firstname + /// lastname + /// email + /// RFC 3339 date (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// employeeNumber + /// externalId + /// metadata + [JsonConstructor] + public UserUpdate(Option login = default, Option firstname = default, Option lastname = default, Option email = default, Option entryDate = default, Option resignDate = default, Option employeeNumber = default, Option externalId = default, Option?> metadata = default) + { + LoginOption = login; + FirstnameOption = firstname; + LastnameOption = lastname; + EmailOption = email; + EntryDateOption = entryDate; + ResignDateOption = resignDate; + EmployeeNumberOption = employeeNumber; + ExternalIdOption = externalId; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Login + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LoginOption { get; private set; } + + /// + /// Gets or Sets Login + /// + [JsonPropertyName("login")] + public string? Login { get { return this.LoginOption.Value; } set { this.LoginOption = new(value); } } + + /// + /// Used to track the state of Firstname + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option FirstnameOption { get; private set; } + + /// + /// Gets or Sets Firstname + /// + [JsonPropertyName("firstname")] + public string? Firstname { get { return this.FirstnameOption.Value; } set { this.FirstnameOption = new(value); } } + + /// + /// Used to track the state of Lastname + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LastnameOption { get; private set; } + + /// + /// Gets or Sets Lastname + /// + [JsonPropertyName("lastname")] + public string? Lastname { get { return this.LastnameOption.Value; } set { this.LastnameOption = new(value); } } + + /// + /// Used to track the state of Email + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EmailOption { get; private set; } + + /// + /// Gets or Sets Email + /// + [JsonPropertyName("email")] + public string? Email { get { return this.EmailOption.Value; } set { this.EmailOption = new(value); } } + + /// + /// Used to track the state of EntryDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EntryDateOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("entry_date")] + public DateOnly? EntryDate { get { return this.EntryDateOption.Value; } set { this.EntryDateOption = new(value); } } + + /// + /// Used to track the state of ResignDate + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ResignDateOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("resign_date")] + public DateOnly? ResignDate { get { return this.ResignDateOption.Value; } set { this.ResignDateOption = new(value); } } + + /// + /// Used to track the state of EmployeeNumber + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EmployeeNumberOption { get; private set; } + + /// + /// Gets or Sets EmployeeNumber + /// + [JsonPropertyName("employee_number")] + public string? EmployeeNumber { get { return this.EmployeeNumberOption.Value; } set { this.EmployeeNumberOption = new(value); } } + + /// + /// Used to track the state of ExternalId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ExternalIdOption { get; private set; } + + /// + /// Gets or Sets ExternalId + /// + [JsonPropertyName("external_id")] + public string? ExternalId { get { return this.ExternalIdOption.Value; } set { this.ExternalIdOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UserUpdate {\n"); + sb.Append(" Login: ").Append(Login).Append("\n"); + sb.Append(" Firstname: ").Append(Firstname).Append("\n"); + sb.Append(" Lastname: ").Append(Lastname).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" EntryDate: ").Append(EntryDate).Append("\n"); + sb.Append(" ResignDate: ").Append(ResignDate).Append("\n"); + sb.Append(" EmployeeNumber: ").Append(EmployeeNumber).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Login (string) minLength + if (this.Login != null && this.Login.Length < 1) + { + yield return new ValidationResult("Invalid value for Login, length must be greater than 1.", new [] { "Login" }); + } + + if (this.LoginOption.Value != null) { + // Login (string) pattern + Regex regexLogin = new Regex(@"^[A-Za-z0-9!#$%&'*+/=@\.?^_`{|}~-]*$", RegexOptions.CultureInvariant); + + if (this.LoginOption.Value != null &&!regexLogin.Match(this.LoginOption.Value).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Login, must match a pattern of " + regexLogin, new [] { "Login" }); + } + } + + // Email (string) minLength + if (this.Email != null && this.Email.Length < 1) + { + yield return new ValidationResult("Invalid value for Email, length must be greater than 1.", new [] { "Email" }); + } + + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UserUpdateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize EntryDate + /// + public static string EntryDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize ResignDate + /// + public static string ResignDateFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override UserUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option login = default; + Option firstname = default; + Option lastname = default; + Option email = default; + Option entryDate = default; + Option resignDate = default; + Option employeeNumber = default; + Option externalId = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "login": + login = new Option(utf8JsonReader.GetString()!); + break; + case "firstname": + firstname = new Option(utf8JsonReader.GetString()); + break; + case "lastname": + lastname = new Option(utf8JsonReader.GetString()); + break; + case "email": + email = new Option(utf8JsonReader.GetString()); + break; + case "entry_date": + entryDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "resign_date": + resignDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "employee_number": + employeeNumber = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (login.IsSet && login.Value == null) + throw new ArgumentNullException(nameof(login), "Property is not nullable for class UserUpdate."); + + return new UserUpdate(login, firstname, lastname, email, entryDate, resignDate, employeeNumber, externalId, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UserUpdate userUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, userUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UserUpdate userUpdate, JsonSerializerOptions jsonSerializerOptions) + { + if (userUpdate.LoginOption.IsSet && userUpdate.Login == null) + throw new ArgumentNullException(nameof(userUpdate.Login), "Property is required for class UserUpdate."); + + if (userUpdate.LoginOption.IsSet) + writer.WriteString("login", userUpdate.Login); + + if (userUpdate.FirstnameOption.IsSet) + if (userUpdate.FirstnameOption.Value != null) + writer.WriteString("firstname", userUpdate.Firstname); + else + writer.WriteNull("firstname"); + + if (userUpdate.LastnameOption.IsSet) + if (userUpdate.LastnameOption.Value != null) + writer.WriteString("lastname", userUpdate.Lastname); + else + writer.WriteNull("lastname"); + + if (userUpdate.EmailOption.IsSet) + if (userUpdate.EmailOption.Value != null) + writer.WriteString("email", userUpdate.Email); + else + writer.WriteNull("email"); + + if (userUpdate.EntryDateOption.IsSet) + if (userUpdate.EntryDateOption.Value != null) + writer.WriteString("entry_date", userUpdate.EntryDateOption.Value!.Value.ToString(EntryDateFormat)); + else + writer.WriteNull("entry_date"); + + if (userUpdate.ResignDateOption.IsSet) + if (userUpdate.ResignDateOption.Value != null) + writer.WriteString("resign_date", userUpdate.ResignDateOption.Value!.Value.ToString(ResignDateFormat)); + else + writer.WriteNull("resign_date"); + + if (userUpdate.EmployeeNumberOption.IsSet) + if (userUpdate.EmployeeNumberOption.Value != null) + writer.WriteString("employee_number", userUpdate.EmployeeNumber); + else + writer.WriteNull("employee_number"); + + if (userUpdate.ExternalIdOption.IsSet) + if (userUpdate.ExternalIdOption.Value != null) + writer.WriteString("external_id", userUpdate.ExternalId); + else + writer.WriteNull("external_id"); + + if (userUpdate.MetadataOption.IsSet) + if (userUpdate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, userUpdate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/UsersPage.cs b/sdk/dotnet/Timr.Api/Model/UsersPage.cs new file mode 100644 index 0000000..36909fd --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/UsersPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// UsersPage + /// + public partial class UsersPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public UsersPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UsersPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UsersPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override UsersPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class UsersPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class UsersPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class UsersPage."); + + return new UsersPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UsersPage usersPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, usersPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UsersPage usersPage, JsonSerializerOptions jsonSerializerOptions) + { + if (usersPage.Data == null) + throw new ArgumentNullException(nameof(usersPage.Data), "Property is required for class UsersPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, usersPage.Data, jsonSerializerOptions); + if (usersPage.NextPageToken != null) + writer.WriteString("next_page_token", usersPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/UsersPartialPage.cs b/sdk/dotnet/Timr.Api/Model/UsersPartialPage.cs new file mode 100644 index 0000000..6101a3b --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/UsersPartialPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// UsersPartialPage + /// + public partial class UsersPartialPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public UsersPartialPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class UsersPartialPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class UsersPartialPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override UsersPartialPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class UsersPartialPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class UsersPartialPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class UsersPartialPage."); + + return new UsersPartialPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UsersPartialPage usersPartialPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, usersPartialPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, UsersPartialPage usersPartialPage, JsonSerializerOptions jsonSerializerOptions) + { + if (usersPartialPage.Data == null) + throw new ArgumentNullException(nameof(usersPartialPage.Data), "Property is required for class UsersPartialPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, usersPartialPage.Data, jsonSerializerOptions); + if (usersPartialPage.NextPageToken != null) + writer.WriteString("next_page_token", usersPartialPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/UsersSortColumn.cs b/sdk/dotnet/Timr.Api/Model/UsersSortColumn.cs new file mode 100644 index 0000000..a7b820e --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/UsersSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Users. `name` orders by last name, then first name. + /// + /// Sort property for Users. `name` orders by last name, then first name. + public enum UsersSortColumn + { + /// + /// Enum Name for value: name + /// + Name = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class UsersSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static UsersSortColumn FromString(string value) + { + if (value.Equals("name")) + return UsersSortColumn.Name; + + throw new NotImplementedException($"Could not convert value to type UsersSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static UsersSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("name")) + return UsersSortColumn.Name; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(UsersSortColumn value) + { + if (value == UsersSortColumn.Name) + return "name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class UsersSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override UsersSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + UsersSortColumn? result = rawValue == null + ? null + : UsersSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the UsersSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UsersSortColumn usersSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(UsersSortColumnValueConverter.ToJsonValue(usersSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class UsersSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a UsersSortColumn from the Json object + /// + /// + /// + /// + /// + public override UsersSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + UsersSortColumn? result = rawValue == null + ? null + : UsersSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the UsersSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, UsersSortColumn? usersSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(usersSortColumn.HasValue ? UsersSortColumnValueConverter.ToJsonValue(usersSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/VacationAccount.cs b/sdk/dotnet/Timr.Api/Model/VacationAccount.cs new file mode 100644 index 0000000..b634c98 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/VacationAccount.cs @@ -0,0 +1,236 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// VacationAccount + /// + public partial class VacationAccount : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// + public VacationAccount(VacationAccountDays vacationAccountDays) + { + VacationAccountDays = vacationAccountDays; + OnCreated(); + } + + /// + /// Initializes a new instance of the class. + /// + /// + public VacationAccount(VacationAccountMinutes vacationAccountMinutes) + { + VacationAccountMinutes = vacationAccountMinutes; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets VacationAccountDays + /// + public VacationAccountDays? VacationAccountDays { get; set; } + + /// + /// Gets or Sets VacationAccountMinutes + /// + public VacationAccountMinutes? VacationAccountMinutes { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VacationAccount {\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VacationAccountJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override VacationAccount Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option unit = default; + + VacationAccountDays? vacationAccountDays = null; + VacationAccountMinutes? vacationAccountMinutes = null; + + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName?.Equals("unit") ?? false) + { + string? discriminator = utf8JsonReaderDiscriminator.GetString(); + if (discriminator?.Equals("days") ?? false) + { + Utf8JsonReader utf8JsonReaderVacationAccountDays = utf8JsonReader; + vacationAccountDays = JsonSerializer.Deserialize(ref utf8JsonReaderVacationAccountDays, jsonSerializerOptions); + } + if (discriminator?.Equals("minutes") ?? false) + { + Utf8JsonReader utf8JsonReaderVacationAccountMinutes = utf8JsonReader; + vacationAccountMinutes = JsonSerializer.Deserialize(ref utf8JsonReaderVacationAccountMinutes, jsonSerializerOptions); + } + } + } + } + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "unit": + string? unitRawValue = utf8JsonReader.GetString(); + if (unitRawValue != null) + unit = new Option(VacationUnitValueConverter.FromStringOrDefault(unitRawValue)); + break; + default: + break; + } + } + } + + if (!unit.IsSet) + throw new ArgumentException("Property is required for class VacationAccount.", nameof(unit)); + + if (unit.IsSet && unit.Value == null) + throw new ArgumentNullException(nameof(unit), "Property is not nullable for class VacationAccount."); + + if (vacationAccountDays != null) + return new VacationAccount(vacationAccountDays); + + if (vacationAccountMinutes != null) + return new VacationAccount(vacationAccountMinutes); + + throw new JsonException(); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VacationAccount vacationAccount, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + if (vacationAccount.VacationAccountDays != null) + { + VacationAccountDaysJsonConverter vacationAccountDaysJsonConverter = (VacationAccountDaysJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(vacationAccount.VacationAccountDays.GetType())); + vacationAccountDaysJsonConverter.WriteProperties(writer, vacationAccount.VacationAccountDays, jsonSerializerOptions); + } + + if (vacationAccount.VacationAccountMinutes != null) + { + VacationAccountMinutesJsonConverter vacationAccountMinutesJsonConverter = (VacationAccountMinutesJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(vacationAccount.VacationAccountMinutes.GetType())); + vacationAccountMinutesJsonConverter.WriteProperties(writer, vacationAccount.VacationAccountMinutes, jsonSerializerOptions); + } + + WriteProperties(writer, vacationAccount, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VacationAccount vacationAccount, JsonSerializerOptions jsonSerializerOptions) + { + + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/VacationAccountBase.cs b/sdk/dotnet/Timr.Api/Model/VacationAccountBase.cs new file mode 100644 index 0000000..7d11578 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/VacationAccountBase.cs @@ -0,0 +1,164 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Members shared by every kind of vacation account, including the discriminator. + /// + public partial class VacationAccountBase : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// unit + [JsonConstructor] + public VacationAccountBase(VacationUnit unit) + { + Unit = unit; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Unit + /// + [JsonPropertyName("unit")] + public VacationUnit Unit { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VacationAccountBase {\n"); + sb.Append(" Unit: ").Append(Unit).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VacationAccountBaseJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override VacationAccountBase Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option unit = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "unit": + string? unitRawValue = utf8JsonReader.GetString(); + if (unitRawValue != null) + unit = new Option(VacationUnitValueConverter.FromStringOrDefault(unitRawValue)); + break; + default: + break; + } + } + } + + if (!unit.IsSet) + throw new ArgumentException("Property is required for class VacationAccountBase.", nameof(unit)); + + if (unit.IsSet && unit.Value == null) + throw new ArgumentNullException(nameof(unit), "Property is not nullable for class VacationAccountBase."); + + return new VacationAccountBase(unit.Value!.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VacationAccountBase vacationAccountBase, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, vacationAccountBase, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VacationAccountBase vacationAccountBase, JsonSerializerOptions jsonSerializerOptions) + { + var unitRawValue = VacationUnitValueConverter.ToJsonValue(vacationAccountBase.Unit); + writer.WriteString("unit", unitRawValue); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/VacationAccountDays.cs b/sdk/dotnet/Timr.Api/Model/VacationAccountDays.cs new file mode 100644 index 0000000..ab02153 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/VacationAccountDays.cs @@ -0,0 +1,272 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// VacationAccountDays + /// + public partial class VacationAccountDays : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// unit + /// vacation balance carried over from the previous vacation period, in days + /// vacation consumed in the current vacation period, in days + /// vacation newly granted in the current vacation period, in days + /// total vacation balance for the current vacation period, in days + [JsonConstructor] + public VacationAccountDays(VacationUnit unit, Option balanceLastPeriodDays = default, Option consumedDays = default, Option newDays = default, Option balanceTotalDays = default) + { + Unit = unit; + BalanceLastPeriodDaysOption = balanceLastPeriodDays; + ConsumedDaysOption = consumedDays; + NewDaysOption = newDays; + BalanceTotalDaysOption = balanceTotalDays; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Unit + /// + [JsonPropertyName("unit")] + public VacationUnit Unit { get; set; } + + /// + /// Used to track the state of BalanceLastPeriodDays + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BalanceLastPeriodDaysOption { get; private set; } + + /// + /// vacation balance carried over from the previous vacation period, in days + /// + /// vacation balance carried over from the previous vacation period, in days + [JsonPropertyName("balance_last_period_days")] + public decimal? BalanceLastPeriodDays { get { return this.BalanceLastPeriodDaysOption.Value; } set { this.BalanceLastPeriodDaysOption = new(value); } } + + /// + /// Used to track the state of ConsumedDays + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ConsumedDaysOption { get; private set; } + + /// + /// vacation consumed in the current vacation period, in days + /// + /// vacation consumed in the current vacation period, in days + [JsonPropertyName("consumed_days")] + public decimal? ConsumedDays { get { return this.ConsumedDaysOption.Value; } set { this.ConsumedDaysOption = new(value); } } + + /// + /// Used to track the state of NewDays + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NewDaysOption { get; private set; } + + /// + /// vacation newly granted in the current vacation period, in days + /// + /// vacation newly granted in the current vacation period, in days + [JsonPropertyName("new_days")] + public decimal? NewDays { get { return this.NewDaysOption.Value; } set { this.NewDaysOption = new(value); } } + + /// + /// Used to track the state of BalanceTotalDays + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BalanceTotalDaysOption { get; private set; } + + /// + /// total vacation balance for the current vacation period, in days + /// + /// total vacation balance for the current vacation period, in days + [JsonPropertyName("balance_total_days")] + public decimal? BalanceTotalDays { get { return this.BalanceTotalDaysOption.Value; } set { this.BalanceTotalDaysOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VacationAccountDays {\n"); + sb.Append(" Unit: ").Append(Unit).Append("\n"); + sb.Append(" BalanceLastPeriodDays: ").Append(BalanceLastPeriodDays).Append("\n"); + sb.Append(" ConsumedDays: ").Append(ConsumedDays).Append("\n"); + sb.Append(" NewDays: ").Append(NewDays).Append("\n"); + sb.Append(" BalanceTotalDays: ").Append(BalanceTotalDays).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VacationAccountDaysJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override VacationAccountDays Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option unit = default; + Option balanceLastPeriodDays = default; + Option consumedDays = default; + Option newDays = default; + Option balanceTotalDays = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "unit": + string? unitRawValue = utf8JsonReader.GetString(); + if (unitRawValue != null) + unit = new Option(VacationUnitValueConverter.FromStringOrDefault(unitRawValue)); + break; + case "balance_last_period_days": + balanceLastPeriodDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "consumed_days": + consumedDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "new_days": + newDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "balance_total_days": + balanceTotalDays = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + default: + break; + } + } + } + + if (!unit.IsSet) + throw new ArgumentException("Property is required for class VacationAccountDays.", nameof(unit)); + + if (unit.IsSet && unit.Value == null) + throw new ArgumentNullException(nameof(unit), "Property is not nullable for class VacationAccountDays."); + + return new VacationAccountDays(unit.Value!.Value!, balanceLastPeriodDays, consumedDays, newDays, balanceTotalDays); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VacationAccountDays vacationAccountDays, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, vacationAccountDays, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VacationAccountDays vacationAccountDays, JsonSerializerOptions jsonSerializerOptions) + { + var unitRawValue = VacationUnitValueConverter.ToJsonValue(vacationAccountDays.Unit); + writer.WriteString("unit", unitRawValue); + + if (vacationAccountDays.BalanceLastPeriodDaysOption.IsSet) + if (vacationAccountDays.BalanceLastPeriodDaysOption.Value != null) + writer.WriteNumber("balance_last_period_days", vacationAccountDays.BalanceLastPeriodDaysOption.Value!.Value); + else + writer.WriteNull("balance_last_period_days"); + + if (vacationAccountDays.ConsumedDaysOption.IsSet) + if (vacationAccountDays.ConsumedDaysOption.Value != null) + writer.WriteNumber("consumed_days", vacationAccountDays.ConsumedDaysOption.Value!.Value); + else + writer.WriteNull("consumed_days"); + + if (vacationAccountDays.NewDaysOption.IsSet) + if (vacationAccountDays.NewDaysOption.Value != null) + writer.WriteNumber("new_days", vacationAccountDays.NewDaysOption.Value!.Value); + else + writer.WriteNull("new_days"); + + if (vacationAccountDays.BalanceTotalDaysOption.IsSet) + if (vacationAccountDays.BalanceTotalDaysOption.Value != null) + writer.WriteNumber("balance_total_days", vacationAccountDays.BalanceTotalDaysOption.Value!.Value); + else + writer.WriteNull("balance_total_days"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/VacationAccountMinutes.cs b/sdk/dotnet/Timr.Api/Model/VacationAccountMinutes.cs new file mode 100644 index 0000000..c8f5666 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/VacationAccountMinutes.cs @@ -0,0 +1,272 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// VacationAccountMinutes + /// + public partial class VacationAccountMinutes : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// unit + /// vacation balance carried over from the previous vacation period, in minutes + /// vacation consumed in the current vacation period, in minutes + /// vacation newly granted in the current vacation period, in minutes + /// total vacation balance for the current vacation period, in minutes + [JsonConstructor] + public VacationAccountMinutes(VacationUnit unit, Option balanceLastPeriodMinutes = default, Option consumedMinutes = default, Option newMinutes = default, Option balanceTotalMinutes = default) + { + Unit = unit; + BalanceLastPeriodMinutesOption = balanceLastPeriodMinutes; + ConsumedMinutesOption = consumedMinutes; + NewMinutesOption = newMinutes; + BalanceTotalMinutesOption = balanceTotalMinutes; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Unit + /// + [JsonPropertyName("unit")] + public VacationUnit Unit { get; set; } + + /// + /// Used to track the state of BalanceLastPeriodMinutes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BalanceLastPeriodMinutesOption { get; private set; } + + /// + /// vacation balance carried over from the previous vacation period, in minutes + /// + /// vacation balance carried over from the previous vacation period, in minutes + [JsonPropertyName("balance_last_period_minutes")] + public decimal? BalanceLastPeriodMinutes { get { return this.BalanceLastPeriodMinutesOption.Value; } set { this.BalanceLastPeriodMinutesOption = new(value); } } + + /// + /// Used to track the state of ConsumedMinutes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ConsumedMinutesOption { get; private set; } + + /// + /// vacation consumed in the current vacation period, in minutes + /// + /// vacation consumed in the current vacation period, in minutes + [JsonPropertyName("consumed_minutes")] + public decimal? ConsumedMinutes { get { return this.ConsumedMinutesOption.Value; } set { this.ConsumedMinutesOption = new(value); } } + + /// + /// Used to track the state of NewMinutes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NewMinutesOption { get; private set; } + + /// + /// vacation newly granted in the current vacation period, in minutes + /// + /// vacation newly granted in the current vacation period, in minutes + [JsonPropertyName("new_minutes")] + public decimal? NewMinutes { get { return this.NewMinutesOption.Value; } set { this.NewMinutesOption = new(value); } } + + /// + /// Used to track the state of BalanceTotalMinutes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option BalanceTotalMinutesOption { get; private set; } + + /// + /// total vacation balance for the current vacation period, in minutes + /// + /// total vacation balance for the current vacation period, in minutes + [JsonPropertyName("balance_total_minutes")] + public decimal? BalanceTotalMinutes { get { return this.BalanceTotalMinutesOption.Value; } set { this.BalanceTotalMinutesOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VacationAccountMinutes {\n"); + sb.Append(" Unit: ").Append(Unit).Append("\n"); + sb.Append(" BalanceLastPeriodMinutes: ").Append(BalanceLastPeriodMinutes).Append("\n"); + sb.Append(" ConsumedMinutes: ").Append(ConsumedMinutes).Append("\n"); + sb.Append(" NewMinutes: ").Append(NewMinutes).Append("\n"); + sb.Append(" BalanceTotalMinutes: ").Append(BalanceTotalMinutes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VacationAccountMinutesJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override VacationAccountMinutes Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option unit = default; + Option balanceLastPeriodMinutes = default; + Option consumedMinutes = default; + Option newMinutes = default; + Option balanceTotalMinutes = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "unit": + string? unitRawValue = utf8JsonReader.GetString(); + if (unitRawValue != null) + unit = new Option(VacationUnitValueConverter.FromStringOrDefault(unitRawValue)); + break; + case "balance_last_period_minutes": + balanceLastPeriodMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "consumed_minutes": + consumedMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "new_minutes": + newMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + case "balance_total_minutes": + balanceTotalMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + break; + default: + break; + } + } + } + + if (!unit.IsSet) + throw new ArgumentException("Property is required for class VacationAccountMinutes.", nameof(unit)); + + if (unit.IsSet && unit.Value == null) + throw new ArgumentNullException(nameof(unit), "Property is not nullable for class VacationAccountMinutes."); + + return new VacationAccountMinutes(unit.Value!.Value!, balanceLastPeriodMinutes, consumedMinutes, newMinutes, balanceTotalMinutes); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VacationAccountMinutes vacationAccountMinutes, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, vacationAccountMinutes, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VacationAccountMinutes vacationAccountMinutes, JsonSerializerOptions jsonSerializerOptions) + { + var unitRawValue = VacationUnitValueConverter.ToJsonValue(vacationAccountMinutes.Unit); + writer.WriteString("unit", unitRawValue); + + if (vacationAccountMinutes.BalanceLastPeriodMinutesOption.IsSet) + if (vacationAccountMinutes.BalanceLastPeriodMinutesOption.Value != null) + writer.WriteNumber("balance_last_period_minutes", vacationAccountMinutes.BalanceLastPeriodMinutesOption.Value!.Value); + else + writer.WriteNull("balance_last_period_minutes"); + + if (vacationAccountMinutes.ConsumedMinutesOption.IsSet) + if (vacationAccountMinutes.ConsumedMinutesOption.Value != null) + writer.WriteNumber("consumed_minutes", vacationAccountMinutes.ConsumedMinutesOption.Value!.Value); + else + writer.WriteNull("consumed_minutes"); + + if (vacationAccountMinutes.NewMinutesOption.IsSet) + if (vacationAccountMinutes.NewMinutesOption.Value != null) + writer.WriteNumber("new_minutes", vacationAccountMinutes.NewMinutesOption.Value!.Value); + else + writer.WriteNull("new_minutes"); + + if (vacationAccountMinutes.BalanceTotalMinutesOption.IsSet) + if (vacationAccountMinutes.BalanceTotalMinutesOption.Value != null) + writer.WriteNumber("balance_total_minutes", vacationAccountMinutes.BalanceTotalMinutesOption.Value!.Value); + else + writer.WriteNull("balance_total_minutes"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/VacationUnit.cs b/sdk/dotnet/Timr.Api/Model/VacationUnit.cs new file mode 100644 index 0000000..d1db2b3 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/VacationUnit.cs @@ -0,0 +1,177 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Unit a vacation entitlement is expressed in. + /// + /// Unit a vacation entitlement is expressed in. + public enum VacationUnit + { + /// + /// Enum Days for value: days + /// + Days = 1, + + /// + /// Enum Minutes for value: minutes + /// + Minutes = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class VacationUnitValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static VacationUnit FromString(string value) + { + if (value.Equals("days")) + return VacationUnit.Days; + + if (value.Equals("minutes")) + return VacationUnit.Minutes; + + throw new NotImplementedException($"Could not convert value to type VacationUnit: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static VacationUnit? FromStringOrDefault(string value) + { + if (value.Equals("days")) + return VacationUnit.Days; + + if (value.Equals("minutes")) + return VacationUnit.Minutes; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(VacationUnit value) + { + if (value == VacationUnit.Days) + return "days"; + + if (value == VacationUnit.Minutes) + return "minutes"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class VacationUnitJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override VacationUnit Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + VacationUnit? result = rawValue == null + ? null + : VacationUnitValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the VacationUnit to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VacationUnit vacationUnit, JsonSerializerOptions options) + { + writer.WriteStringValue(VacationUnitValueConverter.ToJsonValue(vacationUnit).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class VacationUnitNullableJsonConverter : JsonConverter + { + /// + /// Returns a VacationUnit from the Json object + /// + /// + /// + /// + /// + public override VacationUnit? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + VacationUnit? result = rawValue == null + ? null + : VacationUnitValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the VacationUnit to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VacationUnit? vacationUnit, JsonSerializerOptions options) + { + writer.WriteStringValue(vacationUnit.HasValue ? VacationUnitValueConverter.ToJsonValue(vacationUnit.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/VenuePartial.cs b/sdk/dotnet/Timr.Api/Model/VenuePartial.cs new file mode 100644 index 0000000..c6d76d7 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/VenuePartial.cs @@ -0,0 +1,365 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// VenuePartial + /// + public partial class VenuePartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// city + /// zipCode + /// street + /// streetNumber + /// country + /// Latitude in decimal degrees. + /// Longitude in decimal degrees. + [JsonConstructor] + public VenuePartial(string id, string name, string city, string zipCode, string street, string streetNumber, string country, Option lat = default, Option lon = default) + { + Id = id; + Name = name; + City = city; + ZipCode = zipCode; + Street = street; + StreetNumber = streetNumber; + Country = country; + LatOption = lat; + LonOption = lon; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets City + /// + [JsonPropertyName("city")] + public string City { get; set; } + + /// + /// Gets or Sets ZipCode + /// + [JsonPropertyName("zip_code")] + public string ZipCode { get; set; } + + /// + /// Gets or Sets Street + /// + [JsonPropertyName("street")] + public string Street { get; set; } + + /// + /// Gets or Sets StreetNumber + /// + [JsonPropertyName("street_number")] + public string StreetNumber { get; set; } + + /// + /// Gets or Sets Country + /// + [JsonPropertyName("country")] + public string Country { get; set; } + + /// + /// Used to track the state of Lat + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LatOption { get; private set; } + + /// + /// Latitude in decimal degrees. + /// + /// Latitude in decimal degrees. + /* 48.2455964 */ + [JsonPropertyName("lat")] + public float? Lat { get { return this.LatOption.Value; } set { this.LatOption = new(value); } } + + /// + /// Used to track the state of Lon + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option LonOption { get; private set; } + + /// + /// Longitude in decimal degrees. + /// + /// Longitude in decimal degrees. + /* 13.0543811 */ + [JsonPropertyName("lon")] + public float? Lon { get { return this.LonOption.Value; } set { this.LonOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class VenuePartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" City: ").Append(City).Append("\n"); + sb.Append(" ZipCode: ").Append(ZipCode).Append("\n"); + sb.Append(" Street: ").Append(Street).Append("\n"); + sb.Append(" StreetNumber: ").Append(StreetNumber).Append("\n"); + sb.Append(" Country: ").Append(Country).Append("\n"); + sb.Append(" Lat: ").Append(Lat).Append("\n"); + sb.Append(" Lon: ").Append(Lon).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class VenuePartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override VenuePartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option city = default; + Option zipCode = default; + Option street = default; + Option streetNumber = default; + Option country = default; + Option lat = default; + Option lon = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "city": + city = new Option(utf8JsonReader.GetString()!); + break; + case "zip_code": + zipCode = new Option(utf8JsonReader.GetString()!); + break; + case "street": + street = new Option(utf8JsonReader.GetString()!); + break; + case "street_number": + streetNumber = new Option(utf8JsonReader.GetString()!); + break; + case "country": + country = new Option(utf8JsonReader.GetString()!); + break; + case "lat": + lat = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + case "lon": + lon = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class VenuePartial.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class VenuePartial.", nameof(name)); + + if (!city.IsSet) + throw new ArgumentException("Property is required for class VenuePartial.", nameof(city)); + + if (!zipCode.IsSet) + throw new ArgumentException("Property is required for class VenuePartial.", nameof(zipCode)); + + if (!street.IsSet) + throw new ArgumentException("Property is required for class VenuePartial.", nameof(street)); + + if (!streetNumber.IsSet) + throw new ArgumentException("Property is required for class VenuePartial.", nameof(streetNumber)); + + if (!country.IsSet) + throw new ArgumentException("Property is required for class VenuePartial.", nameof(country)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class VenuePartial."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class VenuePartial."); + + if (city.IsSet && city.Value == null) + throw new ArgumentNullException(nameof(city), "Property is not nullable for class VenuePartial."); + + if (zipCode.IsSet && zipCode.Value == null) + throw new ArgumentNullException(nameof(zipCode), "Property is not nullable for class VenuePartial."); + + if (street.IsSet && street.Value == null) + throw new ArgumentNullException(nameof(street), "Property is not nullable for class VenuePartial."); + + if (streetNumber.IsSet && streetNumber.Value == null) + throw new ArgumentNullException(nameof(streetNumber), "Property is not nullable for class VenuePartial."); + + if (country.IsSet && country.Value == null) + throw new ArgumentNullException(nameof(country), "Property is not nullable for class VenuePartial."); + + if (lat.IsSet && lat.Value == null) + throw new ArgumentNullException(nameof(lat), "Property is not nullable for class VenuePartial."); + + if (lon.IsSet && lon.Value == null) + throw new ArgumentNullException(nameof(lon), "Property is not nullable for class VenuePartial."); + + return new VenuePartial(id.Value!, name.Value!, city.Value!, zipCode.Value!, street.Value!, streetNumber.Value!, country.Value!, lat, lon); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, VenuePartial venuePartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, venuePartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, VenuePartial venuePartial, JsonSerializerOptions jsonSerializerOptions) + { + if (venuePartial.Id == null) + throw new ArgumentNullException(nameof(venuePartial.Id), "Property is required for class VenuePartial."); + + if (venuePartial.Name == null) + throw new ArgumentNullException(nameof(venuePartial.Name), "Property is required for class VenuePartial."); + + if (venuePartial.City == null) + throw new ArgumentNullException(nameof(venuePartial.City), "Property is required for class VenuePartial."); + + if (venuePartial.ZipCode == null) + throw new ArgumentNullException(nameof(venuePartial.ZipCode), "Property is required for class VenuePartial."); + + if (venuePartial.Street == null) + throw new ArgumentNullException(nameof(venuePartial.Street), "Property is required for class VenuePartial."); + + if (venuePartial.StreetNumber == null) + throw new ArgumentNullException(nameof(venuePartial.StreetNumber), "Property is required for class VenuePartial."); + + if (venuePartial.Country == null) + throw new ArgumentNullException(nameof(venuePartial.Country), "Property is required for class VenuePartial."); + + writer.WriteString("id", venuePartial.Id); + + writer.WriteString("name", venuePartial.Name); + + writer.WriteString("city", venuePartial.City); + + writer.WriteString("zip_code", venuePartial.ZipCode); + + writer.WriteString("street", venuePartial.Street); + + writer.WriteString("street_number", venuePartial.StreetNumber); + + writer.WriteString("country", venuePartial.Country); + + if (venuePartial.LatOption.IsSet) + writer.WriteNumber("lat", venuePartial.LatOption.Value!.Value); + + if (venuePartial.LonOption.IsSet) + writer.WriteNumber("lon", venuePartial.LonOption.Value!.Value); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/Waypoint.cs b/sdk/dotnet/Timr.Api/Model/Waypoint.cs new file mode 100644 index 0000000..62cb2d2 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/Waypoint.cs @@ -0,0 +1,182 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Waypoint + /// + public partial class Waypoint : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// lat + /// lon + [JsonConstructor] + public Waypoint(double lat, double lon) + { + Lat = lat; + Lon = lon; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Lat + /// + [JsonPropertyName("lat")] + public double Lat { get; set; } + + /// + /// Gets or Sets Lon + /// + [JsonPropertyName("lon")] + public double Lon { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class Waypoint {\n"); + sb.Append(" Lat: ").Append(Lat).Append("\n"); + sb.Append(" Lon: ").Append(Lon).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WaypointJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override Waypoint Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option lat = default; + Option lon = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "lat": + lat = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (double?)null : utf8JsonReader.GetDouble()); + break; + case "lon": + lon = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (double?)null : utf8JsonReader.GetDouble()); + break; + default: + break; + } + } + } + + if (!lat.IsSet) + throw new ArgumentException("Property is required for class Waypoint.", nameof(lat)); + + if (!lon.IsSet) + throw new ArgumentException("Property is required for class Waypoint.", nameof(lon)); + + if (lat.IsSet && lat.Value == null) + throw new ArgumentNullException(nameof(lat), "Property is not nullable for class Waypoint."); + + if (lon.IsSet && lon.Value == null) + throw new ArgumentNullException(nameof(lon), "Property is not nullable for class Waypoint."); + + return new Waypoint(lat.Value!.Value!, lon.Value!.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, Waypoint waypoint, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, waypoint, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, Waypoint waypoint, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteNumber("lat", waypoint.Lat); + + writer.WriteNumber("lon", waypoint.Lon); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkScheduleModel.cs b/sdk/dotnet/Timr.Api/Model/WorkScheduleModel.cs new file mode 100644 index 0000000..f17e75b --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkScheduleModel.cs @@ -0,0 +1,263 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// The weekday targets a user is measured against: `weeks` holds the layout, `type` selects the calculation mode, and `working_time_rules` the recording constraints. + /// + public partial class WorkScheduleModel : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id + /// name + /// working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks) + /// for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name + /// workingTimeRules + [JsonConstructor] + public WorkScheduleModel(string id, string name, WorkScheduleModelType type, List weeks, WorkingTimeRules? workingTimeRules = default) + { + Id = id; + Name = name; + Type = type; + Weeks = weeks; + WorkingTimeRules = workingTimeRules; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks) + /// + /// working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks) + [JsonPropertyName("type")] + public WorkScheduleModelType Type { get; set; } + + /// + /// Gets or Sets Id + /// + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + /* full-time */ + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name + /// + /// for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name + [JsonPropertyName("weeks")] + public List Weeks { get; set; } + + /// + /// Gets or Sets WorkingTimeRules + /// + [JsonPropertyName("working_time_rules")] + public WorkingTimeRules? WorkingTimeRules { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkScheduleModel {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Weeks: ").Append(Weeks).Append("\n"); + sb.Append(" WorkingTimeRules: ").Append(WorkingTimeRules).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkScheduleModelJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkScheduleModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option type = default; + Option?> weeks = default; + Option workingTimeRules = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "type": + string? typeRawValue = utf8JsonReader.GetString(); + if (typeRawValue != null) + type = new Option(WorkScheduleModelTypeValueConverter.FromStringOrDefault(typeRawValue)); + break; + case "weeks": + weeks = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "working_time_rules": + workingTimeRules = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModel.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModel.", nameof(name)); + + if (!type.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModel.", nameof(type)); + + if (!weeks.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModel.", nameof(weeks)); + + if (!workingTimeRules.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModel.", nameof(workingTimeRules)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class WorkScheduleModel."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class WorkScheduleModel."); + + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class WorkScheduleModel."); + + if (weeks.IsSet && weeks.Value == null) + throw new ArgumentNullException(nameof(weeks), "Property is not nullable for class WorkScheduleModel."); + + return new WorkScheduleModel(id.Value!, name.Value!, type.Value!.Value!, weeks.Value!, workingTimeRules.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkScheduleModel workScheduleModel, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workScheduleModel, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkScheduleModel workScheduleModel, JsonSerializerOptions jsonSerializerOptions) + { + if (workScheduleModel.Id == null) + throw new ArgumentNullException(nameof(workScheduleModel.Id), "Property is required for class WorkScheduleModel."); + + if (workScheduleModel.Name == null) + throw new ArgumentNullException(nameof(workScheduleModel.Name), "Property is required for class WorkScheduleModel."); + + if (workScheduleModel.Weeks == null) + throw new ArgumentNullException(nameof(workScheduleModel.Weeks), "Property is required for class WorkScheduleModel."); + + writer.WriteString("id", workScheduleModel.Id); + + writer.WriteString("name", workScheduleModel.Name); + + var typeRawValue = WorkScheduleModelTypeValueConverter.ToJsonValue(workScheduleModel.Type); + writer.WriteString("type", typeRawValue); + + writer.WritePropertyName("weeks"); + JsonSerializer.Serialize(writer, workScheduleModel.Weeks, jsonSerializerOptions); + if (workScheduleModel.WorkingTimeRules != null) + { + writer.WritePropertyName("working_time_rules"); + JsonSerializer.Serialize(writer, workScheduleModel.WorkingTimeRules, jsonSerializerOptions); + } + else + writer.WriteNull("working_time_rules"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkScheduleModelPartial.cs b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelPartial.cs new file mode 100644 index 0000000..67cf15d --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelPartial.cs @@ -0,0 +1,190 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkScheduleModelPartial + /// + public partial class WorkScheduleModelPartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + [JsonConstructor] + public WorkScheduleModelPartial(string id, string name) + { + Id = id; + Name = name; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + /* full-time */ + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkScheduleModelPartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkScheduleModelPartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkScheduleModelPartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelPartial.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelPartial.", nameof(name)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class WorkScheduleModelPartial."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class WorkScheduleModelPartial."); + + return new WorkScheduleModelPartial(id.Value!, name.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkScheduleModelPartial workScheduleModelPartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workScheduleModelPartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkScheduleModelPartial workScheduleModelPartial, JsonSerializerOptions jsonSerializerOptions) + { + if (workScheduleModelPartial.Id == null) + throw new ArgumentNullException(nameof(workScheduleModelPartial.Id), "Property is required for class WorkScheduleModelPartial."); + + if (workScheduleModelPartial.Name == null) + throw new ArgumentNullException(nameof(workScheduleModelPartial.Name), "Property is required for class WorkScheduleModelPartial."); + + writer.WriteString("id", workScheduleModelPartial.Id); + + writer.WriteString("name", workScheduleModelPartial.Name); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkScheduleModelSortColumn.cs b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelSortColumn.cs new file mode 100644 index 0000000..64d37b1 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Work Schedule Models. + /// + /// Sort property for Work Schedule Models. + public enum WorkScheduleModelSortColumn + { + /// + /// Enum Name for value: name + /// + Name = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class WorkScheduleModelSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static WorkScheduleModelSortColumn FromString(string value) + { + if (value.Equals("name")) + return WorkScheduleModelSortColumn.Name; + + throw new NotImplementedException($"Could not convert value to type WorkScheduleModelSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static WorkScheduleModelSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("name")) + return WorkScheduleModelSortColumn.Name; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(WorkScheduleModelSortColumn value) + { + if (value == WorkScheduleModelSortColumn.Name) + return "name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class WorkScheduleModelSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override WorkScheduleModelSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkScheduleModelSortColumn? result = rawValue == null + ? null + : WorkScheduleModelSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkScheduleModelSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkScheduleModelSortColumn workScheduleModelSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(WorkScheduleModelSortColumnValueConverter.ToJsonValue(workScheduleModelSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class WorkScheduleModelSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a WorkScheduleModelSortColumn from the Json object + /// + /// + /// + /// + /// + public override WorkScheduleModelSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkScheduleModelSortColumn? result = rawValue == null + ? null + : WorkScheduleModelSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkScheduleModelSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkScheduleModelSortColumn? workScheduleModelSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(workScheduleModelSortColumn.HasValue ? WorkScheduleModelSortColumnValueConverter.ToJsonValue(workScheduleModelSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkScheduleModelType.cs b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelType.cs new file mode 100644 index 0000000..8677c60 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelType.cs @@ -0,0 +1,177 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// How the target working time of the model is defined. + /// + /// How the target working time of the model is defined. + public enum WorkScheduleModelType + { + /// + /// Enum DailyTargetHours for value: daily_target_hours + /// + DailyTargetHours = 1, + + /// + /// Enum NormalWorkingTime for value: normal_working_time + /// + NormalWorkingTime = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class WorkScheduleModelTypeValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static WorkScheduleModelType FromString(string value) + { + if (value.Equals("daily_target_hours")) + return WorkScheduleModelType.DailyTargetHours; + + if (value.Equals("normal_working_time")) + return WorkScheduleModelType.NormalWorkingTime; + + throw new NotImplementedException($"Could not convert value to type WorkScheduleModelType: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static WorkScheduleModelType? FromStringOrDefault(string value) + { + if (value.Equals("daily_target_hours")) + return WorkScheduleModelType.DailyTargetHours; + + if (value.Equals("normal_working_time")) + return WorkScheduleModelType.NormalWorkingTime; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(WorkScheduleModelType value) + { + if (value == WorkScheduleModelType.DailyTargetHours) + return "daily_target_hours"; + + if (value == WorkScheduleModelType.NormalWorkingTime) + return "normal_working_time"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class WorkScheduleModelTypeJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override WorkScheduleModelType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkScheduleModelType? result = rawValue == null + ? null + : WorkScheduleModelTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkScheduleModelType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkScheduleModelType workScheduleModelType, JsonSerializerOptions options) + { + writer.WriteStringValue(WorkScheduleModelTypeValueConverter.ToJsonValue(workScheduleModelType).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class WorkScheduleModelTypeNullableJsonConverter : JsonConverter + { + /// + /// Returns a WorkScheduleModelType from the Json object + /// + /// + /// + /// + /// + public override WorkScheduleModelType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkScheduleModelType? result = rawValue == null + ? null + : WorkScheduleModelTypeValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkScheduleModelType to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkScheduleModelType? workScheduleModelType, JsonSerializerOptions options) + { + writer.WriteStringValue(workScheduleModelType.HasValue ? WorkScheduleModelTypeValueConverter.ToJsonValue(workScheduleModelType.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkScheduleModelWeek.cs b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelWeek.cs new file mode 100644 index 0000000..e94c2e7 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelWeek.cs @@ -0,0 +1,387 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkScheduleModelWeek + /// + public partial class WorkScheduleModelWeek : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// value in minutes + /// monday + /// tuesday + /// wednesday + /// thursday + /// friday + /// saturday + /// sunday + /// index of the week in alternating_weeks models (0-based); omitted for fixed_week models + /// display name of the week in alternating_weeks models; omitted for fixed_week models + [JsonConstructor] + public WorkScheduleModelWeek(long targetDurationWeeklyMinutes, DailyWorkSchedule monday, DailyWorkSchedule tuesday, DailyWorkSchedule wednesday, DailyWorkSchedule thursday, DailyWorkSchedule friday, DailyWorkSchedule saturday, DailyWorkSchedule sunday, Option weekNumber = default, Option name = default) + { + TargetDurationWeeklyMinutes = targetDurationWeeklyMinutes; + Monday = monday; + Tuesday = tuesday; + Wednesday = wednesday; + Thursday = thursday; + Friday = friday; + Saturday = saturday; + Sunday = sunday; + WeekNumberOption = weekNumber; + NameOption = name; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// value in minutes + /// + /// value in minutes + /* 2400 */ + [JsonPropertyName("target_duration_weekly_minutes")] + public long TargetDurationWeeklyMinutes { get; set; } + + /// + /// Gets or Sets Monday + /// + [JsonPropertyName("monday")] + public DailyWorkSchedule Monday { get; set; } + + /// + /// Gets or Sets Tuesday + /// + [JsonPropertyName("tuesday")] + public DailyWorkSchedule Tuesday { get; set; } + + /// + /// Gets or Sets Wednesday + /// + [JsonPropertyName("wednesday")] + public DailyWorkSchedule Wednesday { get; set; } + + /// + /// Gets or Sets Thursday + /// + [JsonPropertyName("thursday")] + public DailyWorkSchedule Thursday { get; set; } + + /// + /// Gets or Sets Friday + /// + [JsonPropertyName("friday")] + public DailyWorkSchedule Friday { get; set; } + + /// + /// Gets or Sets Saturday + /// + [JsonPropertyName("saturday")] + public DailyWorkSchedule Saturday { get; set; } + + /// + /// Gets or Sets Sunday + /// + [JsonPropertyName("sunday")] + public DailyWorkSchedule Sunday { get; set; } + + /// + /// Used to track the state of WeekNumber + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option WeekNumberOption { get; private set; } + + /// + /// index of the week in alternating_weeks models (0-based); omitted for fixed_week models + /// + /// index of the week in alternating_weeks models (0-based); omitted for fixed_week models + /* 0 */ + [JsonPropertyName("week_number")] + public int? WeekNumber { get { return this.WeekNumberOption.Value; } set { this.WeekNumberOption = new(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + + /// + /// display name of the week in alternating_weeks models; omitted for fixed_week models + /// + /// display name of the week in alternating_weeks models; omitted for fixed_week models + /* Week A */ + [JsonPropertyName("name")] + public string? Name { get { return this.NameOption.Value; } set { this.NameOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkScheduleModelWeek {\n"); + sb.Append(" TargetDurationWeeklyMinutes: ").Append(TargetDurationWeeklyMinutes).Append("\n"); + sb.Append(" Monday: ").Append(Monday).Append("\n"); + sb.Append(" Tuesday: ").Append(Tuesday).Append("\n"); + sb.Append(" Wednesday: ").Append(Wednesday).Append("\n"); + sb.Append(" Thursday: ").Append(Thursday).Append("\n"); + sb.Append(" Friday: ").Append(Friday).Append("\n"); + sb.Append(" Saturday: ").Append(Saturday).Append("\n"); + sb.Append(" Sunday: ").Append(Sunday).Append("\n"); + sb.Append(" WeekNumber: ").Append(WeekNumber).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkScheduleModelWeekJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkScheduleModelWeek Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option targetDurationWeeklyMinutes = default; + Option monday = default; + Option tuesday = default; + Option wednesday = default; + Option thursday = default; + Option friday = default; + Option saturday = default; + Option sunday = default; + Option weekNumber = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "target_duration_weekly_minutes": + targetDurationWeeklyMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (long?)null : utf8JsonReader.GetInt64()); + break; + case "monday": + monday = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "tuesday": + tuesday = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "wednesday": + wednesday = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "thursday": + thursday = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "friday": + friday = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "saturday": + saturday = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "sunday": + sunday = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "week_number": + weekNumber = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "name": + name = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!targetDurationWeeklyMinutes.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelWeek.", nameof(targetDurationWeeklyMinutes)); + + if (!monday.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelWeek.", nameof(monday)); + + if (!tuesday.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelWeek.", nameof(tuesday)); + + if (!wednesday.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelWeek.", nameof(wednesday)); + + if (!thursday.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelWeek.", nameof(thursday)); + + if (!friday.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelWeek.", nameof(friday)); + + if (!saturday.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelWeek.", nameof(saturday)); + + if (!sunday.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelWeek.", nameof(sunday)); + + if (targetDurationWeeklyMinutes.IsSet && targetDurationWeeklyMinutes.Value == null) + throw new ArgumentNullException(nameof(targetDurationWeeklyMinutes), "Property is not nullable for class WorkScheduleModelWeek."); + + if (monday.IsSet && monday.Value == null) + throw new ArgumentNullException(nameof(monday), "Property is not nullable for class WorkScheduleModelWeek."); + + if (tuesday.IsSet && tuesday.Value == null) + throw new ArgumentNullException(nameof(tuesday), "Property is not nullable for class WorkScheduleModelWeek."); + + if (wednesday.IsSet && wednesday.Value == null) + throw new ArgumentNullException(nameof(wednesday), "Property is not nullable for class WorkScheduleModelWeek."); + + if (thursday.IsSet && thursday.Value == null) + throw new ArgumentNullException(nameof(thursday), "Property is not nullable for class WorkScheduleModelWeek."); + + if (friday.IsSet && friday.Value == null) + throw new ArgumentNullException(nameof(friday), "Property is not nullable for class WorkScheduleModelWeek."); + + if (saturday.IsSet && saturday.Value == null) + throw new ArgumentNullException(nameof(saturday), "Property is not nullable for class WorkScheduleModelWeek."); + + if (sunday.IsSet && sunday.Value == null) + throw new ArgumentNullException(nameof(sunday), "Property is not nullable for class WorkScheduleModelWeek."); + + return new WorkScheduleModelWeek(targetDurationWeeklyMinutes.Value!.Value!, monday.Value!, tuesday.Value!, wednesday.Value!, thursday.Value!, friday.Value!, saturday.Value!, sunday.Value!, weekNumber, name); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkScheduleModelWeek workScheduleModelWeek, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workScheduleModelWeek, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkScheduleModelWeek workScheduleModelWeek, JsonSerializerOptions jsonSerializerOptions) + { + if (workScheduleModelWeek.Monday == null) + throw new ArgumentNullException(nameof(workScheduleModelWeek.Monday), "Property is required for class WorkScheduleModelWeek."); + + if (workScheduleModelWeek.Tuesday == null) + throw new ArgumentNullException(nameof(workScheduleModelWeek.Tuesday), "Property is required for class WorkScheduleModelWeek."); + + if (workScheduleModelWeek.Wednesday == null) + throw new ArgumentNullException(nameof(workScheduleModelWeek.Wednesday), "Property is required for class WorkScheduleModelWeek."); + + if (workScheduleModelWeek.Thursday == null) + throw new ArgumentNullException(nameof(workScheduleModelWeek.Thursday), "Property is required for class WorkScheduleModelWeek."); + + if (workScheduleModelWeek.Friday == null) + throw new ArgumentNullException(nameof(workScheduleModelWeek.Friday), "Property is required for class WorkScheduleModelWeek."); + + if (workScheduleModelWeek.Saturday == null) + throw new ArgumentNullException(nameof(workScheduleModelWeek.Saturday), "Property is required for class WorkScheduleModelWeek."); + + if (workScheduleModelWeek.Sunday == null) + throw new ArgumentNullException(nameof(workScheduleModelWeek.Sunday), "Property is required for class WorkScheduleModelWeek."); + + writer.WriteNumber("target_duration_weekly_minutes", workScheduleModelWeek.TargetDurationWeeklyMinutes); + + writer.WritePropertyName("monday"); + JsonSerializer.Serialize(writer, workScheduleModelWeek.Monday, jsonSerializerOptions); + writer.WritePropertyName("tuesday"); + JsonSerializer.Serialize(writer, workScheduleModelWeek.Tuesday, jsonSerializerOptions); + writer.WritePropertyName("wednesday"); + JsonSerializer.Serialize(writer, workScheduleModelWeek.Wednesday, jsonSerializerOptions); + writer.WritePropertyName("thursday"); + JsonSerializer.Serialize(writer, workScheduleModelWeek.Thursday, jsonSerializerOptions); + writer.WritePropertyName("friday"); + JsonSerializer.Serialize(writer, workScheduleModelWeek.Friday, jsonSerializerOptions); + writer.WritePropertyName("saturday"); + JsonSerializer.Serialize(writer, workScheduleModelWeek.Saturday, jsonSerializerOptions); + writer.WritePropertyName("sunday"); + JsonSerializer.Serialize(writer, workScheduleModelWeek.Sunday, jsonSerializerOptions); + if (workScheduleModelWeek.WeekNumberOption.IsSet) + if (workScheduleModelWeek.WeekNumberOption.Value != null) + writer.WriteNumber("week_number", workScheduleModelWeek.WeekNumberOption.Value!.Value); + else + writer.WriteNull("week_number"); + + if (workScheduleModelWeek.NameOption.IsSet) + if (workScheduleModelWeek.NameOption.Value != null) + writer.WriteString("name", workScheduleModelWeek.Name); + else + writer.WriteNull("name"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkScheduleModelsPage.cs b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelsPage.cs new file mode 100644 index 0000000..6a9c76e --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkScheduleModelsPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkScheduleModelsPage + /// + public partial class WorkScheduleModelsPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public WorkScheduleModelsPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkScheduleModelsPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkScheduleModelsPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkScheduleModelsPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelsPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class WorkScheduleModelsPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class WorkScheduleModelsPage."); + + return new WorkScheduleModelsPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkScheduleModelsPage workScheduleModelsPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workScheduleModelsPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkScheduleModelsPage workScheduleModelsPage, JsonSerializerOptions jsonSerializerOptions) + { + if (workScheduleModelsPage.Data == null) + throw new ArgumentNullException(nameof(workScheduleModelsPage.Data), "Property is required for class WorkScheduleModelsPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, workScheduleModelsPage.Data, jsonSerializerOptions); + if (workScheduleModelsPage.NextPageToken != null) + writer.WriteString("next_page_token", workScheduleModelsPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTime.cs b/sdk/dotnet/Timr.Api/Model/WorkingTime.cs new file mode 100644 index 0000000..9eead66 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTime.cs @@ -0,0 +1,626 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// One continuous stretch from `start` to `end`, classified by its `working_time_type`. Attendance entries carry `break_times`, locations and the platform they were recorded on; an entry derived from a multi-day absence links back to its `working_time_date_span`. + /// + public partial class WorkingTime : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// RFC 3339 date-time (ISO-8601) + /// Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + /// breakTimes + /// changed + /// user + /// workingTimeType + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// status + /// RFC 3339 date-time (ISO-8601) + /// duration + /// notes + /// workingTimeDateSpan + /// startLocation + /// endLocation + /// startPlatform + /// endPlatform + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// metadata + [JsonConstructor] + public WorkingTime(string id, DateTimeOffset start, int breakTimeTotalMinutes, List breakTimes, bool changed, UserPartial user, WorkingTimeTypePartial workingTimeType, DateTimeOffset lastModified, WorkingTimeStatus status, DateTimeOffset? end = default, Duration? duration = default, string? notes = default, WorkingTimeDateSpanPartial? workingTimeDateSpan = default, Location? startLocation = default, Location? endLocation = default, Platform? startPlatform = default, Platform? endPlatform = default, UserPartial? lastModifiedBy = default, Option?> metadata = default) + { + Id = id; + Start = start; + BreakTimeTotalMinutes = breakTimeTotalMinutes; + BreakTimes = breakTimes; + Changed = changed; + User = user; + WorkingTimeType = workingTimeType; + LastModified = lastModified; + Status = status; + End = end; + Duration = duration; + Notes = notes; + WorkingTimeDateSpan = workingTimeDateSpan; + StartLocation = startLocation; + EndLocation = endLocation; + StartPlatform = startPlatform; + EndPlatform = endPlatform; + LastModifiedBy = lastModifiedBy; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public WorkingTimeStatus Status { get; set; } + + /// + /// Gets or Sets StartPlatform + /// + [JsonPropertyName("start_platform")] + public Platform? StartPlatform { get; set; } + + /// + /// Gets or Sets EndPlatform + /// + [JsonPropertyName("end_platform")] + public Platform? EndPlatform { get; set; } + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + /* 074e7048-9097-11eb-a8b3-0242ac130003 */ + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset Start { get; set; } + + /// + /// Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + /// + /// Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + [JsonPropertyName("break_time_total_minutes")] + public int BreakTimeTotalMinutes { get; set; } + + /// + /// Gets or Sets BreakTimes + /// + /* [ + { + "type": "manual", + "duration_minutes": 20, + "start": null, + "end": null + }, + { + "type": "automatic", + "duration_minutes": 30, + "start": "2021-07-16T13:15:00+02:00", + "end": "2021-07-16T13:45:00+02:00" + } +] + */ + [JsonPropertyName("break_times")] + public List BreakTimes { get; set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool Changed { get; set; } + + /// + /// Gets or Sets User + /// + [JsonPropertyName("user")] + public UserPartial User { get; set; } + + /// + /// Gets or Sets WorkingTimeType + /// + [JsonPropertyName("working_time_type")] + public WorkingTimeTypePartial WorkingTimeType { get; set; } + + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("last_modified")] + public DateTimeOffset LastModified { get; set; } + + /// + /// RFC 3339 date-time (ISO-8601) + /// + /// RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get; set; } + + /// + /// Gets or Sets Duration + /// + [JsonPropertyName("duration")] + public Duration? Duration { get; set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get; set; } + + /// + /// Gets or Sets WorkingTimeDateSpan + /// + [JsonPropertyName("working_time_date_span")] + public WorkingTimeDateSpanPartial? WorkingTimeDateSpan { get; set; } + + /// + /// Gets or Sets StartLocation + /// + [JsonPropertyName("start_location")] + public Location? StartLocation { get; set; } + + /// + /// Gets or Sets EndLocation + /// + [JsonPropertyName("end_location")] + public Location? EndLocation { get; set; } + + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + [JsonPropertyName("last_modified_by")] + public UserPartial? LastModifiedBy { get; set; } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTime {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" BreakTimeTotalMinutes: ").Append(BreakTimeTotalMinutes).Append("\n"); + sb.Append(" BreakTimes: ").Append(BreakTimes).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" User: ").Append(User).Append("\n"); + sb.Append(" WorkingTimeType: ").Append(WorkingTimeType).Append("\n"); + sb.Append(" LastModified: ").Append(LastModified).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" Duration: ").Append(Duration).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" WorkingTimeDateSpan: ").Append(WorkingTimeDateSpan).Append("\n"); + sb.Append(" StartLocation: ").Append(StartLocation).Append("\n"); + sb.Append(" EndLocation: ").Append(EndLocation).Append("\n"); + sb.Append(" StartPlatform: ").Append(StartPlatform).Append("\n"); + sb.Append(" EndPlatform: ").Append(EndPlatform).Append("\n"); + sb.Append(" LastModifiedBy: ").Append(LastModifiedBy).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize LastModified + /// + public static string LastModifiedFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTime Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option start = default; + Option breakTimeTotalMinutes = default; + Option?> breakTimes = default; + Option changed = default; + Option user = default; + Option workingTimeType = default; + Option lastModified = default; + Option status = default; + Option end = default; + Option duration = default; + Option notes = default; + Option workingTimeDateSpan = default; + Option startLocation = default; + Option endLocation = default; + Option startPlatform = default; + Option endPlatform = default; + Option lastModifiedBy = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "break_time_total_minutes": + breakTimeTotalMinutes = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (int?)null : utf8JsonReader.GetInt32()); + break; + case "break_times": + breakTimes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "user": + user = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "working_time_type": + workingTimeType = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "last_modified": + lastModified = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(WorkingTimeStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "duration": + duration = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "working_time_date_span": + workingTimeDateSpan = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_location": + startLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_location": + endLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_platform": + string? startPlatformRawValue = utf8JsonReader.GetString(); + startPlatform = new Option(startPlatformRawValue == null ? null : PlatformValueConverter.FromStringOrDefault(startPlatformRawValue)); + break; + case "end_platform": + string? endPlatformRawValue = utf8JsonReader.GetString(); + endPlatform = new Option(endPlatformRawValue == null ? null : PlatformValueConverter.FromStringOrDefault(endPlatformRawValue)); + break; + case "last_modified_by": + lastModifiedBy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(id)); + + if (!start.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(start)); + + if (!breakTimeTotalMinutes.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(breakTimeTotalMinutes)); + + if (!breakTimes.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(breakTimes)); + + if (!changed.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(changed)); + + if (!user.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(user)); + + if (!workingTimeType.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(workingTimeType)); + + if (!lastModified.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(lastModified)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(status)); + + if (!end.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(end)); + + if (!duration.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(duration)); + + if (!notes.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(notes)); + + if (!workingTimeDateSpan.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(workingTimeDateSpan)); + + if (!startLocation.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(startLocation)); + + if (!endLocation.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(endLocation)); + + if (!startPlatform.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(startPlatform)); + + if (!endPlatform.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(endPlatform)); + + if (!lastModifiedBy.IsSet) + throw new ArgumentException("Property is required for class WorkingTime.", nameof(lastModifiedBy)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class WorkingTime."); + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class WorkingTime."); + + if (breakTimeTotalMinutes.IsSet && breakTimeTotalMinutes.Value == null) + throw new ArgumentNullException(nameof(breakTimeTotalMinutes), "Property is not nullable for class WorkingTime."); + + if (breakTimes.IsSet && breakTimes.Value == null) + throw new ArgumentNullException(nameof(breakTimes), "Property is not nullable for class WorkingTime."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class WorkingTime."); + + if (user.IsSet && user.Value == null) + throw new ArgumentNullException(nameof(user), "Property is not nullable for class WorkingTime."); + + if (workingTimeType.IsSet && workingTimeType.Value == null) + throw new ArgumentNullException(nameof(workingTimeType), "Property is not nullable for class WorkingTime."); + + if (lastModified.IsSet && lastModified.Value == null) + throw new ArgumentNullException(nameof(lastModified), "Property is not nullable for class WorkingTime."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class WorkingTime."); + + return new WorkingTime(id.Value!, start.Value!.Value!, breakTimeTotalMinutes.Value!.Value!, breakTimes.Value!, changed.Value!.Value!, user.Value!, workingTimeType.Value!, lastModified.Value!.Value!, status.Value!.Value!, end.Value!, duration.Value!, notes.Value!, workingTimeDateSpan.Value!, startLocation.Value!, endLocation.Value!, startPlatform.Value!, endPlatform.Value!, lastModifiedBy.Value!, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTime workingTime, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTime, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTime workingTime, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTime.Id == null) + throw new ArgumentNullException(nameof(workingTime.Id), "Property is required for class WorkingTime."); + + if (workingTime.BreakTimes == null) + throw new ArgumentNullException(nameof(workingTime.BreakTimes), "Property is required for class WorkingTime."); + + if (workingTime.User == null) + throw new ArgumentNullException(nameof(workingTime.User), "Property is required for class WorkingTime."); + + if (workingTime.WorkingTimeType == null) + throw new ArgumentNullException(nameof(workingTime.WorkingTimeType), "Property is required for class WorkingTime."); + + writer.WriteString("id", workingTime.Id); + + writer.WriteString("start", workingTime.Start.ToString(StartFormat)); + + writer.WriteNumber("break_time_total_minutes", workingTime.BreakTimeTotalMinutes); + + writer.WritePropertyName("break_times"); + JsonSerializer.Serialize(writer, workingTime.BreakTimes, jsonSerializerOptions); + writer.WriteBoolean("changed", workingTime.Changed); + + writer.WritePropertyName("user"); + JsonSerializer.Serialize(writer, workingTime.User, jsonSerializerOptions); + writer.WritePropertyName("working_time_type"); + JsonSerializer.Serialize(writer, workingTime.WorkingTimeType, jsonSerializerOptions); + writer.WriteString("last_modified", workingTime.LastModified.ToString(LastModifiedFormat)); + + var statusRawValue = WorkingTimeStatusValueConverter.ToJsonValue(workingTime.Status); + writer.WriteString("status", statusRawValue); + + if (workingTime.End != null) + writer.WriteString("end", workingTime.End.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (workingTime.Duration != null) + { + writer.WritePropertyName("duration"); + JsonSerializer.Serialize(writer, workingTime.Duration, jsonSerializerOptions); + } + else + writer.WriteNull("duration"); + if (workingTime.Notes != null) + writer.WriteString("notes", workingTime.Notes); + else + writer.WriteNull("notes"); + + if (workingTime.WorkingTimeDateSpan != null) + { + writer.WritePropertyName("working_time_date_span"); + JsonSerializer.Serialize(writer, workingTime.WorkingTimeDateSpan, jsonSerializerOptions); + } + else + writer.WriteNull("working_time_date_span"); + if (workingTime.StartLocation != null) + { + writer.WritePropertyName("start_location"); + JsonSerializer.Serialize(writer, workingTime.StartLocation, jsonSerializerOptions); + } + else + writer.WriteNull("start_location"); + if (workingTime.EndLocation != null) + { + writer.WritePropertyName("end_location"); + JsonSerializer.Serialize(writer, workingTime.EndLocation, jsonSerializerOptions); + } + else + writer.WriteNull("end_location"); + if (workingTime.StartPlatform == null) + writer.WriteNull("start_platform"); + else + { + var startPlatformRawValue = PlatformValueConverter.ToJsonValue(workingTime.StartPlatform.Value); + if (startPlatformRawValue != null) + writer.WriteString("start_platform", startPlatformRawValue); + else + writer.WriteNull("start_platform"); + } + + if (workingTime.EndPlatform == null) + writer.WriteNull("end_platform"); + else + { + var endPlatformRawValue = PlatformValueConverter.ToJsonValue(workingTime.EndPlatform.Value); + if (endPlatformRawValue != null) + writer.WriteString("end_platform", endPlatformRawValue); + else + writer.WriteNull("end_platform"); + } + + if (workingTime.LastModifiedBy != null) + { + writer.WritePropertyName("last_modified_by"); + JsonSerializer.Serialize(writer, workingTime.LastModifiedBy, jsonSerializerOptions); + } + else + writer.WriteNull("last_modified_by"); + if (workingTime.MetadataOption.IsSet) + if (workingTime.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, workingTime.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeCreate.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeCreate.cs new file mode 100644 index 0000000..0e370d3 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeCreate.cs @@ -0,0 +1,466 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimeCreate + /// + public partial class WorkingTimeCreate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + /// changed + /// workingTimeTypeId + /// status + /// userId + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + /// breakTimes + /// Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + /// notes + /// metadata + /// startLocation + /// endLocation + [JsonConstructor] + public WorkingTimeCreate(DateTimeOffset start, bool changed, string workingTimeTypeId, WorkingTimeStatus status, string userId, Option end = default, Option?> breakTimes = default, Option durationType = default, Option notes = default, Option?> metadata = default, Option startLocation = default, Option endLocation = default) + { + Start = start; + Changed = changed; + WorkingTimeTypeId = workingTimeTypeId; + Status = status; + UserId = userId; + EndOption = end; + BreakTimesOption = breakTimes; + DurationTypeOption = durationType; + NotesOption = notes; + MetadataOption = metadata; + StartLocationOption = startLocation; + EndLocationOption = endLocation; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public WorkingTimeStatus Status { get; set; } + + /// + /// Used to track the state of DurationType + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DurationTypeOption { get; private set; } + + /// + /// Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + /// + /// Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + [JsonPropertyName("duration_type")] + public DurationType? DurationType { get { return this.DurationTypeOption.Value; } set { this.DurationTypeOption = new(value); } } + + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset Start { get; set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool Changed { get; set; } + + /// + /// Gets or Sets WorkingTimeTypeId + /// + [JsonPropertyName("working_time_type_id")] + public string WorkingTimeTypeId { get; set; } + + /// + /// Gets or Sets UserId + /// + [JsonPropertyName("user_id")] + public string UserId { get; set; } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of BreakTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> BreakTimesOption { get; private set; } + + /// + /// Gets or Sets BreakTimes + /// + [JsonPropertyName("break_times")] + public List? BreakTimes { get { return this.BreakTimesOption.Value; } set { this.BreakTimesOption = new(value); } } + + /// + /// Used to track the state of Notes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NotesOption { get; private set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get { return this.NotesOption.Value; } set { this.NotesOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Used to track the state of StartLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartLocationOption { get; private set; } + + /// + /// Gets or Sets StartLocation + /// + [JsonPropertyName("start_location")] + public LocationCreate? StartLocation { get { return this.StartLocationOption.Value; } set { this.StartLocationOption = new(value); } } + + /// + /// Used to track the state of EndLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndLocationOption { get; private set; } + + /// + /// Gets or Sets EndLocation + /// + [JsonPropertyName("end_location")] + public LocationCreate? EndLocation { get { return this.EndLocationOption.Value; } set { this.EndLocationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeCreate {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" WorkingTimeTypeId: ").Append(WorkingTimeTypeId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" UserId: ").Append(UserId).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" BreakTimes: ").Append(BreakTimes).Append("\n"); + sb.Append(" DurationType: ").Append(DurationType).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" StartLocation: ").Append(StartLocation).Append("\n"); + sb.Append(" EndLocation: ").Append(EndLocation).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeCreateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeCreate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option changed = default; + Option workingTimeTypeId = default; + Option status = default; + Option userId = default; + Option end = default; + Option?> breakTimes = default; + Option durationType = default; + Option notes = default; + Option?> metadata = default; + Option startLocation = default; + Option endLocation = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "working_time_type_id": + workingTimeTypeId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(WorkingTimeStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "user_id": + userId = new Option(utf8JsonReader.GetString()!); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "break_times": + breakTimes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "duration_type": + string? durationTypeRawValue = utf8JsonReader.GetString(); + durationType = new Option(durationTypeRawValue == null ? null : DurationTypeValueConverter.FromStringOrDefault(durationTypeRawValue)); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_location": + startLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_location": + endLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!start.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeCreate.", nameof(start)); + + if (!changed.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeCreate.", nameof(changed)); + + if (!workingTimeTypeId.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeCreate.", nameof(workingTimeTypeId)); + + if (!status.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeCreate.", nameof(status)); + + if (!userId.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeCreate.", nameof(userId)); + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class WorkingTimeCreate."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class WorkingTimeCreate."); + + if (workingTimeTypeId.IsSet && workingTimeTypeId.Value == null) + throw new ArgumentNullException(nameof(workingTimeTypeId), "Property is not nullable for class WorkingTimeCreate."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class WorkingTimeCreate."); + + if (userId.IsSet && userId.Value == null) + throw new ArgumentNullException(nameof(userId), "Property is not nullable for class WorkingTimeCreate."); + + if (breakTimes.IsSet && breakTimes.Value == null) + throw new ArgumentNullException(nameof(breakTimes), "Property is not nullable for class WorkingTimeCreate."); + + return new WorkingTimeCreate(start.Value!.Value!, changed.Value!.Value!, workingTimeTypeId.Value!, status.Value!.Value!, userId.Value!, end, breakTimes, durationType, notes, metadata, startLocation, endLocation); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeCreate workingTimeCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeCreate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeCreate workingTimeCreate, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeCreate.WorkingTimeTypeId == null) + throw new ArgumentNullException(nameof(workingTimeCreate.WorkingTimeTypeId), "Property is required for class WorkingTimeCreate."); + + if (workingTimeCreate.UserId == null) + throw new ArgumentNullException(nameof(workingTimeCreate.UserId), "Property is required for class WorkingTimeCreate."); + + if (workingTimeCreate.BreakTimesOption.IsSet && workingTimeCreate.BreakTimes == null) + throw new ArgumentNullException(nameof(workingTimeCreate.BreakTimes), "Property is required for class WorkingTimeCreate."); + + writer.WriteString("start", workingTimeCreate.Start.ToString(StartFormat)); + + writer.WriteBoolean("changed", workingTimeCreate.Changed); + + writer.WriteString("working_time_type_id", workingTimeCreate.WorkingTimeTypeId); + + var statusRawValue = WorkingTimeStatusValueConverter.ToJsonValue(workingTimeCreate.Status); + writer.WriteString("status", statusRawValue); + + writer.WriteString("user_id", workingTimeCreate.UserId); + + if (workingTimeCreate.EndOption.IsSet) + if (workingTimeCreate.EndOption.Value != null) + writer.WriteString("end", workingTimeCreate.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (workingTimeCreate.BreakTimesOption.IsSet) + { + writer.WritePropertyName("break_times"); + JsonSerializer.Serialize(writer, workingTimeCreate.BreakTimes, jsonSerializerOptions); + } + if (workingTimeCreate.DurationTypeOption.IsSet) + if (workingTimeCreate.DurationTypeOption!.Value != null) + { + var durationTypeRawValue = DurationTypeValueConverter.ToJsonValue(workingTimeCreate.DurationTypeOption.Value!.Value); + writer.WriteString("duration_type", durationTypeRawValue); + } + else + writer.WriteNull("duration_type"); + if (workingTimeCreate.NotesOption.IsSet) + if (workingTimeCreate.NotesOption.Value != null) + writer.WriteString("notes", workingTimeCreate.Notes); + else + writer.WriteNull("notes"); + + if (workingTimeCreate.MetadataOption.IsSet) + if (workingTimeCreate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, workingTimeCreate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + if (workingTimeCreate.StartLocationOption.IsSet) + if (workingTimeCreate.StartLocationOption.Value != null) + { + writer.WritePropertyName("start_location"); + JsonSerializer.Serialize(writer, workingTimeCreate.StartLocation, jsonSerializerOptions); + } + else + writer.WriteNull("start_location"); + if (workingTimeCreate.EndLocationOption.IsSet) + if (workingTimeCreate.EndLocationOption.Value != null) + { + writer.WritePropertyName("end_location"); + JsonSerializer.Serialize(writer, workingTimeCreate.EndLocation, jsonSerializerOptions); + } + else + writer.WriteNull("end_location"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpan.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpan.cs new file mode 100644 index 0000000..bfc744a --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpan.cs @@ -0,0 +1,441 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// A span from `start` to `end` of a single `working_time_type`. Every working time derived for a covered day links back to it via `WorkingTime.working_time_date_span`. It can be created directly or become effective through an approved request. + /// + public partial class WorkingTimeDateSpan : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// RFC 3339 date (ISO-8601) + /// Marks the first day of the working time date span as a half day. + /// RFC 3339 date (ISO-8601) + /// Marks the last day of the working time date span as a half day. + /// user + /// workingTimeType + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// notes + /// substitute + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// metadata + [JsonConstructor] + public WorkingTimeDateSpan(string id, DateOnly start, bool startHalfDay, DateOnly end, bool endHalfDay, UserPartial user, WorkingTimeTypePartial workingTimeType, DateTimeOffset lastModified, string? notes = default, Option substitute = default, UserPartial? lastModifiedBy = default, Option?> metadata = default) + { + Id = id; + Start = start; + StartHalfDay = startHalfDay; + End = end; + EndHalfDay = endHalfDay; + User = user; + WorkingTimeType = workingTimeType; + LastModified = lastModified; + Notes = notes; + SubstituteOption = substitute; + LastModifiedBy = lastModifiedBy; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("start")] + public DateOnly Start { get; set; } + + /// + /// Marks the first day of the working time date span as a half day. + /// + /// Marks the first day of the working time date span as a half day. + [JsonPropertyName("start_half_day")] + public bool StartHalfDay { get; set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("end")] + public DateOnly End { get; set; } + + /// + /// Marks the last day of the working time date span as a half day. + /// + /// Marks the last day of the working time date span as a half day. + [JsonPropertyName("end_half_day")] + public bool EndHalfDay { get; set; } + + /// + /// Gets or Sets User + /// + [JsonPropertyName("user")] + public UserPartial User { get; set; } + + /// + /// Gets or Sets WorkingTimeType + /// + [JsonPropertyName("working_time_type")] + public WorkingTimeTypePartial WorkingTimeType { get; set; } + + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /// + /// Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("last_modified")] + public DateTimeOffset LastModified { get; set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get; set; } + + /// + /// Used to track the state of Substitute + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option SubstituteOption { get; private set; } + + /// + /// Gets or Sets Substitute + /// + [JsonPropertyName("substitute")] + public UserPartial? Substitute { get { return this.SubstituteOption.Value; } set { this.SubstituteOption = new(value); } } + + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + /// + /// Read-only. The User who last modified the entry, or null if the change was not made in a user context. + [JsonPropertyName("last_modified_by")] + public UserPartial? LastModifiedBy { get; set; } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeDateSpan {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" StartHalfDay: ").Append(StartHalfDay).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" EndHalfDay: ").Append(EndHalfDay).Append("\n"); + sb.Append(" User: ").Append(User).Append("\n"); + sb.Append(" WorkingTimeType: ").Append(WorkingTimeType).Append("\n"); + sb.Append(" LastModified: ").Append(LastModified).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" Substitute: ").Append(Substitute).Append("\n"); + sb.Append(" LastModifiedBy: ").Append(LastModifiedBy).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeDateSpanJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize LastModified + /// + public static string LastModifiedFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeDateSpan Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option start = default; + Option startHalfDay = default; + Option end = default; + Option endHalfDay = default; + Option user = default; + Option workingTimeType = default; + Option lastModified = default; + Option notes = default; + Option substitute = default; + Option lastModifiedBy = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_half_day": + startHalfDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_half_day": + endHalfDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "user": + user = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "working_time_type": + workingTimeType = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "last_modified": + lastModified = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "substitute": + substitute = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "last_modified_by": + lastModifiedBy = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(id)); + + if (!start.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(start)); + + if (!startHalfDay.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(startHalfDay)); + + if (!end.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(end)); + + if (!endHalfDay.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(endHalfDay)); + + if (!user.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(user)); + + if (!workingTimeType.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(workingTimeType)); + + if (!lastModified.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(lastModified)); + + if (!notes.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(notes)); + + if (!lastModifiedBy.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpan.", nameof(lastModifiedBy)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class WorkingTimeDateSpan."); + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class WorkingTimeDateSpan."); + + if (startHalfDay.IsSet && startHalfDay.Value == null) + throw new ArgumentNullException(nameof(startHalfDay), "Property is not nullable for class WorkingTimeDateSpan."); + + if (end.IsSet && end.Value == null) + throw new ArgumentNullException(nameof(end), "Property is not nullable for class WorkingTimeDateSpan."); + + if (endHalfDay.IsSet && endHalfDay.Value == null) + throw new ArgumentNullException(nameof(endHalfDay), "Property is not nullable for class WorkingTimeDateSpan."); + + if (user.IsSet && user.Value == null) + throw new ArgumentNullException(nameof(user), "Property is not nullable for class WorkingTimeDateSpan."); + + if (workingTimeType.IsSet && workingTimeType.Value == null) + throw new ArgumentNullException(nameof(workingTimeType), "Property is not nullable for class WorkingTimeDateSpan."); + + if (lastModified.IsSet && lastModified.Value == null) + throw new ArgumentNullException(nameof(lastModified), "Property is not nullable for class WorkingTimeDateSpan."); + + return new WorkingTimeDateSpan(id.Value!, start.Value!.Value!, startHalfDay.Value!.Value!, end.Value!.Value!, endHalfDay.Value!.Value!, user.Value!, workingTimeType.Value!, lastModified.Value!.Value!, notes.Value!, substitute, lastModifiedBy.Value!, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeDateSpan workingTimeDateSpan, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeDateSpan, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeDateSpan workingTimeDateSpan, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeDateSpan.Id == null) + throw new ArgumentNullException(nameof(workingTimeDateSpan.Id), "Property is required for class WorkingTimeDateSpan."); + + if (workingTimeDateSpan.User == null) + throw new ArgumentNullException(nameof(workingTimeDateSpan.User), "Property is required for class WorkingTimeDateSpan."); + + if (workingTimeDateSpan.WorkingTimeType == null) + throw new ArgumentNullException(nameof(workingTimeDateSpan.WorkingTimeType), "Property is required for class WorkingTimeDateSpan."); + + writer.WriteString("id", workingTimeDateSpan.Id); + + writer.WriteString("start", workingTimeDateSpan.Start.ToString(StartFormat)); + + writer.WriteBoolean("start_half_day", workingTimeDateSpan.StartHalfDay); + + writer.WriteString("end", workingTimeDateSpan.End.ToString(EndFormat)); + + writer.WriteBoolean("end_half_day", workingTimeDateSpan.EndHalfDay); + + writer.WritePropertyName("user"); + JsonSerializer.Serialize(writer, workingTimeDateSpan.User, jsonSerializerOptions); + writer.WritePropertyName("working_time_type"); + JsonSerializer.Serialize(writer, workingTimeDateSpan.WorkingTimeType, jsonSerializerOptions); + writer.WriteString("last_modified", workingTimeDateSpan.LastModified.ToString(LastModifiedFormat)); + + if (workingTimeDateSpan.Notes != null) + writer.WriteString("notes", workingTimeDateSpan.Notes); + else + writer.WriteNull("notes"); + + if (workingTimeDateSpan.SubstituteOption.IsSet) + if (workingTimeDateSpan.SubstituteOption.Value != null) + { + writer.WritePropertyName("substitute"); + JsonSerializer.Serialize(writer, workingTimeDateSpan.Substitute, jsonSerializerOptions); + } + else + writer.WriteNull("substitute"); + if (workingTimeDateSpan.LastModifiedBy != null) + { + writer.WritePropertyName("last_modified_by"); + JsonSerializer.Serialize(writer, workingTimeDateSpan.LastModifiedBy, jsonSerializerOptions); + } + else + writer.WriteNull("last_modified_by"); + if (workingTimeDateSpan.MetadataOption.IsSet) + if (workingTimeDateSpan.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, workingTimeDateSpan.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanCreate.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanCreate.cs new file mode 100644 index 0000000..412a23b --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanCreate.cs @@ -0,0 +1,375 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimeDateSpanCreate + /// + public partial class WorkingTimeDateSpanCreate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// RFC 3339 date (ISO-8601) + /// RFC 3339 date (ISO-8601) + /// workingTimeTypeId + /// userId + /// startHalfDay + /// endHalfDay + /// notes + /// substituteId + /// metadata + [JsonConstructor] + public WorkingTimeDateSpanCreate(DateOnly start, DateOnly end, string workingTimeTypeId, string userId, Option startHalfDay = default, Option endHalfDay = default, Option notes = default, Option substituteId = default, Option?> metadata = default) + { + Start = start; + End = end; + WorkingTimeTypeId = workingTimeTypeId; + UserId = userId; + StartHalfDayOption = startHalfDay; + EndHalfDayOption = endHalfDay; + NotesOption = notes; + SubstituteIdOption = substituteId; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("start")] + public DateOnly Start { get; set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("end")] + public DateOnly End { get; set; } + + /// + /// Gets or Sets WorkingTimeTypeId + /// + [JsonPropertyName("working_time_type_id")] + public string WorkingTimeTypeId { get; set; } + + /// + /// Gets or Sets UserId + /// + [JsonPropertyName("user_id")] + public string UserId { get; set; } + + /// + /// Used to track the state of StartHalfDay + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartHalfDayOption { get; private set; } + + /// + /// Gets or Sets StartHalfDay + /// + [JsonPropertyName("start_half_day")] + public bool? StartHalfDay { get { return this.StartHalfDayOption.Value; } set { this.StartHalfDayOption = new(value); } } + + /// + /// Used to track the state of EndHalfDay + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndHalfDayOption { get; private set; } + + /// + /// Gets or Sets EndHalfDay + /// + [JsonPropertyName("end_half_day")] + public bool? EndHalfDay { get { return this.EndHalfDayOption.Value; } set { this.EndHalfDayOption = new(value); } } + + /// + /// Used to track the state of Notes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NotesOption { get; private set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get { return this.NotesOption.Value; } set { this.NotesOption = new(value); } } + + /// + /// Used to track the state of SubstituteId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option SubstituteIdOption { get; private set; } + + /// + /// Gets or Sets SubstituteId + /// + [JsonPropertyName("substitute_id")] + public string? SubstituteId { get { return this.SubstituteIdOption.Value; } set { this.SubstituteIdOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeDateSpanCreate {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" WorkingTimeTypeId: ").Append(WorkingTimeTypeId).Append("\n"); + sb.Append(" UserId: ").Append(UserId).Append("\n"); + sb.Append(" StartHalfDay: ").Append(StartHalfDay).Append("\n"); + sb.Append(" EndHalfDay: ").Append(EndHalfDay).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" SubstituteId: ").Append(SubstituteId).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeDateSpanCreateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeDateSpanCreate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option end = default; + Option workingTimeTypeId = default; + Option userId = default; + Option startHalfDay = default; + Option endHalfDay = default; + Option notes = default; + Option substituteId = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "working_time_type_id": + workingTimeTypeId = new Option(utf8JsonReader.GetString()!); + break; + case "user_id": + userId = new Option(utf8JsonReader.GetString()!); + break; + case "start_half_day": + startHalfDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "end_half_day": + endHalfDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "substitute_id": + substituteId = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (!start.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpanCreate.", nameof(start)); + + if (!end.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpanCreate.", nameof(end)); + + if (!workingTimeTypeId.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpanCreate.", nameof(workingTimeTypeId)); + + if (!userId.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpanCreate.", nameof(userId)); + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class WorkingTimeDateSpanCreate."); + + if (end.IsSet && end.Value == null) + throw new ArgumentNullException(nameof(end), "Property is not nullable for class WorkingTimeDateSpanCreate."); + + if (workingTimeTypeId.IsSet && workingTimeTypeId.Value == null) + throw new ArgumentNullException(nameof(workingTimeTypeId), "Property is not nullable for class WorkingTimeDateSpanCreate."); + + if (userId.IsSet && userId.Value == null) + throw new ArgumentNullException(nameof(userId), "Property is not nullable for class WorkingTimeDateSpanCreate."); + + if (startHalfDay.IsSet && startHalfDay.Value == null) + throw new ArgumentNullException(nameof(startHalfDay), "Property is not nullable for class WorkingTimeDateSpanCreate."); + + if (endHalfDay.IsSet && endHalfDay.Value == null) + throw new ArgumentNullException(nameof(endHalfDay), "Property is not nullable for class WorkingTimeDateSpanCreate."); + + return new WorkingTimeDateSpanCreate(start.Value!.Value!, end.Value!.Value!, workingTimeTypeId.Value!, userId.Value!, startHalfDay, endHalfDay, notes, substituteId, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeDateSpanCreate workingTimeDateSpanCreate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeDateSpanCreate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeDateSpanCreate workingTimeDateSpanCreate, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeDateSpanCreate.WorkingTimeTypeId == null) + throw new ArgumentNullException(nameof(workingTimeDateSpanCreate.WorkingTimeTypeId), "Property is required for class WorkingTimeDateSpanCreate."); + + if (workingTimeDateSpanCreate.UserId == null) + throw new ArgumentNullException(nameof(workingTimeDateSpanCreate.UserId), "Property is required for class WorkingTimeDateSpanCreate."); + + writer.WriteString("start", workingTimeDateSpanCreate.Start.ToString(StartFormat)); + + writer.WriteString("end", workingTimeDateSpanCreate.End.ToString(EndFormat)); + + writer.WriteString("working_time_type_id", workingTimeDateSpanCreate.WorkingTimeTypeId); + + writer.WriteString("user_id", workingTimeDateSpanCreate.UserId); + + if (workingTimeDateSpanCreate.StartHalfDayOption.IsSet) + writer.WriteBoolean("start_half_day", workingTimeDateSpanCreate.StartHalfDayOption.Value!.Value); + + if (workingTimeDateSpanCreate.EndHalfDayOption.IsSet) + writer.WriteBoolean("end_half_day", workingTimeDateSpanCreate.EndHalfDayOption.Value!.Value); + + if (workingTimeDateSpanCreate.NotesOption.IsSet) + if (workingTimeDateSpanCreate.NotesOption.Value != null) + writer.WriteString("notes", workingTimeDateSpanCreate.Notes); + else + writer.WriteNull("notes"); + + if (workingTimeDateSpanCreate.SubstituteIdOption.IsSet) + if (workingTimeDateSpanCreate.SubstituteIdOption.Value != null) + writer.WriteString("substitute_id", workingTimeDateSpanCreate.SubstituteId); + else + writer.WriteNull("substitute_id"); + + if (workingTimeDateSpanCreate.MetadataOption.IsSet) + if (workingTimeDateSpanCreate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, workingTimeDateSpanCreate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanPage.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanPage.cs new file mode 100644 index 0000000..fd30159 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimeDateSpanPage + /// + public partial class WorkingTimeDateSpanPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public WorkingTimeDateSpanPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeDateSpanPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeDateSpanPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeDateSpanPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpanPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpanPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class WorkingTimeDateSpanPage."); + + return new WorkingTimeDateSpanPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeDateSpanPage workingTimeDateSpanPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeDateSpanPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeDateSpanPage workingTimeDateSpanPage, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeDateSpanPage.Data == null) + throw new ArgumentNullException(nameof(workingTimeDateSpanPage.Data), "Property is required for class WorkingTimeDateSpanPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, workingTimeDateSpanPage.Data, jsonSerializerOptions); + if (workingTimeDateSpanPage.NextPageToken != null) + writer.WriteString("next_page_token", workingTimeDateSpanPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanPartial.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanPartial.cs new file mode 100644 index 0000000..a916239 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanPartial.cs @@ -0,0 +1,165 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// References the date span this working time belongs to, if any. All working times generated for a date span reference the same span; working times recorded on their own have none. + /// + public partial class WorkingTimeDateSpanPartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonConstructor] + public WorkingTimeDateSpanPartial(string id) + { + Id = id; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeDateSpanPartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeDateSpanPartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeDateSpanPartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeDateSpanPartial.", nameof(id)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class WorkingTimeDateSpanPartial."); + + return new WorkingTimeDateSpanPartial(id.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeDateSpanPartial workingTimeDateSpanPartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeDateSpanPartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeDateSpanPartial workingTimeDateSpanPartial, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeDateSpanPartial.Id == null) + throw new ArgumentNullException(nameof(workingTimeDateSpanPartial.Id), "Property is required for class WorkingTimeDateSpanPartial."); + + writer.WriteString("id", workingTimeDateSpanPartial.Id); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanUpdate.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanUpdate.cs new file mode 100644 index 0000000..3fcc77f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpanUpdate.cs @@ -0,0 +1,366 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimeDateSpanUpdate + /// + public partial class WorkingTimeDateSpanUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// RFC 3339 date (ISO-8601) + /// startHalfDay + /// RFC 3339 date (ISO-8601) + /// endHalfDay + /// notes + /// workingTimeTypeId + /// substituteId + /// metadata + [JsonConstructor] + public WorkingTimeDateSpanUpdate(Option start = default, Option startHalfDay = default, Option end = default, Option endHalfDay = default, Option notes = default, Option workingTimeTypeId = default, Option substituteId = default, Option?> metadata = default) + { + StartOption = start; + StartHalfDayOption = startHalfDay; + EndOption = end; + EndHalfDayOption = endHalfDay; + NotesOption = notes; + WorkingTimeTypeIdOption = workingTimeTypeId; + SubstituteIdOption = substituteId; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Start + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("start")] + public DateOnly? Start { get { return this.StartOption.Value; } set { this.StartOption = new(value); } } + + /// + /// Used to track the state of StartHalfDay + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartHalfDayOption { get; private set; } + + /// + /// Gets or Sets StartHalfDay + /// + [JsonPropertyName("start_half_day")] + public bool? StartHalfDay { get { return this.StartHalfDayOption.Value; } set { this.StartHalfDayOption = new(value); } } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// RFC 3339 date (ISO-8601) + /// + /// RFC 3339 date (ISO-8601) + [JsonPropertyName("end")] + public DateOnly? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of EndHalfDay + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndHalfDayOption { get; private set; } + + /// + /// Gets or Sets EndHalfDay + /// + [JsonPropertyName("end_half_day")] + public bool? EndHalfDay { get { return this.EndHalfDayOption.Value; } set { this.EndHalfDayOption = new(value); } } + + /// + /// Used to track the state of Notes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NotesOption { get; private set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get { return this.NotesOption.Value; } set { this.NotesOption = new(value); } } + + /// + /// Used to track the state of WorkingTimeTypeId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option WorkingTimeTypeIdOption { get; private set; } + + /// + /// Gets or Sets WorkingTimeTypeId + /// + [JsonPropertyName("working_time_type_id")] + public string? WorkingTimeTypeId { get { return this.WorkingTimeTypeIdOption.Value; } set { this.WorkingTimeTypeIdOption = new(value); } } + + /// + /// Used to track the state of SubstituteId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option SubstituteIdOption { get; private set; } + + /// + /// Gets or Sets SubstituteId + /// + [JsonPropertyName("substitute_id")] + public string? SubstituteId { get { return this.SubstituteIdOption.Value; } set { this.SubstituteIdOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeDateSpanUpdate {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" StartHalfDay: ").Append(StartHalfDay).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" EndHalfDay: ").Append(EndHalfDay).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" WorkingTimeTypeId: ").Append(WorkingTimeTypeId).Append("\n"); + sb.Append(" SubstituteId: ").Append(SubstituteId).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeDateSpanUpdateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeDateSpanUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option startHalfDay = default; + Option end = default; + Option endHalfDay = default; + Option notes = default; + Option workingTimeTypeId = default; + Option substituteId = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_half_day": + startHalfDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_half_day": + endHalfDay = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "working_time_type_id": + workingTimeTypeId = new Option(utf8JsonReader.GetString()!); + break; + case "substitute_id": + substituteId = new Option(utf8JsonReader.GetString()); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class WorkingTimeDateSpanUpdate."); + + if (startHalfDay.IsSet && startHalfDay.Value == null) + throw new ArgumentNullException(nameof(startHalfDay), "Property is not nullable for class WorkingTimeDateSpanUpdate."); + + if (end.IsSet && end.Value == null) + throw new ArgumentNullException(nameof(end), "Property is not nullable for class WorkingTimeDateSpanUpdate."); + + if (endHalfDay.IsSet && endHalfDay.Value == null) + throw new ArgumentNullException(nameof(endHalfDay), "Property is not nullable for class WorkingTimeDateSpanUpdate."); + + if (workingTimeTypeId.IsSet && workingTimeTypeId.Value == null) + throw new ArgumentNullException(nameof(workingTimeTypeId), "Property is not nullable for class WorkingTimeDateSpanUpdate."); + + return new WorkingTimeDateSpanUpdate(start, startHalfDay, end, endHalfDay, notes, workingTimeTypeId, substituteId, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeDateSpanUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeDateSpanUpdate.WorkingTimeTypeIdOption.IsSet && workingTimeDateSpanUpdate.WorkingTimeTypeId == null) + throw new ArgumentNullException(nameof(workingTimeDateSpanUpdate.WorkingTimeTypeId), "Property is required for class WorkingTimeDateSpanUpdate."); + + if (workingTimeDateSpanUpdate.StartOption.IsSet) + writer.WriteString("start", workingTimeDateSpanUpdate.StartOption.Value!.Value.ToString(StartFormat)); + + if (workingTimeDateSpanUpdate.StartHalfDayOption.IsSet) + writer.WriteBoolean("start_half_day", workingTimeDateSpanUpdate.StartHalfDayOption.Value!.Value); + + if (workingTimeDateSpanUpdate.EndOption.IsSet) + writer.WriteString("end", workingTimeDateSpanUpdate.EndOption.Value!.Value.ToString(EndFormat)); + + if (workingTimeDateSpanUpdate.EndHalfDayOption.IsSet) + writer.WriteBoolean("end_half_day", workingTimeDateSpanUpdate.EndHalfDayOption.Value!.Value); + + if (workingTimeDateSpanUpdate.NotesOption.IsSet) + if (workingTimeDateSpanUpdate.NotesOption.Value != null) + writer.WriteString("notes", workingTimeDateSpanUpdate.Notes); + else + writer.WriteNull("notes"); + + if (workingTimeDateSpanUpdate.WorkingTimeTypeIdOption.IsSet) + writer.WriteString("working_time_type_id", workingTimeDateSpanUpdate.WorkingTimeTypeId); + + if (workingTimeDateSpanUpdate.SubstituteIdOption.IsSet) + if (workingTimeDateSpanUpdate.SubstituteIdOption.Value != null) + writer.WriteString("substitute_id", workingTimeDateSpanUpdate.SubstituteId); + else + writer.WriteNull("substitute_id"); + + if (workingTimeDateSpanUpdate.MetadataOption.IsSet) + if (workingTimeDateSpanUpdate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, workingTimeDateSpanUpdate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpansSortColumn.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpansSortColumn.cs new file mode 100644 index 0000000..b31028f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeDateSpansSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Working Time Date Spans. + /// + /// Sort property for Working Time Date Spans. + public enum WorkingTimeDateSpansSortColumn + { + /// + /// Enum Start for value: start + /// + Start = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class WorkingTimeDateSpansSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeDateSpansSortColumn FromString(string value) + { + if (value.Equals("start")) + return WorkingTimeDateSpansSortColumn.Start; + + throw new NotImplementedException($"Could not convert value to type WorkingTimeDateSpansSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeDateSpansSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("start")) + return WorkingTimeDateSpansSortColumn.Start; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(WorkingTimeDateSpansSortColumn value) + { + if (value == WorkingTimeDateSpansSortColumn.Start) + return "start"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class WorkingTimeDateSpansSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeDateSpansSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeDateSpansSortColumn? result = rawValue == null + ? null + : WorkingTimeDateSpansSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeDateSpansSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeDateSpansSortColumn workingTimeDateSpansSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(WorkingTimeDateSpansSortColumnValueConverter.ToJsonValue(workingTimeDateSpansSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeDateSpansSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a WorkingTimeDateSpansSortColumn from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeDateSpansSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeDateSpansSortColumn? result = rawValue == null + ? null + : WorkingTimeDateSpansSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeDateSpansSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeDateSpansSortColumn? workingTimeDateSpansSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(workingTimeDateSpansSortColumn.HasValue ? WorkingTimeDateSpansSortColumnValueConverter.ToJsonValue(workingTimeDateSpansSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeRules.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeRules.cs new file mode 100644 index 0000000..7c61aba --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeRules.cs @@ -0,0 +1,190 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimeRules + /// + public partial class WorkingTimeRules : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + [JsonConstructor] + public WorkingTimeRules(string id, string name) + { + Id = id; + Name = name; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + /* 074e7048-9097-11eb-a8b3-0242ac130003 */ + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeRules {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeRulesJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeRules Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeRules.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeRules.", nameof(name)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class WorkingTimeRules."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class WorkingTimeRules."); + + return new WorkingTimeRules(id.Value!, name.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeRules workingTimeRules, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeRules, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeRules workingTimeRules, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeRules.Id == null) + throw new ArgumentNullException(nameof(workingTimeRules.Id), "Property is required for class WorkingTimeRules."); + + if (workingTimeRules.Name == null) + throw new ArgumentNullException(nameof(workingTimeRules.Name), "Property is required for class WorkingTimeRules."); + + writer.WriteString("id", workingTimeRules.Id); + + writer.WriteString("name", workingTimeRules.Name); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeStatus.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeStatus.cs new file mode 100644 index 0000000..cb5cc77 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeStatus.cs @@ -0,0 +1,247 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Processing state of a Working Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, closed and archived. + /// + /// Processing state of a Working Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, closed and archived. + public enum WorkingTimeStatus + { + /// + /// Enum Running for value: running + /// + Running = 1, + + /// + /// Enum Paused for value: paused + /// + Paused = 2, + + /// + /// Enum Changeable for value: changeable + /// + Changeable = 3, + + /// + /// Enum Locked for value: locked + /// + Locked = 4, + + /// + /// Enum Approved for value: approved + /// + Approved = 5, + + /// + /// Enum Closed for value: closed + /// + Closed = 6, + + /// + /// Enum Archived for value: archived + /// + Archived = 7 + } + + /// + /// Converts to and from the JSON value + /// + public static class WorkingTimeStatusValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeStatus FromString(string value) + { + if (value.Equals("running")) + return WorkingTimeStatus.Running; + + if (value.Equals("paused")) + return WorkingTimeStatus.Paused; + + if (value.Equals("changeable")) + return WorkingTimeStatus.Changeable; + + if (value.Equals("locked")) + return WorkingTimeStatus.Locked; + + if (value.Equals("approved")) + return WorkingTimeStatus.Approved; + + if (value.Equals("closed")) + return WorkingTimeStatus.Closed; + + if (value.Equals("archived")) + return WorkingTimeStatus.Archived; + + throw new NotImplementedException($"Could not convert value to type WorkingTimeStatus: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeStatus? FromStringOrDefault(string value) + { + if (value.Equals("running")) + return WorkingTimeStatus.Running; + + if (value.Equals("paused")) + return WorkingTimeStatus.Paused; + + if (value.Equals("changeable")) + return WorkingTimeStatus.Changeable; + + if (value.Equals("locked")) + return WorkingTimeStatus.Locked; + + if (value.Equals("approved")) + return WorkingTimeStatus.Approved; + + if (value.Equals("closed")) + return WorkingTimeStatus.Closed; + + if (value.Equals("archived")) + return WorkingTimeStatus.Archived; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(WorkingTimeStatus value) + { + if (value == WorkingTimeStatus.Running) + return "running"; + + if (value == WorkingTimeStatus.Paused) + return "paused"; + + if (value == WorkingTimeStatus.Changeable) + return "changeable"; + + if (value == WorkingTimeStatus.Locked) + return "locked"; + + if (value == WorkingTimeStatus.Approved) + return "approved"; + + if (value == WorkingTimeStatus.Closed) + return "closed"; + + if (value == WorkingTimeStatus.Archived) + return "archived"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class WorkingTimeStatusJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeStatus? result = rawValue == null + ? null + : WorkingTimeStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeStatus workingTimeStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(WorkingTimeStatusValueConverter.ToJsonValue(workingTimeStatus).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeStatusNullableJsonConverter : JsonConverter + { + /// + /// Returns a WorkingTimeStatus from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeStatus? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeStatus? result = rawValue == null + ? null + : WorkingTimeStatusValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeStatus to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeStatus? workingTimeStatus, JsonSerializerOptions options) + { + writer.WriteStringValue(workingTimeStatus.HasValue ? WorkingTimeStatusValueConverter.ToJsonValue(workingTimeStatus.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeType.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeType.cs new file mode 100644 index 0000000..28b1215 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeType.cs @@ -0,0 +1,401 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// A working time type. `category` and `sub_category` place it in the classification, `edit_unit` decides whether it is recorded by time or by day, and `requires_substitute` governs how it is recorded. + /// + public partial class WorkingTimeType : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// editUnit + /// category + /// Specifies how the user can record this working time type. + /// archived + /// shortName + /// description + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// subCategory + /// requiresSubstitute + [JsonConstructor] + public WorkingTimeType(string id, string name, DurationUnit editUnit, WorkingTimeTypeCategory category, RecordingModeUser recordingModeUser, bool archived, string? shortName = default, string? description = default, string? externalId = default, WorkingTimeTypeSubCategory? subCategory = default, Option requiresSubstitute = default) + { + Id = id; + Name = name; + EditUnit = editUnit; + Category = category; + RecordingModeUser = recordingModeUser; + Archived = archived; + ShortName = shortName; + Description = description; + ExternalId = externalId; + SubCategory = subCategory; + RequiresSubstituteOption = requiresSubstitute; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets EditUnit + /// + [JsonPropertyName("edit_unit")] + public DurationUnit EditUnit { get; set; } + + /// + /// Gets or Sets Category + /// + [JsonPropertyName("category")] + public WorkingTimeTypeCategory Category { get; set; } + + /// + /// Specifies how the user can record this working time type. + /// + /// Specifies how the user can record this working time type. + [JsonPropertyName("recording_mode_user")] + public RecordingModeUser RecordingModeUser { get; set; } + + /// + /// Gets or Sets SubCategory + /// + [JsonPropertyName("sub_category")] + public WorkingTimeTypeSubCategory? SubCategory { get; set; } + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets Archived + /// + [JsonPropertyName("archived")] + public bool Archived { get; set; } + + /// + /// Gets or Sets ShortName + /// + [JsonPropertyName("short_name")] + public string? ShortName { get; set; } + + /// + /// Gets or Sets Description + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Used to track the state of RequiresSubstitute + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option RequiresSubstituteOption { get; private set; } + + /// + /// Gets or Sets RequiresSubstitute + /// + [JsonPropertyName("requires_substitute")] + public bool? RequiresSubstitute { get { return this.RequiresSubstituteOption.Value; } set { this.RequiresSubstituteOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeType {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" EditUnit: ").Append(EditUnit).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" RecordingModeUser: ").Append(RecordingModeUser).Append("\n"); + sb.Append(" Archived: ").Append(Archived).Append("\n"); + sb.Append(" ShortName: ").Append(ShortName).Append("\n"); + sb.Append(" Description: ").Append(Description).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append(" SubCategory: ").Append(SubCategory).Append("\n"); + sb.Append(" RequiresSubstitute: ").Append(RequiresSubstitute).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeTypeJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeType Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option editUnit = default; + Option category = default; + Option recordingModeUser = default; + Option archived = default; + Option shortName = default; + Option description = default; + Option externalId = default; + Option subCategory = default; + Option requiresSubstitute = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "edit_unit": + string? editUnitRawValue = utf8JsonReader.GetString(); + if (editUnitRawValue != null) + editUnit = new Option(DurationUnitValueConverter.FromStringOrDefault(editUnitRawValue)); + break; + case "category": + string? categoryRawValue = utf8JsonReader.GetString(); + if (categoryRawValue != null) + category = new Option(WorkingTimeTypeCategoryValueConverter.FromStringOrDefault(categoryRawValue)); + break; + case "recording_mode_user": + string? recordingModeUserRawValue = utf8JsonReader.GetString(); + if (recordingModeUserRawValue != null) + recordingModeUser = new Option(RecordingModeUserValueConverter.FromStringOrDefault(recordingModeUserRawValue)); + break; + case "archived": + archived = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "short_name": + shortName = new Option(utf8JsonReader.GetString()); + break; + case "description": + description = new Option(utf8JsonReader.GetString()); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + case "sub_category": + string? subCategoryRawValue = utf8JsonReader.GetString(); + subCategory = new Option(subCategoryRawValue == null ? null : WorkingTimeTypeSubCategoryValueConverter.FromStringOrDefault(subCategoryRawValue)); + break; + case "requires_substitute": + requiresSubstitute = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(name)); + + if (!editUnit.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(editUnit)); + + if (!category.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(category)); + + if (!recordingModeUser.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(recordingModeUser)); + + if (!archived.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(archived)); + + if (!shortName.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(shortName)); + + if (!description.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(description)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(externalId)); + + if (!subCategory.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeType.", nameof(subCategory)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class WorkingTimeType."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class WorkingTimeType."); + + if (editUnit.IsSet && editUnit.Value == null) + throw new ArgumentNullException(nameof(editUnit), "Property is not nullable for class WorkingTimeType."); + + if (category.IsSet && category.Value == null) + throw new ArgumentNullException(nameof(category), "Property is not nullable for class WorkingTimeType."); + + if (recordingModeUser.IsSet && recordingModeUser.Value == null) + throw new ArgumentNullException(nameof(recordingModeUser), "Property is not nullable for class WorkingTimeType."); + + if (archived.IsSet && archived.Value == null) + throw new ArgumentNullException(nameof(archived), "Property is not nullable for class WorkingTimeType."); + + if (requiresSubstitute.IsSet && requiresSubstitute.Value == null) + throw new ArgumentNullException(nameof(requiresSubstitute), "Property is not nullable for class WorkingTimeType."); + + return new WorkingTimeType(id.Value!, name.Value!, editUnit.Value!.Value!, category.Value!.Value!, recordingModeUser.Value!.Value!, archived.Value!.Value!, shortName.Value!, description.Value!, externalId.Value!, subCategory.Value!, requiresSubstitute); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeType workingTimeType, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeType, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeType workingTimeType, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeType.Id == null) + throw new ArgumentNullException(nameof(workingTimeType.Id), "Property is required for class WorkingTimeType."); + + if (workingTimeType.Name == null) + throw new ArgumentNullException(nameof(workingTimeType.Name), "Property is required for class WorkingTimeType."); + + writer.WriteString("id", workingTimeType.Id); + + writer.WriteString("name", workingTimeType.Name); + + var editUnitRawValue = DurationUnitValueConverter.ToJsonValue(workingTimeType.EditUnit); + writer.WriteString("edit_unit", editUnitRawValue); + + var categoryRawValue = WorkingTimeTypeCategoryValueConverter.ToJsonValue(workingTimeType.Category); + writer.WriteString("category", categoryRawValue); + + var recordingModeUserRawValue = RecordingModeUserValueConverter.ToJsonValue(workingTimeType.RecordingModeUser); + writer.WriteString("recording_mode_user", recordingModeUserRawValue); + + writer.WriteBoolean("archived", workingTimeType.Archived); + + if (workingTimeType.ShortName != null) + writer.WriteString("short_name", workingTimeType.ShortName); + else + writer.WriteNull("short_name"); + + if (workingTimeType.Description != null) + writer.WriteString("description", workingTimeType.Description); + else + writer.WriteNull("description"); + + if (workingTimeType.ExternalId != null) + writer.WriteString("external_id", workingTimeType.ExternalId); + else + writer.WriteNull("external_id"); + + if (workingTimeType.SubCategory == null) + writer.WriteNull("sub_category"); + else + { + var subCategoryRawValue = WorkingTimeTypeSubCategoryValueConverter.ToJsonValue(workingTimeType.SubCategory.Value); + if (subCategoryRawValue != null) + writer.WriteString("sub_category", subCategoryRawValue); + else + writer.WriteNull("sub_category"); + } + + if (workingTimeType.RequiresSubstituteOption.IsSet) + writer.WriteBoolean("requires_substitute", workingTimeType.RequiresSubstituteOption.Value!.Value); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeTypeCategory.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypeCategory.cs new file mode 100644 index 0000000..9621a69 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypeCategory.cs @@ -0,0 +1,233 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Category of a Working Time Type. `attendance_time` counts as time at work, the remaining categories describe kinds of absence. + /// + /// Category of a Working Time Type. `attendance_time` counts as time at work, the remaining categories describe kinds of absence. + public enum WorkingTimeTypeCategory + { + /// + /// Enum AttendanceTime for value: attendance_time + /// + AttendanceTime = 1, + + /// + /// Enum Vacation for value: vacation + /// + Vacation = 2, + + /// + /// Enum PaidTimeOff for value: paid_time_off + /// + PaidTimeOff = 3, + + /// + /// Enum UnpaidTimeOff for value: unpaid_time_off + /// + UnpaidTimeOff = 4, + + /// + /// Enum Suspension for value: suspension + /// + Suspension = 5, + + /// + /// Enum BreakTime for value: break_time + /// + BreakTime = 6 + } + + /// + /// Converts to and from the JSON value + /// + public static class WorkingTimeTypeCategoryValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeTypeCategory FromString(string value) + { + if (value.Equals("attendance_time")) + return WorkingTimeTypeCategory.AttendanceTime; + + if (value.Equals("vacation")) + return WorkingTimeTypeCategory.Vacation; + + if (value.Equals("paid_time_off")) + return WorkingTimeTypeCategory.PaidTimeOff; + + if (value.Equals("unpaid_time_off")) + return WorkingTimeTypeCategory.UnpaidTimeOff; + + if (value.Equals("suspension")) + return WorkingTimeTypeCategory.Suspension; + + if (value.Equals("break_time")) + return WorkingTimeTypeCategory.BreakTime; + + throw new NotImplementedException($"Could not convert value to type WorkingTimeTypeCategory: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeTypeCategory? FromStringOrDefault(string value) + { + if (value.Equals("attendance_time")) + return WorkingTimeTypeCategory.AttendanceTime; + + if (value.Equals("vacation")) + return WorkingTimeTypeCategory.Vacation; + + if (value.Equals("paid_time_off")) + return WorkingTimeTypeCategory.PaidTimeOff; + + if (value.Equals("unpaid_time_off")) + return WorkingTimeTypeCategory.UnpaidTimeOff; + + if (value.Equals("suspension")) + return WorkingTimeTypeCategory.Suspension; + + if (value.Equals("break_time")) + return WorkingTimeTypeCategory.BreakTime; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(WorkingTimeTypeCategory value) + { + if (value == WorkingTimeTypeCategory.AttendanceTime) + return "attendance_time"; + + if (value == WorkingTimeTypeCategory.Vacation) + return "vacation"; + + if (value == WorkingTimeTypeCategory.PaidTimeOff) + return "paid_time_off"; + + if (value == WorkingTimeTypeCategory.UnpaidTimeOff) + return "unpaid_time_off"; + + if (value == WorkingTimeTypeCategory.Suspension) + return "suspension"; + + if (value == WorkingTimeTypeCategory.BreakTime) + return "break_time"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class WorkingTimeTypeCategoryJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeTypeCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeTypeCategory? result = rawValue == null + ? null + : WorkingTimeTypeCategoryValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeTypeCategory to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeTypeCategory workingTimeTypeCategory, JsonSerializerOptions options) + { + writer.WriteStringValue(WorkingTimeTypeCategoryValueConverter.ToJsonValue(workingTimeTypeCategory).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeTypeCategoryNullableJsonConverter : JsonConverter + { + /// + /// Returns a WorkingTimeTypeCategory from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeTypeCategory? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeTypeCategory? result = rawValue == null + ? null + : WorkingTimeTypeCategoryValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeTypeCategory to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeTypeCategory? workingTimeTypeCategory, JsonSerializerOptions options) + { + writer.WriteStringValue(workingTimeTypeCategory.HasValue ? WorkingTimeTypeCategoryValueConverter.ToJsonValue(workingTimeTypeCategory.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeTypePartial.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypePartial.cs new file mode 100644 index 0000000..aa3c55d --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypePartial.cs @@ -0,0 +1,211 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimeTypePartial + /// + public partial class WorkingTimeTypePartial : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier. Treat it as an opaque string. + /// name + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonConstructor] + public WorkingTimeTypePartial(string id, string name, string? externalId = default) + { + Id = id; + Name = name; + ExternalId = externalId; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Unique identifier. Treat it as an opaque string. + /// + /// Unique identifier. Treat it as an opaque string. + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Gets or Sets Name + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + /// + /// Identifier of the corresponding object in an external system. Set and owned by the client. + [JsonPropertyName("external_id")] + public string? ExternalId { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeTypePartial {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" ExternalId: ").Append(ExternalId).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeTypePartialJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeTypePartial Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option id = default; + Option name = default; + Option externalId = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "id": + id = new Option(utf8JsonReader.GetString()!); + break; + case "name": + name = new Option(utf8JsonReader.GetString()!); + break; + case "external_id": + externalId = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!id.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeTypePartial.", nameof(id)); + + if (!name.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeTypePartial.", nameof(name)); + + if (!externalId.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeTypePartial.", nameof(externalId)); + + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class WorkingTimeTypePartial."); + + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class WorkingTimeTypePartial."); + + return new WorkingTimeTypePartial(id.Value!, name.Value!, externalId.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeTypePartial workingTimeTypePartial, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeTypePartial, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeTypePartial workingTimeTypePartial, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeTypePartial.Id == null) + throw new ArgumentNullException(nameof(workingTimeTypePartial.Id), "Property is required for class WorkingTimeTypePartial."); + + if (workingTimeTypePartial.Name == null) + throw new ArgumentNullException(nameof(workingTimeTypePartial.Name), "Property is required for class WorkingTimeTypePartial."); + + writer.WriteString("id", workingTimeTypePartial.Id); + + writer.WriteString("name", workingTimeTypePartial.Name); + + if (workingTimeTypePartial.ExternalId != null) + writer.WriteString("external_id", workingTimeTypePartial.ExternalId); + else + writer.WriteNull("external_id"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeTypeSubCategory.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypeSubCategory.cs new file mode 100644 index 0000000..a5b3dd4 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypeSubCategory.cs @@ -0,0 +1,219 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Further classification of a Working Time Type within its category. + /// + /// Further classification of a Working Time Type within its category. + public enum WorkingTimeTypeSubCategory + { + /// + /// Enum Present for value: present + /// + Present = 1, + + /// + /// Enum WorkFromHome for value: work_from_home + /// + WorkFromHome = 2, + + /// + /// Enum Away for value: away + /// + Away = 3, + + /// + /// Enum ActiveDrivingTime for value: active_driving_time + /// + ActiveDrivingTime = 4, + + /// + /// Enum PassiveTravellingTime for value: passive_travelling_time + /// + PassiveTravellingTime = 5 + } + + /// + /// Converts to and from the JSON value + /// + public static class WorkingTimeTypeSubCategoryValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeTypeSubCategory FromString(string value) + { + if (value.Equals("present")) + return WorkingTimeTypeSubCategory.Present; + + if (value.Equals("work_from_home")) + return WorkingTimeTypeSubCategory.WorkFromHome; + + if (value.Equals("away")) + return WorkingTimeTypeSubCategory.Away; + + if (value.Equals("active_driving_time")) + return WorkingTimeTypeSubCategory.ActiveDrivingTime; + + if (value.Equals("passive_travelling_time")) + return WorkingTimeTypeSubCategory.PassiveTravellingTime; + + throw new NotImplementedException($"Could not convert value to type WorkingTimeTypeSubCategory: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeTypeSubCategory? FromStringOrDefault(string value) + { + if (value.Equals("present")) + return WorkingTimeTypeSubCategory.Present; + + if (value.Equals("work_from_home")) + return WorkingTimeTypeSubCategory.WorkFromHome; + + if (value.Equals("away")) + return WorkingTimeTypeSubCategory.Away; + + if (value.Equals("active_driving_time")) + return WorkingTimeTypeSubCategory.ActiveDrivingTime; + + if (value.Equals("passive_travelling_time")) + return WorkingTimeTypeSubCategory.PassiveTravellingTime; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(WorkingTimeTypeSubCategory value) + { + if (value == WorkingTimeTypeSubCategory.Present) + return "present"; + + if (value == WorkingTimeTypeSubCategory.WorkFromHome) + return "work_from_home"; + + if (value == WorkingTimeTypeSubCategory.Away) + return "away"; + + if (value == WorkingTimeTypeSubCategory.ActiveDrivingTime) + return "active_driving_time"; + + if (value == WorkingTimeTypeSubCategory.PassiveTravellingTime) + return "passive_travelling_time"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class WorkingTimeTypeSubCategoryJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeTypeSubCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeTypeSubCategory? result = rawValue == null + ? null + : WorkingTimeTypeSubCategoryValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeTypeSubCategory to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeTypeSubCategory workingTimeTypeSubCategory, JsonSerializerOptions options) + { + writer.WriteStringValue(WorkingTimeTypeSubCategoryValueConverter.ToJsonValue(workingTimeTypeSubCategory).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeTypeSubCategoryNullableJsonConverter : JsonConverter + { + /// + /// Returns a WorkingTimeTypeSubCategory from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeTypeSubCategory? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeTypeSubCategory? result = rawValue == null + ? null + : WorkingTimeTypeSubCategoryValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeTypeSubCategory to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeTypeSubCategory? workingTimeTypeSubCategory, JsonSerializerOptions options) + { + writer.WriteStringValue(workingTimeTypeSubCategory.HasValue ? WorkingTimeTypeSubCategoryValueConverter.ToJsonValue(workingTimeTypeSubCategory.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeTypesPage.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypesPage.cs new file mode 100644 index 0000000..398974a --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypesPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimeTypesPage + /// + public partial class WorkingTimeTypesPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public WorkingTimeTypesPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeTypesPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeTypesPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeTypesPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeTypesPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class WorkingTimeTypesPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class WorkingTimeTypesPage."); + + return new WorkingTimeTypesPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeTypesPage workingTimeTypesPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeTypesPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeTypesPage workingTimeTypesPage, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeTypesPage.Data == null) + throw new ArgumentNullException(nameof(workingTimeTypesPage.Data), "Property is required for class WorkingTimeTypesPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, workingTimeTypesPage.Data, jsonSerializerOptions); + if (workingTimeTypesPage.NextPageToken != null) + writer.WriteString("next_page_token", workingTimeTypesPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeTypesSortColumn.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypesSortColumn.cs new file mode 100644 index 0000000..82b4975 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeTypesSortColumn.cs @@ -0,0 +1,163 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Working Time Types. + /// + /// Sort property for Working Time Types. + public enum WorkingTimeTypesSortColumn + { + /// + /// Enum Name for value: name + /// + Name = 1 + } + + /// + /// Converts to and from the JSON value + /// + public static class WorkingTimeTypesSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeTypesSortColumn FromString(string value) + { + if (value.Equals("name")) + return WorkingTimeTypesSortColumn.Name; + + throw new NotImplementedException($"Could not convert value to type WorkingTimeTypesSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimeTypesSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("name")) + return WorkingTimeTypesSortColumn.Name; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(WorkingTimeTypesSortColumn value) + { + if (value == WorkingTimeTypesSortColumn.Name) + return "name"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class WorkingTimeTypesSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeTypesSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeTypesSortColumn? result = rawValue == null + ? null + : WorkingTimeTypesSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeTypesSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeTypesSortColumn workingTimeTypesSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(WorkingTimeTypesSortColumnValueConverter.ToJsonValue(workingTimeTypesSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeTypesSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a WorkingTimeTypesSortColumn from the Json object + /// + /// + /// + /// + /// + public override WorkingTimeTypesSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimeTypesSortColumn? result = rawValue == null + ? null + : WorkingTimeTypesSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimeTypesSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeTypesSortColumn? workingTimeTypesSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(workingTimeTypesSortColumn.HasValue ? WorkingTimeTypesSortColumnValueConverter.ToJsonValue(workingTimeTypesSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeUpdate.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeUpdate.cs new file mode 100644 index 0000000..033308f --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeUpdate.cs @@ -0,0 +1,463 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimeUpdate + /// + public partial class WorkingTimeUpdate : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + /// breakTimes + /// Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + /// changed + /// notes + /// workingTimeTypeId + /// status + /// metadata + /// startLocation + /// endLocation + [JsonConstructor] + public WorkingTimeUpdate(Option start = default, Option end = default, Option?> breakTimes = default, Option durationType = default, Option changed = default, Option notes = default, Option workingTimeTypeId = default, Option status = default, Option?> metadata = default, Option startLocation = default, Option endLocation = default) + { + StartOption = start; + EndOption = end; + BreakTimesOption = breakTimes; + DurationTypeOption = durationType; + ChangedOption = changed; + NotesOption = notes; + WorkingTimeTypeIdOption = workingTimeTypeId; + StatusOption = status; + MetadataOption = metadata; + StartLocationOption = startLocation; + EndLocationOption = endLocation; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of DurationType + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DurationTypeOption { get; private set; } + + /// + /// Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + /// + /// Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + [JsonPropertyName("duration_type")] + public DurationType? DurationType { get { return this.DurationTypeOption.Value; } set { this.DurationTypeOption = new(value); } } + + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public WorkingTimeStatus? Status { get { return this.StatusOption.Value; } set { this.StatusOption = new(value); } } + + /// + /// Used to track the state of Start + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartOption { get; private set; } + + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset? Start { get { return this.StartOption.Value; } set { this.StartOption = new(value); } } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of BreakTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> BreakTimesOption { get; private set; } + + /// + /// Gets or Sets BreakTimes + /// + [JsonPropertyName("break_times")] + public List? BreakTimes { get { return this.BreakTimesOption.Value; } set { this.BreakTimesOption = new(value); } } + + /// + /// Used to track the state of Changed + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ChangedOption { get; private set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool? Changed { get { return this.ChangedOption.Value; } set { this.ChangedOption = new(value); } } + + /// + /// Used to track the state of Notes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NotesOption { get; private set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get { return this.NotesOption.Value; } set { this.NotesOption = new(value); } } + + /// + /// Used to track the state of WorkingTimeTypeId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option WorkingTimeTypeIdOption { get; private set; } + + /// + /// Gets or Sets WorkingTimeTypeId + /// + [JsonPropertyName("working_time_type_id")] + public string? WorkingTimeTypeId { get { return this.WorkingTimeTypeIdOption.Value; } set { this.WorkingTimeTypeIdOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Used to track the state of StartLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartLocationOption { get; private set; } + + /// + /// Gets or Sets StartLocation + /// + [JsonPropertyName("start_location")] + public LocationUpdate? StartLocation { get { return this.StartLocationOption.Value; } set { this.StartLocationOption = new(value); } } + + /// + /// Used to track the state of EndLocation + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndLocationOption { get; private set; } + + /// + /// Gets or Sets EndLocation + /// + [JsonPropertyName("end_location")] + public LocationUpdate? EndLocation { get { return this.EndLocationOption.Value; } set { this.EndLocationOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeUpdate {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" BreakTimes: ").Append(BreakTimes).Append("\n"); + sb.Append(" DurationType: ").Append(DurationType).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" WorkingTimeTypeId: ").Append(WorkingTimeTypeId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append(" StartLocation: ").Append(StartLocation).Append("\n"); + sb.Append(" EndLocation: ").Append(EndLocation).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeUpdateJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeUpdate Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option end = default; + Option?> breakTimes = default; + Option durationType = default; + Option changed = default; + Option notes = default; + Option workingTimeTypeId = default; + Option status = default; + Option?> metadata = default; + Option startLocation = default; + Option endLocation = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "break_times": + breakTimes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "duration_type": + string? durationTypeRawValue = utf8JsonReader.GetString(); + durationType = new Option(durationTypeRawValue == null ? null : DurationTypeValueConverter.FromStringOrDefault(durationTypeRawValue)); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "working_time_type_id": + workingTimeTypeId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(WorkingTimeStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "start_location": + startLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end_location": + endLocation = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class WorkingTimeUpdate."); + + if (breakTimes.IsSet && breakTimes.Value == null) + throw new ArgumentNullException(nameof(breakTimes), "Property is not nullable for class WorkingTimeUpdate."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class WorkingTimeUpdate."); + + if (workingTimeTypeId.IsSet && workingTimeTypeId.Value == null) + throw new ArgumentNullException(nameof(workingTimeTypeId), "Property is not nullable for class WorkingTimeUpdate."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class WorkingTimeUpdate."); + + return new WorkingTimeUpdate(start, end, breakTimes, durationType, changed, notes, workingTimeTypeId, status, metadata, startLocation, endLocation); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeUpdate workingTimeUpdate, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeUpdate, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeUpdate workingTimeUpdate, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeUpdate.BreakTimesOption.IsSet && workingTimeUpdate.BreakTimes == null) + throw new ArgumentNullException(nameof(workingTimeUpdate.BreakTimes), "Property is required for class WorkingTimeUpdate."); + + if (workingTimeUpdate.WorkingTimeTypeIdOption.IsSet && workingTimeUpdate.WorkingTimeTypeId == null) + throw new ArgumentNullException(nameof(workingTimeUpdate.WorkingTimeTypeId), "Property is required for class WorkingTimeUpdate."); + + if (workingTimeUpdate.StartOption.IsSet) + writer.WriteString("start", workingTimeUpdate.StartOption.Value!.Value.ToString(StartFormat)); + + if (workingTimeUpdate.EndOption.IsSet) + if (workingTimeUpdate.EndOption.Value != null) + writer.WriteString("end", workingTimeUpdate.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (workingTimeUpdate.BreakTimesOption.IsSet) + { + writer.WritePropertyName("break_times"); + JsonSerializer.Serialize(writer, workingTimeUpdate.BreakTimes, jsonSerializerOptions); + } + if (workingTimeUpdate.DurationTypeOption.IsSet) + if (workingTimeUpdate.DurationTypeOption!.Value != null) + { + var durationTypeRawValue = DurationTypeValueConverter.ToJsonValue(workingTimeUpdate.DurationTypeOption.Value!.Value); + writer.WriteString("duration_type", durationTypeRawValue); + } + else + writer.WriteNull("duration_type"); + if (workingTimeUpdate.ChangedOption.IsSet) + writer.WriteBoolean("changed", workingTimeUpdate.ChangedOption.Value!.Value); + + if (workingTimeUpdate.NotesOption.IsSet) + if (workingTimeUpdate.NotesOption.Value != null) + writer.WriteString("notes", workingTimeUpdate.Notes); + else + writer.WriteNull("notes"); + + if (workingTimeUpdate.WorkingTimeTypeIdOption.IsSet) + writer.WriteString("working_time_type_id", workingTimeUpdate.WorkingTimeTypeId); + + if (workingTimeUpdate.StatusOption.IsSet) + { + var statusRawValue = WorkingTimeStatusValueConverter.ToJsonValue(workingTimeUpdate.Status!.Value); + writer.WriteString("status", statusRawValue); + } + if (workingTimeUpdate.MetadataOption.IsSet) + if (workingTimeUpdate.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, workingTimeUpdate.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + if (workingTimeUpdate.StartLocationOption.IsSet) + if (workingTimeUpdate.StartLocationOption.Value != null) + { + writer.WritePropertyName("start_location"); + JsonSerializer.Serialize(writer, workingTimeUpdate.StartLocation, jsonSerializerOptions); + } + else + writer.WriteNull("start_location"); + if (workingTimeUpdate.EndLocationOption.IsSet) + if (workingTimeUpdate.EndLocationOption.Value != null) + { + writer.WritePropertyName("end_location"); + JsonSerializer.Serialize(writer, workingTimeUpdate.EndLocation, jsonSerializerOptions); + } + else + writer.WriteNull("end_location"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimeUpsert.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimeUpsert.cs new file mode 100644 index 0000000..ec1c668 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimeUpsert.cs @@ -0,0 +1,407 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimeUpsert + /// + public partial class WorkingTimeUpsert : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + /// breakTimes + /// Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + /// changed + /// notes + /// workingTimeTypeId + /// status + /// metadata + [JsonConstructor] + public WorkingTimeUpsert(Option start = default, Option end = default, Option?> breakTimes = default, Option durationType = default, Option changed = default, Option notes = default, Option workingTimeTypeId = default, Option status = default, Option?> metadata = default) + { + StartOption = start; + EndOption = end; + BreakTimesOption = breakTimes; + DurationTypeOption = durationType; + ChangedOption = changed; + NotesOption = notes; + WorkingTimeTypeIdOption = workingTimeTypeId; + StatusOption = status; + MetadataOption = metadata; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of DurationType + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option DurationTypeOption { get; private set; } + + /// + /// Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + /// + /// Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + [JsonPropertyName("duration_type")] + public DurationType? DurationType { get { return this.DurationTypeOption.Value; } set { this.DurationTypeOption = new(value); } } + + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + + /// + /// Gets or Sets Status + /// + [JsonPropertyName("status")] + public WorkingTimeStatus? Status { get { return this.StatusOption.Value; } set { this.StatusOption = new(value); } } + + /// + /// Used to track the state of Start + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option StartOption { get; private set; } + + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("start")] + public DateTimeOffset? Start { get { return this.StartOption.Value; } set { this.StartOption = new(value); } } + + /// + /// Used to track the state of End + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option EndOption { get; private set; } + + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + /// + /// For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + /* 2021-07-16T08:20Z */ + [JsonPropertyName("end")] + public DateTimeOffset? End { get { return this.EndOption.Value; } set { this.EndOption = new(value); } } + + /// + /// Used to track the state of BreakTimes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> BreakTimesOption { get; private set; } + + /// + /// Gets or Sets BreakTimes + /// + [JsonPropertyName("break_times")] + public List? BreakTimes { get { return this.BreakTimesOption.Value; } set { this.BreakTimesOption = new(value); } } + + /// + /// Used to track the state of Changed + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option ChangedOption { get; private set; } + + /// + /// Gets or Sets Changed + /// + [JsonPropertyName("changed")] + public bool? Changed { get { return this.ChangedOption.Value; } set { this.ChangedOption = new(value); } } + + /// + /// Used to track the state of Notes + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option NotesOption { get; private set; } + + /// + /// Gets or Sets Notes + /// + [JsonPropertyName("notes")] + public string? Notes { get { return this.NotesOption.Value; } set { this.NotesOption = new(value); } } + + /// + /// Used to track the state of WorkingTimeTypeId + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option WorkingTimeTypeIdOption { get; private set; } + + /// + /// Gets or Sets WorkingTimeTypeId + /// + [JsonPropertyName("working_time_type_id")] + public string? WorkingTimeTypeId { get { return this.WorkingTimeTypeIdOption.Value; } set { this.WorkingTimeTypeIdOption = new(value); } } + + /// + /// Used to track the state of Metadata + /// + [JsonIgnore] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MetadataOption { get; private set; } + + /// + /// Gets or Sets Metadata + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get { return this.MetadataOption.Value; } set { this.MetadataOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimeUpsert {\n"); + sb.Append(" Start: ").Append(Start).Append("\n"); + sb.Append(" End: ").Append(End).Append("\n"); + sb.Append(" BreakTimes: ").Append(BreakTimes).Append("\n"); + sb.Append(" DurationType: ").Append(DurationType).Append("\n"); + sb.Append(" Changed: ").Append(Changed).Append("\n"); + sb.Append(" Notes: ").Append(Notes).Append("\n"); + sb.Append(" WorkingTimeTypeId: ").Append(WorkingTimeTypeId).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Metadata: ").Append(Metadata).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimeUpsertJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Start + /// + public static string StartFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize End + /// + public static string EndFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimeUpsert Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option start = default; + Option end = default; + Option?> breakTimes = default; + Option durationType = default; + Option changed = default; + Option notes = default; + Option workingTimeTypeId = default; + Option status = default; + Option?> metadata = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "start": + start = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "end": + end = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "break_times": + breakTimes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "duration_type": + string? durationTypeRawValue = utf8JsonReader.GetString(); + durationType = new Option(durationTypeRawValue == null ? null : DurationTypeValueConverter.FromStringOrDefault(durationTypeRawValue)); + break; + case "changed": + changed = new Option(utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + break; + case "notes": + notes = new Option(utf8JsonReader.GetString()); + break; + case "working_time_type_id": + workingTimeTypeId = new Option(utf8JsonReader.GetString()!); + break; + case "status": + string? statusRawValue = utf8JsonReader.GetString(); + if (statusRawValue != null) + status = new Option(WorkingTimeStatusValueConverter.FromStringOrDefault(statusRawValue)); + break; + case "metadata": + metadata = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (start.IsSet && start.Value == null) + throw new ArgumentNullException(nameof(start), "Property is not nullable for class WorkingTimeUpsert."); + + if (breakTimes.IsSet && breakTimes.Value == null) + throw new ArgumentNullException(nameof(breakTimes), "Property is not nullable for class WorkingTimeUpsert."); + + if (changed.IsSet && changed.Value == null) + throw new ArgumentNullException(nameof(changed), "Property is not nullable for class WorkingTimeUpsert."); + + if (workingTimeTypeId.IsSet && workingTimeTypeId.Value == null) + throw new ArgumentNullException(nameof(workingTimeTypeId), "Property is not nullable for class WorkingTimeUpsert."); + + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class WorkingTimeUpsert."); + + return new WorkingTimeUpsert(start, end, breakTimes, durationType, changed, notes, workingTimeTypeId, status, metadata); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimeUpsert workingTimeUpsert, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimeUpsert, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimeUpsert workingTimeUpsert, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimeUpsert.BreakTimesOption.IsSet && workingTimeUpsert.BreakTimes == null) + throw new ArgumentNullException(nameof(workingTimeUpsert.BreakTimes), "Property is required for class WorkingTimeUpsert."); + + if (workingTimeUpsert.WorkingTimeTypeIdOption.IsSet && workingTimeUpsert.WorkingTimeTypeId == null) + throw new ArgumentNullException(nameof(workingTimeUpsert.WorkingTimeTypeId), "Property is required for class WorkingTimeUpsert."); + + if (workingTimeUpsert.StartOption.IsSet) + writer.WriteString("start", workingTimeUpsert.StartOption.Value!.Value.ToString(StartFormat)); + + if (workingTimeUpsert.EndOption.IsSet) + if (workingTimeUpsert.EndOption.Value != null) + writer.WriteString("end", workingTimeUpsert.EndOption.Value!.Value.ToString(EndFormat)); + else + writer.WriteNull("end"); + + if (workingTimeUpsert.BreakTimesOption.IsSet) + { + writer.WritePropertyName("break_times"); + JsonSerializer.Serialize(writer, workingTimeUpsert.BreakTimes, jsonSerializerOptions); + } + if (workingTimeUpsert.DurationTypeOption.IsSet) + if (workingTimeUpsert.DurationTypeOption!.Value != null) + { + var durationTypeRawValue = DurationTypeValueConverter.ToJsonValue(workingTimeUpsert.DurationTypeOption.Value!.Value); + writer.WriteString("duration_type", durationTypeRawValue); + } + else + writer.WriteNull("duration_type"); + if (workingTimeUpsert.ChangedOption.IsSet) + writer.WriteBoolean("changed", workingTimeUpsert.ChangedOption.Value!.Value); + + if (workingTimeUpsert.NotesOption.IsSet) + if (workingTimeUpsert.NotesOption.Value != null) + writer.WriteString("notes", workingTimeUpsert.Notes); + else + writer.WriteNull("notes"); + + if (workingTimeUpsert.WorkingTimeTypeIdOption.IsSet) + writer.WriteString("working_time_type_id", workingTimeUpsert.WorkingTimeTypeId); + + if (workingTimeUpsert.StatusOption.IsSet) + { + var statusRawValue = WorkingTimeStatusValueConverter.ToJsonValue(workingTimeUpsert.Status!.Value); + writer.WriteString("status", statusRawValue); + } + if (workingTimeUpsert.MetadataOption.IsSet) + if (workingTimeUpsert.MetadataOption.Value != null) + { + writer.WritePropertyName("metadata"); + JsonSerializer.Serialize(writer, workingTimeUpsert.Metadata, jsonSerializerOptions); + } + else + writer.WriteNull("metadata"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimesPage.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimesPage.cs new file mode 100644 index 0000000..4908ea1 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimesPage.cs @@ -0,0 +1,186 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// WorkingTimesPage + /// + public partial class WorkingTimesPage : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// data + /// Token for the next page, or null when this is the last page. + [JsonConstructor] + public WorkingTimesPage(List data, string? nextPageToken = default) + { + Data = data; + NextPageToken = nextPageToken; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Gets or Sets Data + /// + [JsonPropertyName("data")] + public List Data { get; set; } + + /// + /// Token for the next page, or null when this is the last page. + /// + /// Token for the next page, or null when this is the last page. + [JsonPropertyName("next_page_token")] + public string? NextPageToken { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class WorkingTimesPage {\n"); + sb.Append(" Data: ").Append(Data).Append("\n"); + sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimesPageJsonConverter : JsonConverter + { + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override WorkingTimesPage Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option?> data = default; + Option nextPageToken = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "data": + data = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "next_page_token": + nextPageToken = new Option(utf8JsonReader.GetString()); + break; + default: + break; + } + } + } + + if (!data.IsSet) + throw new ArgumentException("Property is required for class WorkingTimesPage.", nameof(data)); + + if (!nextPageToken.IsSet) + throw new ArgumentException("Property is required for class WorkingTimesPage.", nameof(nextPageToken)); + + if (data.IsSet && data.Value == null) + throw new ArgumentNullException(nameof(data), "Property is not nullable for class WorkingTimesPage."); + + return new WorkingTimesPage(data.Value!, nextPageToken.Value!); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimesPage workingTimesPage, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(writer, workingTimesPage, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, WorkingTimesPage workingTimesPage, JsonSerializerOptions jsonSerializerOptions) + { + if (workingTimesPage.Data == null) + throw new ArgumentNullException(nameof(workingTimesPage.Data), "Property is required for class WorkingTimesPage."); + + writer.WritePropertyName("data"); + JsonSerializer.Serialize(writer, workingTimesPage.Data, jsonSerializerOptions); + if (workingTimesPage.NextPageToken != null) + writer.WriteString("next_page_token", workingTimesPage.NextPageToken); + else + writer.WriteNull("next_page_token"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/Model/WorkingTimesSortColumn.cs b/sdk/dotnet/Timr.Api/Model/WorkingTimesSortColumn.cs new file mode 100644 index 0000000..515aa92 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Model/WorkingTimesSortColumn.cs @@ -0,0 +1,177 @@ +// +/* + * timr API + * + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Timr.Api.Client; + +namespace Timr.Api.Model +{ + /// + /// Sort property for Working Times. + /// + /// Sort property for Working Times. + public enum WorkingTimesSortColumn + { + /// + /// Enum Start for value: start + /// + Start = 1, + + /// + /// Enum LastModified for value: last_modified + /// + LastModified = 2 + } + + /// + /// Converts to and from the JSON value + /// + public static class WorkingTimesSortColumnValueConverter + { + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimesSortColumn FromString(string value) + { + if (value.Equals("start")) + return WorkingTimesSortColumn.Start; + + if (value.Equals("last_modified")) + return WorkingTimesSortColumn.LastModified; + + throw new NotImplementedException($"Could not convert value to type WorkingTimesSortColumn: '{value}'"); + } + + /// + /// Parses a given value to + /// + /// + /// + public static WorkingTimesSortColumn? FromStringOrDefault(string value) + { + if (value.Equals("start")) + return WorkingTimesSortColumn.Start; + + if (value.Equals("last_modified")) + return WorkingTimesSortColumn.LastModified; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string ToJsonValue(WorkingTimesSortColumn value) + { + if (value == WorkingTimesSortColumn.Start) + return "start"; + + if (value == WorkingTimesSortColumn.LastModified) + return "last_modified"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + } + + /// + /// A Json converter for type + /// + /// + public class WorkingTimesSortColumnJsonConverter : JsonConverter + { + /// + /// Returns a from the Json object + /// + /// + /// + /// + /// + public override WorkingTimesSortColumn Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimesSortColumn? result = rawValue == null + ? null + : WorkingTimesSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimesSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimesSortColumn workingTimesSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(WorkingTimesSortColumnValueConverter.ToJsonValue(workingTimesSortColumn).ToString()); + } + } + + /// + /// A Json converter for type + /// + public class WorkingTimesSortColumnNullableJsonConverter : JsonConverter + { + /// + /// Returns a WorkingTimesSortColumn from the Json object + /// + /// + /// + /// + /// + public override WorkingTimesSortColumn? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? rawValue = reader.GetString(); + + WorkingTimesSortColumn? result = rawValue == null + ? null + : WorkingTimesSortColumnValueConverter.FromStringOrDefault(rawValue); + + if (result != null) + return result.Value; + + throw new JsonException(); + } + + /// + /// Writes the WorkingTimesSortColumn to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, WorkingTimesSortColumn? workingTimesSortColumn, JsonSerializerOptions options) + { + writer.WriteStringValue(workingTimesSortColumn.HasValue ? WorkingTimesSortColumnValueConverter.ToJsonValue(workingTimesSortColumn.Value).ToString() : "null"); + } + } +} diff --git a/sdk/dotnet/Timr.Api/README.md b/sdk/dotnet/Timr.Api/README.md new file mode 100644 index 0000000..5fc7581 --- /dev/null +++ b/sdk/dotnet/Timr.Api/README.md @@ -0,0 +1,51 @@ +# Created with Openapi Generator + + +## Using the library in your project + +```cs +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Timr.Api.Api; +using Timr.Api.Client; +using Timr.Api.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + LoginApiResponse apiResponse = await api.LoginAsync("todo"); + AuthResponse model = apiResponse.Ok(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, options) => + { + // the type of token here depends on the api security specifications + ApiKeyToken token = new("", ClientUtils.ApiKeyHeader.Authorization); + options.AddTokens(token); + + // optionally choose the method the tokens will be provided with, default is RateLimitProvider + options.UseProvider, ApiKeyToken>(); + + options.ConfigureJsonOptions((jsonOptions) => + { + // your custom converters if any + }); + + options.AddApiHttpClients(builder: builder => builder + .AddRetryPolicy(2) + .AddTimeoutPolicy(TimeSpan.FromSeconds(5)) + .AddCircuitBreakerPolicy(10, TimeSpan.FromSeconds(30)) + // add whatever middleware you prefer + ); + }); + } +} +``` diff --git a/sdk/dotnet/Timr.Api/Timr.Api.csproj b/sdk/dotnet/Timr.Api/Timr.Api.csproj new file mode 100644 index 0000000..b9d1f05 --- /dev/null +++ b/sdk/dotnet/Timr.Api/Timr.Api.csproj @@ -0,0 +1,38 @@ + + + + true + Timr.Api + timr.Api + Library + troii Software GmbH + troii Software GmbH + timr REST API SDK + Official .NET client for the timr API + Copyright © 2026 troii Software GmbH + Timr.Api + bin\$(Configuration)\$(TargetFramework)\Timr.Api.xml + https://developer.timr.com + https://github.com/troii/timr-api + git + README.md + Apache-2.0 + timr;api;client;dotnet + enable + false + net8.0;net10.0 + latest + + + + + + + + + + + + + + diff --git a/sdk/dotnet/build.gradle b/sdk/dotnet/build.gradle new file mode 100644 index 0000000..1fc0763 --- /dev/null +++ b/sdk/dotnet/build.gradle @@ -0,0 +1,76 @@ +plugins { + alias(libs.plugins.openapi) + id 'base' +} + +tasks.register('cleanOpenApiGenerate', Delete) { + delete layout.projectDirectory.dir("Timr.Api/Api") + delete layout.projectDirectory.dir("Timr.Api/Model") +} + +openApiGenerate { + generatorName = 'csharp' + outputDir = "$projectDir" + templateDir = "$projectDir/templates" + configOptions = [ + apiName : 'TimrApiClient', + packageName : 'Timr.Api', + sourceFolder : './', + nullableReferenceTypes: 'true', + useDateTimeOffset : 'true' + ] +} + +tasks.named('openApiGenerate').configure { task -> + task.dependsOn('cleanOpenApiGenerate') +} + +// Generated sources are committed into this module's source set, so the restore that reads them runs after +// generation; a build on its own would otherwise quietly compile the previous generation's output. +tasks.matching { it.name == 'dotnetRestore' }.configureEach { + dependsOn tasks.named('openApiGenerate') +} + + +def packageVersion = project.version +File nugetOutputDirectory = layout.buildDirectory.file("nuget/").get().asFile + +tasks.register('dotnetRestore', Exec) { + group = 'build' + description = 'Runs dotnet restore for the timr SDK solution.' + workingDir = project.projectDir + + commandLine 'dotnet', 'restore', '.' +} + +tasks.register('dotnetBuild', Exec) { + group = 'build' + description = 'Builds the timr SDK solution with the shared version.' + workingDir = project.projectDir + + dependsOn tasks.named('dotnetRestore') + commandLine 'dotnet', 'build', '.', + '-c', 'Release', + '-p:Version=' + packageVersion +} + +tasks.register('dotnetPack', Exec) { + group = 'publishing' + description = 'Creates the NuGet package at the module version.' + workingDir = project.projectDir + + dependsOn tasks.named('dotnetBuild') + doFirst { + nugetOutputDirectory.mkdirs() + } + commandLine 'dotnet', 'pack', 'Timr.Api/Timr.Api.csproj', + '-c', 'Release', + '--no-build', + '-o', nugetOutputDirectory.absolutePath, + '-p:Version=' + packageVersion, + '-p:PackageVersion=' + packageVersion +} + +tasks.named('assemble').configure { task -> + task.dependsOn tasks.named('dotnetBuild') +} diff --git a/sdk/dotnet/global.json b/sdk/dotnet/global.json new file mode 100644 index 0000000..a11f48e --- /dev/null +++ b/sdk/dotnet/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.0", + "rollForward": "latestMajor", + "allowPrerelease": true + } +} \ No newline at end of file diff --git a/sdk/dotnet/templates/HostConfiguration.mustache b/sdk/dotnet/templates/HostConfiguration.mustache new file mode 100644 index 0000000..02a3081 --- /dev/null +++ b/sdk/dotnet/templates/HostConfiguration.mustache @@ -0,0 +1,192 @@ +{{>partial_header}} +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using {{packageName}}.{{apiPackage}}; +{{#models}} +{{#-first}} +using {{packageName}}.{{modelPackage}}; +{{/-first}} +{{/models}} + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Provides hosting configuration for {{packageName}} + /// + {{>visibility}} class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + internal bool HttpClientsAdded { get; private set; } + + /// + /// Instantiates the class + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + {{#supportsDateOnly}} + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + {{/supportsDateOnly}} + {{#models}} + {{#model}} + {{#isEnum}} + _jsonOptions.Converters.Add(new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}JsonConverter()); + _jsonOptions.Converters.Add(new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}NullableJsonConverter()); + {{/isEnum}} + {{^isEnum}} + _jsonOptions.Converters.Add(new {{classname}}JsonConverter()); + {{/isEnum}} + {{/model}} + {{/models}} + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new{{^net60OrLater}} JsonSerializerOptionsProvider{{/net60OrLater}}(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + {{#useSourceGeneration}} + + {{#models}} + {{#-first}} + _jsonOptions.TypeInfoResolver = System.Text.Json.Serialization.Metadata.JsonTypeInfoResolver.Combine( + {{/-first}} + {{/models}} + {{#lambda.joinLinesWithComma}} + {{#models}} + {{#model}} + new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}SerializationContext(){{#-last}},{{/-last}} + {{/model}} + {{/models}} + {{/lambda.joinLinesWithComma}} + {{#models}} + {{#-last}} + + new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver() + ); + {{/-last}} + {{/models}} + + {{/useSourceGeneration}} + _services.AddSingleton();{{#apiInfo}}{{#apis}} + _services.AddSingleton<{{classname}}Events>();{{/apis}}{{/apiInfo}} + } + + /// + /// Configures the HttpClients. + /// + /// + /// + public HostConfiguration Add{{apiName}}HttpClients(Action{{nrt?}} builder = null) + { + return Add{{apiName}}HttpClients((Action{{nrt?}})null, builder); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration Add{{apiName}}HttpClients( + Action{{nrt?}} client, + Action{{nrt?}} builder = null) + { + var wrapped = client != null ? new Action((_, httpClient) => + { + client(httpClient); + }) : null; + return Add{{apiName}}HttpClients(wrapped, builder); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration Add{{apiName}}HttpClients( + Action{{nrt?}} client, + Action{{nrt?}} builder = null) + { + if (client == null) + client = (_, c) => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); + + List builders = new List(); + + {{#apiInfo}}{{#apis}}builders.Add(_services.AddHttpClient<{{interfacePrefix}}{{classname}}, {{classname}}>(client)); + {{/apis}}{{/apiInfo}} + if (builder != null) + foreach (IHttpClientBuilder instance in builders) + builder(instance); + + HttpClientsAdded = true; + + return this; + } + + /// + /// Configures the JsonSerializerSettings + /// + /// + /// + public HostConfiguration ConfigureJsonOptions(Action options) + { + options(_jsonOptions); + + return this; + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + { + return AddTokens(new TTokenBase[]{ token }); + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + { + TokenContainer container = new TokenContainer(tokens); + _services.AddSingleton(services => container); + + return this; + } + + /// + /// Adds a token provider to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration UseProvider() + where TTokenProvider : TokenProvider + where TTokenBase : TokenBase + { + _services.AddSingleton(); + _services.AddSingleton>(services => services.GetRequiredService()); + + return this; + } + } +} diff --git a/sdk/dotnet/templates/JsonConverter.mustache b/sdk/dotnet/templates/JsonConverter.mustache new file mode 100644 index 0000000..d8e203b --- /dev/null +++ b/sdk/dotnet/templates/JsonConverter.mustache @@ -0,0 +1,666 @@ + /// + /// A Json converter for type + /// + {{>visibility}} class {{classname}}JsonConverter : JsonConverter<{{classname}}> + { + {{#allVars}} + {{#isDateTime}} + /// + /// The format to use to serialize {{name}} + /// + public static string {{name}}Format { get; set; } = "{{{dateTimeFormat}}}"; + + {{/isDateTime}} + {{#isDate}} + /// + /// The format to use to serialize {{name}} + /// + public static string {{name}}Format { get; set; } = "{{{dateFormat}}}"; + + {{/isDate}} + {{/allVars}} + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override {{classname}} Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.trimLineBreaks}} + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + {{#allVars}} + Option<{{#isInnerEnum}}{{^isMap}}{{classname}}.{{/isMap}}{{/isInnerEnum}}{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}> {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = default; + {{#-last}} + + {{/-last}} + {{/allVars}} + {{#discriminator}} + {{#children}} + {{#-first}} + string{{nrt?}} discriminator = ClientUtils.GetDiscriminator(utf8JsonReader, "{{discriminator.propertyBaseName}}"); + + {{/-first}} + if (discriminator != null && discriminator.Equals("{{name}}")) + return JsonSerializer.Deserialize<{{{classname}}}>(ref utf8JsonReader, jsonSerializerOptions) ?? throw new JsonException("The result was an unexpected value."); + + {{/children}} + {{/discriminator}} + {{#model.discriminator}} + {{#model.hasDiscriminatorWithNonEmptyMapping}} + {{#mappedModels}} + {{#model}} + {{^vendorExtensions.x-duplicated-data-type}} + {{classname}}{{nrt?}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}} = null; + {{#-last}} + + {{/-last}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/model}} + {{/mappedModels}} + Utf8JsonReader utf8JsonReaderDiscriminator = utf8JsonReader; + while (utf8JsonReaderDiscriminator.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderDiscriminator.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth) + break; + + if (utf8JsonReaderDiscriminator.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderDiscriminator.CurrentDepth - 1) + { + string{{nrt?}} localVarJsonPropertyName = utf8JsonReaderDiscriminator.GetString(); + utf8JsonReaderDiscriminator.Read(); + if (localVarJsonPropertyName{{nrt?}}.Equals("{{propertyBaseName}}"){{#nrt}} ?? false{{/nrt}}) + { + string{{nrt?}} discriminator = utf8JsonReaderDiscriminator.GetString(); + {{#mappedModels}} + if (discriminator{{nrt?}}.Equals("{{mappingName}}"){{#nrt}} ?? false{{/nrt}}) + { + Utf8JsonReader utf8JsonReader{{model.classname}} = utf8JsonReader; + {{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}} = JsonSerializer.Deserialize<{{{model.classname}}}>(ref utf8JsonReader{{model.classname}}, jsonSerializerOptions); + } + {{/mappedModels}} + } + } + } + + {{/model.hasDiscriminatorWithNonEmptyMapping}} + {{/model.discriminator}} + {{^model.discriminator}} + {{#composedSchemas}} + {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = default; + {{#-last}} + + Utf8JsonReader utf8JsonReaderOneOf = utf8JsonReader; + while (utf8JsonReaderOneOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderOneOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderOneOf.CurrentDepth) + break; + + if (utf8JsonReaderOneOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderOneOf.CurrentDepth - 1) + { + {{#oneOf}} + Utf8JsonReader utf8JsonReader{{name}} = utf8JsonReader; + ClientUtils.TryDeserialize<{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}>(ref utf8JsonReader{{name}}, jsonSerializerOptions, out {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}); + {{^-last}} + + {{/-last}} + {{/oneOf}} + } + } + {{/-last}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/oneOf}} + + {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + {{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = default; + {{#-last}} + + Utf8JsonReader utf8JsonReaderAnyOf = utf8JsonReader; + while (utf8JsonReaderAnyOf.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReaderAnyOf.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReaderAnyOf.CurrentDepth) + break; + + if (utf8JsonReaderAnyOf.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReaderAnyOf.CurrentDepth - 1) + { + {{#anyOf}} + Utf8JsonReader utf8JsonReader{{name}} = utf8JsonReader; + ClientUtils.TryDeserialize<{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}>(ref utf8JsonReader{{name}}, jsonSerializerOptions, out {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}); + {{^-last}} + + {{/-last}} + {{/anyOf}} + } + } + {{/-last}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/anyOf}} + + {{/composedSchemas}} + {{/model.discriminator}} + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string{{nrt?}} localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + {{#allVars}} + case "{{baseName}}": + {{#isString}} + {{^isMap}} + {{^isEnum}} + {{^isUuid}} + {{#isDecimal}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.GetDecimal()); + {{/isDecimal}} + {{^isDecimal}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.GetString(){{^isNullable}}{{nrt!}}{{/isNullable}}); + {{/isDecimal}} + {{/isUuid}} + {{/isEnum}} + {{/isMap}} + {{/isString}} + {{#isBoolean}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (bool?)null : utf8JsonReader.GetBoolean()); + {{/isBoolean}} + {{#isNumeric}} + {{^isEnum}} + {{#isDouble}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (double?)null : utf8JsonReader.GetDouble()); + {{/isDouble}} + {{#isDecimal}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (decimal?)null : utf8JsonReader.GetDecimal()); + {{/isDecimal}} + {{#isFloat}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (float?)null : (float)utf8JsonReader.GetDouble()); + {{/isFloat}} + {{#isLong}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? ({{#vendorExtensions.x-unsigned}}u{{/vendorExtensions.x-unsigned}}long?)null : utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int64()); + {{/isLong}} + {{^isLong}} + {{^isFloat}} + {{^isDecimal}} + {{^isDouble}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? ({{#vendorExtensions.x-unsigned}}u{{/vendorExtensions.x-unsigned}}int?)null : utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32()); + {{/isDouble}} + {{/isDecimal}} + {{/isFloat}} + {{/isLong}} + {{/isEnum}} + {{/isNumeric}} + {{#isDate}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}JsonSerializer.Deserialize<{{#supportsDateOnly}}DateOnly{{/supportsDateOnly}}{{^supportsDateOnly}}DateTime{{/supportsDateOnly}}{{#isNullable}}?{{/isNullable}}>(ref utf8JsonReader, jsonSerializerOptions)); + {{/isDate}} + {{#isDateTime}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + {{/isDateTime}} + {{#isEnum}} + {{^isMap}} + {{#isNumeric}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? ({{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}?)null : ({{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}})utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32()); + {{/isNumeric}} + {{^isNumeric}} + string{{nrt?}} {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = utf8JsonReader.GetString(); + {{! A nullable enum may be explicitly null in the payload; still mark the Option as set so a present-but-null value is not rejected as missing. }} + {{^isInnerEnum}} + {{#isNullable}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue == null ? null : {{{datatypeWithEnum}}}ValueConverter.FromStringOrDefault({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue)); + {{/isNullable}} + {{^isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue != null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}{{{datatypeWithEnum}}}ValueConverter.FromStringOrDefault({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue)); + {{/isNullable}} + {{/isInnerEnum}} + {{#isInnerEnum}} + {{#isNullable}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue == null ? null : {{classname}}.{{{datatypeWithEnum}}}FromStringOrDefault({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue)); + {{/isNullable}} + {{^isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue != null) + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}{{classname}}.{{{datatypeWithEnum}}}FromStringOrDefault({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue)); + {{/isNullable}} + {{/isInnerEnum}} + {{/isNumeric}} + {{/isMap}} + {{/isEnum}} + {{#isUuid}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}utf8JsonReader.TokenType == JsonTokenType.Null ? (Guid?)null : utf8JsonReader.GetGuid()); + {{/isUuid}} + {{^isUuid}} + {{^isEnum}} + {{^isString}} + {{^isBoolean}} + {{^isNumeric}} + {{^isDate}} + {{^isDateTime}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} = {{>OptionProperty}}JsonSerializer.Deserialize<{{{datatypeWithEnum}}}>(ref utf8JsonReader, jsonSerializerOptions){{^isNullable}}{{nrt!}}{{/isNullable}}); + {{/isDateTime}} + {{/isDate}} + {{/isNumeric}} + {{/isBoolean}} + {{/isString}} + {{/isEnum}} + {{/isUuid}} + break; + {{/allVars}} + default: + break; + } + } + } + + {{#allVars}} + {{#required}} + if (!{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}.IsSet) + throw new ArgumentException("Property is required for class {{classname}}.", nameof({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}})); + + {{/required}} + {{/allVars}} + {{#allVars}} + {{^isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}.IsSet && {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}.Value == null) + throw new ArgumentNullException(nameof({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}), "Property is not nullable for class {{classname}}."); + + {{/isNullable}} + {{/allVars}} + {{^vendorExtensions.x-duplicated-data-type}} + {{#model.discriminator}} + {{#model.hasDiscriminatorWithNonEmptyMapping}} + {{^model.composedSchemas.anyOf}} + {{#mappedModels}} + if ({{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}} != null) + return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#required}}.Value{{nrt!}}{{^isNullable}}{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}}{{/isNullable}}{{/required}} {{/isDiscriminator}}{{/allVars}}{{/lambda.joinWithComma}}); + + {{#-last}} + throw new JsonException(); + {{/-last}} + {{/mappedModels}} + {{/model.composedSchemas.anyOf}} + {{/model.hasDiscriminatorWithNonEmptyMapping}} + {{/model.discriminator}} + {{^composedSchemas.oneOf}} + {{^required}} + {{#model.composedSchemas.anyOf}} + Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}ParsedValue = {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} == null + ? default + : new Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}); + {{/model.composedSchemas.anyOf}} + {{#-last}} + + {{/-last}} + {{/required}} + return new {{classname}}({{#lambda.joinWithComma}}{{#model.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}ParsedValue{{#required}}.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{nrt!}}{{/vendorExtensions.x-is-value-type}}{{/required}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#required}}.Value{{nrt!}}{{^isNullable}}{{#vendorExtensions.x-is-value-type}}.Value{{nrt!}}{{/vendorExtensions.x-is-value-type}}{{/isNullable}}{{/required}} {{/isDiscriminator}}{{/allVars}}{{/lambda.joinWithComma}}); + {{/composedSchemas.oneOf}} + {{^model.discriminator}} + {{#composedSchemas}} + {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} != null) + return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{^isDiscriminator}}{{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}{{#required}}ParsedValue{{/required}} {{/isDiscriminator}}{{/allVars}}{{/lambda.joinWithComma}}); + + {{/vendorExtensions.x-duplicated-data-type}} + {{#-last}} + throw new JsonException(); + {{/-last}} + {{/oneOf}} + {{/composedSchemas}} + {{/model.discriminator}} + {{/vendorExtensions.x-duplicated-data-type}} + {{/lambda.trimLineBreaks}} + {{/lambda.trimTrailingWithNewLine}} + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions jsonSerializerOptions) + { + {{#lambda.trimLineBreaks}} + {{#lambda.copyText}} + {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}} + {{/lambda.copyText}} + {{#discriminator}} + {{#children}} + if ({{#lambda.paste}}{{/lambda.paste}} is {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}){ + JsonSerializer.Serialize<{{{classname}}}>(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, jsonSerializerOptions); + return; + } + + {{/children}} + {{/discriminator}} + writer.WriteStartObject(); + + {{#model.discriminator}} + {{#model.hasDiscriminatorWithNonEmptyMapping}} + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + {{#isPrimitiveType}} + {{#isString}} + writer.WriteString("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value); + {{/isString}} + {{#isBoolean}} + writer.WriteBoolean("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isBoolean}} + {{#isNumeric}} + writer.WriteNumber("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isNumeric}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + { + {{baseType}}JsonConverter {{#lambda.camelcase_sanitize_param}}{{baseType}}JsonConverter{{/lambda.camelcase_sanitize_param}} = ({{baseType}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}.GetType())); + {{#lambda.camelcase_sanitize_param}}{{baseType}}JsonConverter{{/lambda.camelcase_sanitize_param}}.WriteProperties(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + {{/isPrimitiveType}} + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + {{/model.hasDiscriminatorWithNonEmptyMapping}} + {{/model.discriminator}} + {{^model.discriminator}} + {{#composedSchemas}} + {{#anyOf}} + if ({{#lambda.joinWithAmpersand}}{{^required}}{{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet {{/required}}{{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}} != null{{/lambda.joinWithAmpersand}}) + {{#isPrimitiveType}} + {{#isString}} + writer.WriteString("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value); + {{/isString}} + {{#isBoolean}} + writer.WriteBoolean("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isBoolean}} + {{#isNumeric}} + writer.WriteNumber("{{vendorExtensions.x-base-name}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value.Value); + {{/isNumeric}} + {{#isEnum}} + { + {{datatypeWithEnum}}JsonConverter {{#lambda.camelcase}}{{datatypeWithEnum}}{{/lambda.camelcase}}JsonConverter = ({{datatypeWithEnum}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}}.GetType())); + {{#lambda.camelcase}}{{datatypeWithEnum}}{{/lambda.camelcase}}JsonConverter.Write{{^isEnumRef}}Properties{{/isEnumRef}}(writer, {{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}, jsonSerializerOptions); + } + {{/isEnum}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + { + {{datatypeWithEnum}}JsonConverter {{#lambda.camelcase}}{{datatypeWithEnum}}{{/lambda.camelcase}}JsonConverter = ({{datatypeWithEnum}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{/required}}.GetType())); + {{#lambda.camelcase}}{{datatypeWithEnum}}{{/lambda.camelcase}}JsonConverter.Write{{^isEnumRef}}Properties{{/isEnumRef}}(writer, {{#lambda.camelcase_sanitize_param}}{{model.classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}, jsonSerializerOptions); + } + {{/isPrimitiveType}} + + {{/anyOf}} + {{/composedSchemas}} + {{/model.discriminator}} + WriteProperties(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, jsonSerializerOptions); + writer.WriteEndObject(); + {{/lambda.trimLineBreaks}} + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(Utf8JsonWriter writer, {{classname}} {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions jsonSerializerOptions) + { + {{#lambda.trimTrailingWithNewLine}} + {{#lambda.trimLineBreaks}} + {{#allVars}} + {{^isDiscriminator}} + {{^isNullable}} + {{#vendorExtensions.x-is-reference-type}} + if ({{^required}}{{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet && {{/required}}{{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} == null) + throw new ArgumentNullException(nameof({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}), "Property is required for class {{classname}}."); + + {{/vendorExtensions.x-is-reference-type}} + {{/isNullable}} + {{/isDiscriminator}} + {{/allVars}} + {{#allVars}} + {{#isDiscriminator}} + {{^model.composedSchemas.anyOf}} + {{^model.composedSchemas.oneOf}} + writer.WriteString("{{baseName}}", {{^isEnum}}{{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{/isEnum}}{{#isEnum}}{{#isInnerEnum}}{{classname}}.{{{datatypeWithEnum}}}ToJsonValue{{/isInnerEnum}}{{^isInnerEnum}}{{{datatypeWithEnum}}}ValueConverter.ToJsonValue{{/isInnerEnum}}({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}.Value{{/required}}){{/isEnum}}); + + {{/model.composedSchemas.oneOf}} + {{/model.composedSchemas.anyOf}} + {{/isDiscriminator}} + {{^isDiscriminator}} + {{#isString}} + {{^isMap}} + {{^isEnum}} + {{^isUuid}} + {{#lambda.copyText}} + {{#isDecimal}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}.ToString()); + {{/isDecimal}} + {{^isDecimal}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}); + {{/isDecimal}} + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isUuid}} + {{/isEnum}} + {{/isMap}} + {{/isString}} + {{#isBoolean}} + {{#lambda.copyText}} + writer.WriteBoolean("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isBoolean}} + {{^isEnum}} + {{#isNumeric}} + {{#lambda.copyText}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isNumeric}} + {{/isEnum}} + {{#isDate}} + {{#lambda.copyText}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}.ToString({{name}}Format)); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isDate}} + {{#isDateTime}} + {{#lambda.copyText}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}.ToString({{name}}Format)); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isDateTime}} + {{#isEnum}} + {{#isNumeric}} + {{#lambda.copyText}} + writer.WriteNumber("{{baseName}}", {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}})); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isNumeric}} + {{^isMap}} + {{^isNumeric}} + {{#isInnerEnum}} + {{#isNullable}} + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}{{nrt!}}.Value{{/isNullable}}{{/required}}); + if ({{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue != null) + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue); + else + writer.WriteNull("{{baseName}}"); + + {{/isNullable}} + {{^isNullable}} + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}{{nrt!}}.Value{{/isNullable}}{{/required}}); + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue); + {{/isNullable}} + {{/isInnerEnum}} + {{^isInnerEnum}} + {{#lambda.copyText}} + {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}} + {{/lambda.copyText}} + {{#required}} + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} == null) + writer.WriteNull("{{baseName}}"); + else + { + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}.Value); + {{#allowableValues}} + {{#enumVars}} + {{#-first}} + {{#isString}} + if ({{#lambda.paste}}{{/lambda.paste}}RawValue != null){{! we cant use name here because enumVar also has a name property, so use the paste lambda instead }} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{nameInPascalCase}}{{/lambda.camelcase_sanitize_param}}RawValue); + else + writer.WriteNull("{{baseName}}"); + {{/isString}} + {{^isString}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{nameInPascalCase}}{{/lambda.camelcase_sanitize_param}}RawValue); + {{/isString}} + {{/-first}} + {{/enumVars}} + {{/allowableValues}} + } + {{/isNullable}} + {{^isNullable}} + var {{#lambda.camelcase_sanitize_param}}{{name}}{{/lambda.camelcase_sanitize_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}); + {{#allowableValues}} + {{#enumVars}} + {{#-first}} + {{^isNumeric}} + writer.WriteString("{{baseName}}", {{#lambda.paste}}{{/lambda.paste}}RawValue); + {{/isNumeric}} + {{#isNumeric}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{#lambda.paste}}{{/lambda.paste}}{{/lambda.camelcase_sanitize_param}}RawValue); + {{/isNumeric}} + {{/-first}} + {{/enumVars}} + {{/allowableValues}} + {{/isNullable}} + + {{/required}} + {{^required}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet) + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option{{nrt!}}.Value != null) + { + var {{#lambda.paste}}{{/lambda.paste}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value{{nrt!}}.Value); + writer.{{#lambda.first}}{{#allowableValues}}{{#enumVars}}{{^isNumeric}}WriteString {{/isNumeric}}{{#isNumeric}}WriteNumber {{/isNumeric}}{{/enumVars}}{{/allowableValues}}{{/lambda.first}}("{{baseName}}", {{#lambda.paste}}{{/lambda.paste}}RawValue); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + { + var {{#lambda.paste}}{{/lambda.paste}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{nrt!}}.Value); + writer.{{#lambda.first}}{{#allowableValues}}{{#enumVars}}{{^isNumeric}}WriteString {{/isNumeric}}{{#isNumeric}}WriteNumber {{/isNumeric}}{{/enumVars}}{{/allowableValues}}{{/lambda.first}}("{{baseName}}", {{#lambda.paste}}{{/lambda.paste}}RawValue); + } + {{/isNullable}} + {{/required}} + {{/isInnerEnum}} + {{/isNumeric}} + {{/isMap}} + {{/isEnum}} + {{#isUuid}} + {{#lambda.copyText}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copyText}} + {{#lambda.indent3}} + {{>WriteProperty}}{{! prevent indent}} + {{/lambda.indent3}} + {{/isUuid}} + {{^isUuid}} + {{^isEnum}} + {{^isString}} + {{^isBoolean}} + {{^isNumeric}} + {{^isDate}} + {{^isDateTime}} + {{#required}} + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}} != null) + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + {{/isNullable}} + {{/required}} + {{^required}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.IsSet) + {{#isNullable}} + if ({{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}Option.Value != null) + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_sanitize_param}}{{classname}}{{/lambda.camelcase_sanitize_param}}.{{name}}, jsonSerializerOptions); + } + {{/isNullable}} + {{/required}} + {{/isDateTime}} + {{/isDate}} + {{/isNumeric}} + {{/isBoolean}} + {{/isString}} + {{/isEnum}} + {{/isUuid}} + {{/isDiscriminator}} + {{/allVars}} + {{/lambda.trimLineBreaks}} + {{/lambda.trimTrailingWithNewLine}} + } + } \ No newline at end of file diff --git a/sdk/dotnet/templates/RateLimitProvider`1.mustache b/sdk/dotnet/templates/RateLimitProvider`1.mustache new file mode 100644 index 0000000..83c7207 --- /dev/null +++ b/sdk/dotnet/templates/RateLimitProvider`1.mustache @@ -0,0 +1,96 @@ +// +{{>partial_header}} + +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; +using System.Collections.Generic; +using System.Linq; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. + /// + /// + {{>visibility}} class RateLimitProvider : TokenProvider where TTokenBase : TokenBase + { + internal Dictionary> AvailableTokens { get; } = new{{^net70OrLater}} Dictionary>{{/net70OrLater}}(); + + /// + /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. + /// + /// + public RateLimitProvider(TokenContainer container) + { + foreach(TTokenBase token in container.Tokens) + token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); + + {{#lambda.copy}} + global::System.Threading.Channels.BoundedChannelOptions options = new global::System.Threading.Channels.BoundedChannelOptions(container.Tokens.Count) + { + FullMode = global::System.Threading.Channels.BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(string.Empty, global::System.Threading.Channels.Channel.CreateBounded(options)); + {{/lambda.copy}} + {{#hasApiKeyMethods}} + if (container is TokenContainer apiKeyTokenContainer) + { + string[] headers = apiKeyTokenContainer.Tokens.Select(t => ClientUtils.ApiKeyHeaderToString(t.Header)).Distinct().ToArray(); + + foreach (string header in headers) + { + global::System.Threading.Channels.BoundedChannelOptions options = new global::System.Threading.Channels.BoundedChannelOptions(apiKeyTokenContainer.Tokens.Count(t => ClientUtils.ApiKeyHeaderToString(t.Header).Equals(header))) + { + FullMode = global::System.Threading.Channels.BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(header, global::System.Threading.Channels.Channel.CreateBounded(options)); + } + } + else + { + {{#lambda.indentAll1}} + {{#lambda.paste}} + {{/lambda.paste}} + {{/lambda.indentAll1}} + } + {{/hasApiKeyMethods}} + {{^hasApiKeyMethods}} + {{#lambda.paste}} + {{/lambda.paste}} + {{/hasApiKeyMethods}} + + foreach (var availableToken in AvailableTokens) + foreach(TTokenBase token in container.Tokens) + { + {{#hasApiKeyMethods}} + if (token is ApiKeyToken apiKeyToken) + { + if (ClientUtils.ApiKeyHeaderToString(apiKeyToken.Header) == availableToken.Key) + { + token.TokenBecameAvailable += ((sender) => availableToken.Value.Writer.TryWrite((TTokenBase)sender)); + } + } else + { + token.TokenBecameAvailable += ((sender) => availableToken.Value.Writer.TryWrite((TTokenBase)sender)); + } + {{/hasApiKeyMethods}} + {{^hasApiKeyMethods}} + token.TokenBecameAvailable += ((sender) => availableToken.Value.Writer.TryWrite((TTokenBase)sender)); + {{/hasApiKeyMethods}} + } + } + + public override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(global::System.Threading.CancellationToken){{/netstandard20OrLater}}) + { + if (!AvailableTokens.TryGetValue(header, out global::System.Threading.Channels.Channel{{nrt?}} tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); + } + } +} diff --git a/sdk/dotnet/templates/TokenProvider`1.mustache b/sdk/dotnet/templates/TokenProvider`1.mustache new file mode 100644 index 0000000..524fb2c --- /dev/null +++ b/sdk/dotnet/templates/TokenProvider`1.mustache @@ -0,0 +1,19 @@ +// +{{>partial_header}} + +{{#nrt}} +#nullable enable + +{{/nrt}} +using System; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// A class which will provide tokens. + /// + {{>visibility}} abstract class TokenProvider where TTokenBase : TokenBase + { + public abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(global::System.Threading.CancellationToken){{/netstandard20OrLater}}); + } +} diff --git a/sdk/java-restclient/.gitignore b/sdk/java-restclient/.gitignore new file mode 100644 index 0000000..d919f54 --- /dev/null +++ b/sdk/java-restclient/.gitignore @@ -0,0 +1,2 @@ +# OpenApiGenerator generated meta files +.openapi-generator diff --git a/sdk/java-restclient/.openapi-generator-ignore b/sdk/java-restclient/.openapi-generator-ignore new file mode 100644 index 0000000..963a130 --- /dev/null +++ b/sdk/java-restclient/.openapi-generator-ignore @@ -0,0 +1,19 @@ +.github/** +.gitignore +.travis.yml +README.md +api/** +build.gradle +build.sbt +docs/** +git_push.sh +gradle.properties +gradle/** +gradlew +gradlew.bat +pom.xml +settings.gradle + +src/main/AndroidManifest.xml +src/main/java/com/timr/api/ApiClient.java +src/test/** diff --git a/sdk/java-restclient/build.gradle b/sdk/java-restclient/build.gradle new file mode 100644 index 0000000..3105513 --- /dev/null +++ b/sdk/java-restclient/build.gradle @@ -0,0 +1,80 @@ +plugins { + alias(libs.plugins.openapi) + id 'java-library' +} + +repositories { + mavenCentral() +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(25) + } + withSourcesJar() + withJavadocJar() +} + +dependencies { + implementation platform(libs.spring.boot.dependencies) + + implementation 'tools.jackson.core:jackson-databind' + implementation 'com.fasterxml.jackson.core:jackson-annotations' + // JsonNullable is exposed in generated model getters/setters, so it is part of the public API + api libs.jackson.nullable + + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.apache.httpcomponents.client5:httpclient5' // necessary for PATCH support + // @jakarta.annotation.Generated is emitted on every model + implementation libs.jakarta.annotation + // JSpecify annotations appear on generated public signatures, so consumers need them on their compile classpath + api libs.jspecify + implementation libs.swagger.annotations + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +test { + useJUnitPlatform() +} + +def cleanOpenApiGenerateTask = tasks.register('cleanOpenApiGenerate', Delete) { + delete fileTree("$projectDir/src/main/java/com/timr/api/apis") + delete fileTree("$projectDir/src/main/java/com/timr/api/models") +} + +openApiGenerate { + generatorName = 'java' + outputDir = "$projectDir" + templateDir = "$projectDir/templates" + configOptions = [ + library : 'restclient', + serializationLibrary : 'jackson', + useSpringBoot4 : 'true', + useJackson3 : 'true', + dateLibrary : 'java8', + openApiNullable : 'true', + useJspecify : 'true', + containerDefaultToNull: 'true', + legacyDiscriminatorBehavior: 'true', + interfaceOnly : 'true', + skipDefaultInterface : 'true', + apiPackage : 'com.timr.api.apis', + modelPackage : 'com.timr.api.models', + hideGenerationTimestamp: 'true' + ] +} + +tasks.named('openApiGenerate').configure { task -> + task.dependsOn(cleanOpenApiGenerateTask) +} + +// Generated sources are committed into this module's source set, so everything that reads them runs +// after generation; `build` on its own would otherwise quietly compile the previous generation's output. +tasks.matching { + it.name in ['compileJava', 'compileTestJava', 'processResources', 'processTestResources', 'sourcesJar', 'javadoc'] +}.configureEach { + dependsOn tasks.named('openApiGenerate') +} diff --git a/sdk/java-restclient/openapi-overlay.yaml b/sdk/java-restclient/openapi-overlay.yaml new file mode 100644 index 0000000..78c1fa6 --- /dev/null +++ b/sdk/java-restclient/openapi-overlay.yaml @@ -0,0 +1,52 @@ +overlay: 1.0.0 +info: + title: Java one-of interface support + version: 1.0.0 +actions: + - target: "$['info']" + update: + x-getter: true + x-implements: true + x-is-one-of-interface: true + # Inheritance is a generator capability, not part of the contract: the Java generator can + # extend a shared base, so the discriminator keeps its enum type instead of degrading to String. + - target: "$['components']['schemas']['BreakTimeBase']" + update: + x-parent: true + - target: "$['components']['schemas']['BreakTime']" + update: + x-is-one-of-interface: true + - target: "$['components']['schemas']['BreakTimeUpdate']" + update: + x-is-one-of-interface: true + - target: "$['components']['schemas']['BreakTimeManual']" + update: + x-implements: + - BreakTime + - BreakTimeUpdate + - target: "$['components']['schemas']['BreakTimeOngoing']" + update: + x-implements: + - BreakTime + - BreakTimeUpdate + - target: "$['components']['schemas']['BreakTimeAutomatic']" + update: + x-implements: + - BreakTime + # VacationAccount is the same oneOf + discriminator shape as BreakTime and needs the same + # treatment, otherwise the generator collapses it into one flat class carrying both variants' + # fields. + - target: "$['components']['schemas']['VacationAccountBase']" + update: + x-parent: true + - target: "$['components']['schemas']['VacationAccount']" + update: + x-is-one-of-interface: true + - target: "$['components']['schemas']['VacationAccountDays']" + update: + x-implements: + - VacationAccount + - target: "$['components']['schemas']['VacationAccountMinutes']" + update: + x-implements: + - VacationAccount diff --git a/sdk/java-restclient/src/main/java/com/timr/api/ApiClient.java b/sdk/java-restclient/src/main/java/com/timr/api/ApiClient.java new file mode 100644 index 0000000..5ca1e10 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/ApiClient.java @@ -0,0 +1,561 @@ +package com.timr.api; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.timr.api.auth.OAuth; +import org.openapitools.jackson.nullable.JsonNullableJackson3Module; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.InvalidMediaTypeException; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter; +import org.springframework.util.CollectionUtils; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientException; +import org.springframework.web.util.UriComponentsBuilder; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.cfg.DateTimeFeature; +import tools.jackson.databind.json.JsonMapper; + +import java.text.DateFormat; +import java.text.ParseException; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.Map.Entry; + +/** + * TODO + */ +// DEVNOTE originally: @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.9.0") +public class ApiClient extends JavaTimeFormatter { + + public enum CollectionFormat { + CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null); + + private final String separator; + + CollectionFormat(String separator) { + this.separator = separator; + } + + private String collectionToString(Collection collection) { + return StringUtils.collectionToDelimitedString(collection, separator); + } + } + + private final HttpHeaders defaultHeaders = new HttpHeaders(); + private final MultiValueMap defaultCookies = new LinkedMultiValueMap<>(); + + private String basePath = "https://api.timr.com/v1"; + + private final DateFormat dateFormat; + private final RestClient restClient; + + /** + * The credential sent with every request. The contract defines a single OAuth2 security + * scheme, so there is one credential rather than a registry keyed by scheme name. + * Obtaining and refreshing the token is the caller's business; this client only carries it. + */ + private OAuth authentication = new OAuth(); + + public ApiClient() { + this(RestClient.builder()); + } + + public ApiClient(RestClient.Builder restClientBuilder) { + this.dateFormat = createDefaultDateFormat(); + this.restClient = buildRestClient(restClientBuilder, createDefaultMapper(this.dateFormat)); + this.init(); + } + + public static DateFormat createDefaultDateFormat() { + DateFormat dateFormat = new RFC3339DateFormat(); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // TODO check if necessary + return dateFormat; + } + + static JsonMapper createDefaultMapper(DateFormat dateFormat) { + return JsonMapper.builder() + .addModule(new JsonNullableJackson3Module()) + .addModule(new RFC3339JavaTimeModule()) + .changeDefaultPropertyInclusion(incl -> incl.withValueInclusion(JsonInclude.Include.NON_NULL)) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(DateTimeFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, + DateTimeFeature.WRITE_DATES_WITH_CONTEXT_TIME_ZONE) + .defaultDateFormat(dateFormat) + .build(); + } + + /** + * Build the RestClient used to make HTTP requests. + * + * @param mapper JsonMapper used for serialize/deserialize + * @return RestClient + */ + private static RestClient buildRestClient(RestClient.Builder builder, JsonMapper mapper) { + return builder + .configureMessageConverters(converters -> converters.addCustomConverter(new JacksonJsonHttpMessageConverter(mapper))) + // .requestFactory(new HttpComponentsClientHttpRequestFactory()) // necessary for PATCH support + .build(); + } + + protected void init() { + } + + /** + * Get the current base path + * @return String the base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set the base path, which should include the host + * @param basePath the base path + * @return ApiClient this client + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * The credential sent with every request, for setting the access token on it. + * + * @return the current authentication + */ + public OAuth getAuthentication() { + return authentication; + } + + /** + * Replaces the credential sent with every request, for a caller that supplies its own — + * one backed by a token supplier that refreshes, for instance. + * + * @param authentication the authentication to use + */ + public void setAuthentication(OAuth authentication) { + this.authentication = Objects.requireNonNull(authentication, "authentication"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent the user agent string + * @return ApiClient this client + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param name The header's name + * @param value The header's value + * @return ApiClient this client + */ + public ApiClient addDefaultHeader(String name, String value) { + defaultHeaders.set(name, value); + return this; + } + + /** + * Add a default cookie. + * + * @param name The cookie's name + * @param value The cookie's value + * @return ApiClient this client + */ + public ApiClient addDefaultCookie(String name, String value) { + if (defaultCookies.containsKey(name)) { + defaultCookies.remove(name); + } + defaultCookies.add(name, value); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + * @return DateFormat format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * @param param the object to convert + * @return String the parameter represented as a String + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate( (Date) param); + } else if (param instanceof OffsetDateTime) { + return formatOffsetDateTime((OffsetDateTime) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection) param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Converts a parameter to a {@link MultiValueMap} for use in REST requests + * @param collectionFormat The format to convert to + * @param name The name of the parameter + * @param value The parameter's value + * @return a Map containing the String value(s) of the input parameter + */ + public MultiValueMap parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) { + final MultiValueMap params = new LinkedMultiValueMap<>(); + + if (name == null || name.isEmpty() || value == null) { + return params; + } + + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + if (value instanceof Map) { + @SuppressWarnings("unchecked") + final Map valuesMap = (Map) value; + for (final Entry entry : valuesMap.entrySet()) { + params.add(entry.getKey(), parameterToString(entry.getValue())); + } + return params; + } + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(name, parameterToString(value)); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + if (collectionFormat.equals(CollectionFormat.MULTI)) { + for (Object item : valueCollection) { + params.add(name, parameterToString(item)); + } + return params; + } + + List values = new ArrayList<>(); + for(Object o : valueCollection) { + values.add(parameterToString(o)); + } + params.add(name, collectionFormat.collectionToString(values)); + + return params; + } + + /** + * Check if the given {@code String} is a JSON MIME. + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(String mediaType) { + // "* / *" is default to JSON + if ("*/*".equals(mediaType)) { + return true; + } + + try { + return isJsonMime(MediaType.parseMediaType(mediaType)); + } catch (InvalidMediaTypeException e) { + } + return false; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(MediaType mediaType) { + return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*(\\+json|ndjson)[;]?\\s*$")); + } + + /** + * Check if the given {@code String} is a Problem JSON MIME (RFC-7807). + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents Problem JSON, false otherwise + */ + public boolean isProblemJsonMime(String mediaType) { + return "application/problem+json".equalsIgnoreCase(mediaType); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return List The list of MediaTypes to use for the Accept header + */ + public List selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + MediaType mediaType = MediaType.parseMediaType(accept); + if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) { + return Collections.singletonList(mediaType); + } + } + return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts)); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return MediaType The Content-Type header to use. If the given array is empty, null will be returned. + */ + public MediaType selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return null; + } + for (String contentType : contentTypes) { + MediaType mediaType = MediaType.parseMediaType(contentType); + if (isJsonMime(mediaType)) { + return mediaType; + } + } + return MediaType.parseMediaType(contentTypes[0]); + } + + /** + * Select the body to use for the request + * + * @param obj the body object + * @param formParams the form parameters + * @param contentType the content type of the request + * @return Object the selected body + */ + protected Object selectBody(Object obj, MultiValueMap formParams, MediaType contentType) { + boolean isForm = MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType); + return isForm ? formParams : obj; + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param the return type to use + * @param path The sub-path of the HTTP URL + * @param method The request method + * @param pathParams The path parameters + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return The response body in chosen type + */ + public ResponseSpec invokeAPI(String path, HttpMethod method, Map pathParams, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap cookieParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames, ParameterizedTypeReference returnType) throws RestClientException { + final RestClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames); + return requestBuilder.retrieve(); + } + + /** + * Include queryParams in uriParams taking into account the paramName + * @param queryParams The query parameters + * @param uriParams The path parameters + * return templatized query string + */ + private String generateQueryUri(MultiValueMap queryParams, Map uriParams) { + StringBuilder queryBuilder = new StringBuilder(); + queryParams.forEach((name, values) -> { + if (CollectionUtils.isEmpty(values)) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(name); + } else { + int valueItemCounter = 0; + for (Object value : values) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(name); + if (value != null) { + String templatizedKey = name + valueItemCounter++; + uriParams.put(templatizedKey, value.toString()); + queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + } + } + } + }); + return queryBuilder.toString(); + } + + private RestClient.RequestBodySpec prepareRequest(String path, HttpMethod method, Map pathParams, + MultiValueMap queryParams, Object body, HttpHeaders headerParams, + MultiValueMap cookieParams, MultiValueMap formParams, List accept, + MediaType contentType, String[] authNames) { + updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); + + final UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(basePath).path(path); + + String finalUri = builder.build(false).toUriString(); + Map uriParams = new HashMap<>(); + uriParams.putAll(pathParams); + + if (queryParams != null && !queryParams.isEmpty()) { + //Include queryParams in uriParams taking into account the paramName + String queryUri = generateQueryUri(queryParams, uriParams); + //Append to finalUri the templatized query string like "?param1={param1Value}&....... + finalUri += "?" + queryUri; + } + + final RestClient.RequestBodySpec requestBuilder = restClient.method(method).uri(finalUri, uriParams); + + if (accept != null) { + requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); + } + if(contentType != null) { + requestBuilder.contentType(contentType); + } + + addHeadersToRequest(headerParams, requestBuilder); + addHeadersToRequest(defaultHeaders, requestBuilder); + addCookiesToRequest(cookieParams, requestBuilder); + addCookiesToRequest(defaultCookies, requestBuilder); + + var selectedBody = selectBody(body, formParams, contentType); + if (selectedBody != null) { + requestBuilder.body(selectedBody); + } + + return requestBuilder; + } + + /** + * Add headers to the request that is being built + * @param headers The headers to add + * @param requestBuilder The current request + */ + protected void addHeadersToRequest(HttpHeaders headers, RestClient.RequestBodySpec requestBuilder) { + for (Entry> entry : headers.headerSet()) { + List values = entry.getValue(); + for(String value : values) { + if (value != null) { + requestBuilder.header(entry.getKey(), value); + } + } + } + } + + /** + * Add cookies to the request that is being built + * + * @param cookies The cookies to add + * @param requestBuilder The current request + */ + protected void addCookiesToRequest(MultiValueMap cookies, RestClient.RequestBodySpec requestBuilder) { + if (!cookies.isEmpty()) { + requestBuilder.header("Cookie", buildCookieHeader(cookies)); + } + } + + /** + * Build cookie header. Keeps a single value per cookie (as per + * RFC6265 section 5.3). + * + * @param cookies map all cookies + * @return header string for cookies. + */ + private String buildCookieHeader(MultiValueMap cookies) { + final StringBuilder cookieValue = new StringBuilder(); + String delimiter = ""; + for (final Map.Entry> entry : cookies.entrySet()) { + final String value = entry.getValue().get(entry.getValue().size() - 1); + cookieValue.append(String.format("%s%s=%s", delimiter, entry.getKey(), value)); + delimiter = "; "; + } + return cookieValue.toString(); + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams The query parameters + * @param headerParams The header parameters + * @param cookieParams the cookie parameters + */ + protected void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + // authNames is the generated call site telling us which schemes the operation declares. + // The contract declares exactly one, so the single credential applies to every request. + authentication.applyToParams(queryParams, headerParams, cookieParams); + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param values The values of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(CollectionFormat collectionFormat, Collection values) { + // create the value based on the collection format + if (CollectionFormat.MULTI.equals(collectionFormat)) { + // not valid for path params + return parameterToString(values); + } + + // collectionFormat is assumed to be "csv" by default + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + return collectionFormat.collectionToString(values); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/JavaTimeFormatter.java b/sdk/java-restclient/src/main/java/com/timr/api/JavaTimeFormatter.java new file mode 100644 index 0000000..904acae --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/JavaTimeFormatter.java @@ -0,0 +1,68 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.timr.api; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class JavaTimeFormatter { + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given {@code OffsetDateTime} object into string. + * + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} \ No newline at end of file diff --git a/sdk/java-restclient/src/main/java/com/timr/api/RFC3339DateFormat.java b/sdk/java-restclient/src/main/java/com/timr/api/RFC3339DateFormat.java new file mode 100644 index 0000000..2d53335 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/RFC3339DateFormat.java @@ -0,0 +1,57 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.timr.api; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.text.DecimalFormat; +import java.util.GregorianCalendar; +import java.util.TimeZone; +import tools.jackson.databind.util.StdDateFormat; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + this.numberFormat = new DecimalFormat(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return super.clone(); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/RFC3339InstantDeserializer.java b/sdk/java-restclient/src/main/java/com/timr/api/RFC3339InstantDeserializer.java new file mode 100644 index 0000000..13b2f8e --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/RFC3339InstantDeserializer.java @@ -0,0 +1,100 @@ +/* + * timr API + * timr API for time tracking + * + * The version of the OpenAPI document: 0.2.20 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.timr.api; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.Temporal; +import java.time.temporal.TemporalAccessor; +import java.util.function.BiFunction; +import java.util.function.Function; + +import tools.jackson.core.JacksonException; +import tools.jackson.core.JsonParser; +import tools.jackson.databind.DeserializationContext; +import tools.jackson.databind.cfg.DateTimeFeature; +import tools.jackson.databind.ext.javatime.deser.InstantDeserializer; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class RFC3339InstantDeserializer extends InstantDeserializer { + private static final long serialVersionUID = 1L; + private final static boolean DEFAULT_NORMALIZE_ZONE_ID = DateTimeFeature.NORMALIZE_DESERIALIZED_ZONE_ID.enabledByDefault(); + private final static boolean DEFAULT_ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS + = DateTimeFeature.ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS.enabledByDefault(); + + public static final RFC3339InstantDeserializer INSTANT = new RFC3339InstantDeserializer<>( + Instant.class, DateTimeFormatter.ISO_INSTANT, + Instant::from, + a -> Instant.ofEpochMilli( a.value ), + a -> Instant.ofEpochSecond( a.integer, a.fraction ), + null, + true, // yes, replace zero offset with Z + DEFAULT_NORMALIZE_ZONE_ID, + DEFAULT_ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS + ); + + public static final RFC3339InstantDeserializer OFFSET_DATE_TIME = new RFC3339InstantDeserializer<>( + OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, + OffsetDateTime::from, + a -> OffsetDateTime.ofInstant( Instant.ofEpochMilli( a.value ), a.zoneId ), + a -> OffsetDateTime.ofInstant( Instant.ofEpochSecond( a.integer, a.fraction ), a.zoneId ), + (d, z) -> ( d.isEqual( OffsetDateTime.MIN ) || d.isEqual( OffsetDateTime.MAX ) ? + d : + d.withOffsetSameInstant( z.getRules().getOffset( d.toLocalDateTime() ) ) ), + true, // yes, replace zero offset with Z + DEFAULT_NORMALIZE_ZONE_ID, + DEFAULT_ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS + ); + + public static final RFC3339InstantDeserializer ZONED_DATE_TIME = new RFC3339InstantDeserializer<>( + ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, + ZonedDateTime::from, + a -> ZonedDateTime.ofInstant( Instant.ofEpochMilli( a.value ), a.zoneId ), + a -> ZonedDateTime.ofInstant( Instant.ofEpochSecond( a.integer, a.fraction ), a.zoneId ), + ZonedDateTime::withZoneSameInstant, + false, // keep zero offset and Z separate since zones explicitly supported + DEFAULT_NORMALIZE_ZONE_ID, + DEFAULT_ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS + ); + + protected RFC3339InstantDeserializer( + Class supportedType, + DateTimeFormatter formatter, + Function parsedToValue, + Function fromMilliseconds, + Function fromNanoseconds, + BiFunction adjust, + boolean replaceZeroOffsetAsZ, + boolean normalizeZoneId, + boolean readNumericStringsAsTimestamp) { + super( + supportedType, + formatter, + parsedToValue, + fromMilliseconds, + fromNanoseconds, + adjust, + replaceZeroOffsetAsZ, + normalizeZoneId, + readNumericStringsAsTimestamp + ); + } + + @Override + protected T _fromString(JsonParser p, DeserializationContext ctxt, String string0) throws JacksonException { + return super._fromString(p, ctxt, string0.replace( ' ', 'T' )); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/RFC3339JavaTimeModule.java b/sdk/java-restclient/src/main/java/com/timr/api/RFC3339JavaTimeModule.java new file mode 100644 index 0000000..8af6aab --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/RFC3339JavaTimeModule.java @@ -0,0 +1,32 @@ +/* + * timr API + * timr API for time tracking + * + * The version of the OpenAPI document: 0.2.20 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.timr.api; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZonedDateTime; + +import tools.jackson.databind.module.SimpleModule; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class RFC3339JavaTimeModule extends SimpleModule { + private static final long serialVersionUID = 1L; + + public RFC3339JavaTimeModule() { + super("RFC3339JavaTimeModule"); + addDeserializer(Instant.class, RFC3339InstantDeserializer.INSTANT); + addDeserializer(OffsetDateTime.class, RFC3339InstantDeserializer.OFFSET_DATE_TIME); + addDeserializer(ZonedDateTime.class, RFC3339InstantDeserializer.ZONED_DATE_TIME); + } + +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/ServerConfiguration.java b/sdk/java-restclient/src/main/java/com/timr/api/ServerConfiguration.java new file mode 100644 index 0000000..801f285 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/ServerConfiguration.java @@ -0,0 +1,72 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replace("{" + name + "}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/ServerVariable.java b/sdk/java-restclient/src/main/java/com/timr/api/ServerVariable.java new file mode 100644 index 0000000..73638a0 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/ServerVariable.java @@ -0,0 +1,37 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/StringUtil.java b/sdk/java-restclient/src/main/java/com/timr/api/StringUtil.java new file mode 100644 index 0000000..45b3875 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/StringUtil.java @@ -0,0 +1,83 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api; + +import java.util.Collection; +import java.util.Iterator; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/TimrAutoConfiguration.java b/sdk/java-restclient/src/main/java/com/timr/api/TimrAutoConfiguration.java new file mode 100644 index 0000000..212df3b --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/TimrAutoConfiguration.java @@ -0,0 +1,89 @@ +package com.timr.api; + +import com.timr.api.apis.*; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.context.annotation.Bean; + +@AutoConfiguration +public class TimrAutoConfiguration { + + @Bean + @ConditionalOnBean(ApiClient.class) + public CarApi carApi(ApiClient apiClient) { + return new CarApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public DriveLogApi driveLogApi(ApiClient apiClient) { + return new DriveLogApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public DriveLogCategoryApi driveLogCategoryApi(ApiClient apiClient) { + return new DriveLogCategoryApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public HolidayCalendarApi holidayCalendarApi(ApiClient apiClient) { + return new HolidayCalendarApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public ProjectTimeApi projectTimeApi(ApiClient apiClient) { + return new ProjectTimeApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public TaskApi taskApi(ApiClient apiClient) { + return new TaskApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public TimeAccountApi timeAccountApi(ApiClient apiClient) { + return new TimeAccountApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public TrackApi trackApi(ApiClient apiClient) { + return new TrackApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public UserApi userApi(ApiClient apiClient) { + return new UserApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public WorkingTimeApi workingTimeApi(ApiClient apiClient) { + return new WorkingTimeApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public WorkingTimeDateSpanApi workingTimeDateSpanApi(ApiClient apiClient) { + return new WorkingTimeDateSpanApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public WorkingTimeTypeApi workingTimeTypeApi(ApiClient apiClient) { + return new WorkingTimeTypeApi(apiClient); + } + + @Bean + @ConditionalOnBean(ApiClient.class) + public WorkScheduleModelApi workScheduleModelApi(ApiClient apiClient) { + return new WorkScheduleModelApi(apiClient); + } + +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/CarApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/CarApi.java new file mode 100644 index 0000000..7a62892 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/CarApi.java @@ -0,0 +1,433 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Car; +import com.timr.api.models.CarCreate; +import com.timr.api.models.CarUpdate; +import com.timr.api.models.CarsPage; +import com.timr.api.models.CarsSortColumn; +import com.timr.api.models.Error; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class CarApi { + private ApiClient apiClient; + + public CarApi() { + this(new ApiClient()); + } + + public CarApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a Car + * Creates a Car from the data in the request body. + *

201 - The created Car. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param carCreate Car entity + * @return Car + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createCarRequestCreation(CarCreate carCreate) throws RestClientResponseException { + Object postBody = carCreate; + // verify the required parameter 'carCreate' is set + if (carCreate == null) { + throw new RestClientResponseException("Missing the required parameter 'carCreate' when calling createCar", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/cars", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Car + * Creates a Car from the data in the request body. + *

201 - The created Car. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param carCreate Car entity + * @return Car + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Car createCar( CarCreate carCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createCarRequestCreation(carCreate).body(localVarReturnType); + } + + /** + * Create a Car + * Creates a Car from the data in the request body. + *

201 - The created Car. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param carCreate Car entity + * @return ResponseEntity<Car> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createCarWithHttpInfo( CarCreate carCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createCarRequestCreation(carCreate).toEntity(localVarReturnType); + } + + /** + * Create a Car + * Creates a Car from the data in the request body. + *

201 - The created Car. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param carCreate Car entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createCarWithResponseSpec(CarCreate carCreate) throws RestClientResponseException { + return createCarRequestCreation(carCreate); + } + + /** + * List Cars + * Lists the Cars the authenticated user or API token can access. + *

200 - Page of Cars. + *

400 - Bad Request + * @param nameOrPlate Only return Cars whose name or plate contains this text. + * @param usable Only return Cars that are usable (true) or not usable (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return CarsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchCarsRequestCreation(@Nullable String nameOrPlate, @Nullable Boolean usable, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable CarsSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "name_or_plate", nameOrPlate)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "usable", usable)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/cars", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Cars + * Lists the Cars the authenticated user or API token can access. + *

200 - Page of Cars. + *

400 - Bad Request + * @param nameOrPlate Only return Cars whose name or plate contains this text. + * @param usable Only return Cars that are usable (true) or not usable (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return CarsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public CarsPage fetchCars( String nameOrPlate, Boolean usable, String pageToken, Integer limit, SortDirection sortDirection, CarsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchCarsRequestCreation(nameOrPlate, usable, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Cars + * Lists the Cars the authenticated user or API token can access. + *

200 - Page of Cars. + *

400 - Bad Request + * @param nameOrPlate Only return Cars whose name or plate contains this text. + * @param usable Only return Cars that are usable (true) or not usable (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<CarsPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchCarsWithHttpInfo( String nameOrPlate, Boolean usable, String pageToken, Integer limit, SortDirection sortDirection, CarsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchCarsRequestCreation(nameOrPlate, usable, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Cars + * Lists the Cars the authenticated user or API token can access. + *

200 - Page of Cars. + *

400 - Bad Request + * @param nameOrPlate Only return Cars whose name or plate contains this text. + * @param usable Only return Cars that are usable (true) or not usable (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchCarsWithResponseSpec(@Nullable String nameOrPlate, @Nullable Boolean usable, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable CarsSortColumn sortBy) throws RestClientResponseException { + return fetchCarsRequestCreation(nameOrPlate, usable, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Car + * Returns a single Car by its ID. + *

200 - The requested Car. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Car. + * @return Car + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getCarRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getCar", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/cars/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Car + * Returns a single Car by its ID. + *

200 - The requested Car. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Car. + * @return Car + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Car getCar( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getCarRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Car + * Returns a single Car by its ID. + *

200 - The requested Car. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Car. + * @return ResponseEntity<Car> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getCarWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getCarRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Car + * Returns a single Car by its ID. + *

200 - The requested Car. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Car. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getCarWithResponseSpec(String id) throws RestClientResponseException { + return getCarRequestCreation(id); + } + + /** + * Update a Car + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Car. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Car. + * @param carUpdate Car entity + * @return Car + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec updateCarRequestCreation(String id, CarUpdate carUpdate) throws RestClientResponseException { + Object postBody = carUpdate; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling updateCar", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'carUpdate' is set + if (carUpdate == null) { + throw new RestClientResponseException("Missing the required parameter 'carUpdate' when calling updateCar", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/cars/{id}", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Update a Car + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Car. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Car. + * @param carUpdate Car entity + * @return Car + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Car updateCar( String id, CarUpdate carUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateCarRequestCreation(id, carUpdate).body(localVarReturnType); + } + + /** + * Update a Car + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Car. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Car. + * @param carUpdate Car entity + * @return ResponseEntity<Car> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateCarWithHttpInfo( String id, CarUpdate carUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateCarRequestCreation(id, carUpdate).toEntity(localVarReturnType); + } + + /** + * Update a Car + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Car. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Car. + * @param carUpdate Car entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateCarWithResponseSpec(String id, CarUpdate carUpdate) throws RestClientResponseException { + return updateCarRequestCreation(id, carUpdate); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/DriveLogApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/DriveLogApi.java new file mode 100644 index 0000000..7afa8f2 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/DriveLogApi.java @@ -0,0 +1,653 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.DeletedEntryPage; +import com.timr.api.models.DeletedEntrySortColumn; +import com.timr.api.models.DriveLog; +import com.timr.api.models.DriveLogCreate; +import com.timr.api.models.DriveLogStatus; +import com.timr.api.models.DriveLogUpdate; +import com.timr.api.models.DriveLogsPage; +import com.timr.api.models.DriveLogsSortColumn; +import com.timr.api.models.Error; +import java.time.LocalDate; +import org.jspecify.annotations.Nullable; +import java.time.OffsetDateTime; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogApi { + private ApiClient apiClient; + + public DriveLogApi() { + this(new ApiClient()); + } + + public DriveLogApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a Drive Log + * Creates a Drive Log from the data in the request body. + *

201 - The created Drive Log. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param driveLogCreate Drive Log entity + * @return DriveLog + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createDriveLogRequestCreation(DriveLogCreate driveLogCreate) throws RestClientResponseException { + Object postBody = driveLogCreate; + // verify the required parameter 'driveLogCreate' is set + if (driveLogCreate == null) { + throw new RestClientResponseException("Missing the required parameter 'driveLogCreate' when calling createDriveLog", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Drive Log + * Creates a Drive Log from the data in the request body. + *

201 - The created Drive Log. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param driveLogCreate Drive Log entity + * @return DriveLog + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DriveLog createDriveLog( DriveLogCreate driveLogCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createDriveLogRequestCreation(driveLogCreate).body(localVarReturnType); + } + + /** + * Create a Drive Log + * Creates a Drive Log from the data in the request body. + *

201 - The created Drive Log. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param driveLogCreate Drive Log entity + * @return ResponseEntity<DriveLog> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createDriveLogWithHttpInfo( DriveLogCreate driveLogCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createDriveLogRequestCreation(driveLogCreate).toEntity(localVarReturnType); + } + + /** + * Create a Drive Log + * Creates a Drive Log from the data in the request body. + *

201 - The created Drive Log. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param driveLogCreate Drive Log entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createDriveLogWithResponseSpec(DriveLogCreate driveLogCreate) throws RestClientResponseException { + return createDriveLogRequestCreation(driveLogCreate); + } + + /** + * Delete a Drive Log + * Deletes the Drive Log, including its Track. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Drive Log. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteDriveLogRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling deleteDriveLog", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs/{id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Drive Log + * Deletes the Drive Log, including its Track. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Drive Log. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteDriveLog( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteDriveLogRequestCreation(id).body(localVarReturnType); + } + + /** + * Delete a Drive Log + * Deletes the Drive Log, including its Track. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Drive Log. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteDriveLogWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteDriveLogRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Delete a Drive Log + * Deletes the Drive Log, including its Track. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Drive Log. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteDriveLogWithResponseSpec(String id) throws RestClientResponseException { + return deleteDriveLogRequestCreation(id); + } + + /** + * List deleted Drive Logs + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Drive Logs. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DeletedEntryPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchDeletedDriveLogsRequestCreation(@Nullable OffsetDateTime lastModifiedAfter, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DeletedEntrySortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs:deleted", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List deleted Drive Logs + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Drive Logs. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DeletedEntryPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DeletedEntryPage fetchDeletedDriveLogs( OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDeletedDriveLogsRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List deleted Drive Logs + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Drive Logs. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<DeletedEntryPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDeletedDriveLogsWithHttpInfo( OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDeletedDriveLogsRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List deleted Drive Logs + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Drive Logs. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchDeletedDriveLogsWithResponseSpec(@Nullable OffsetDateTime lastModifiedAfter, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DeletedEntrySortColumn sortBy) throws RestClientResponseException { + return fetchDeletedDriveLogsRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + } + + /** + * List Drive Logs + * Lists the Drive Logs the authenticated user or API token can access. + *

200 - Page of Drive Logs. + *

400 - Bad Request + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param cars Only return entries recorded for these Cars. + * @param driveLogCategories Only return entries in these Drive Log Categories. + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param details Only return Drive Logs whose route, purpose or visited contains this text. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param hasTrack Only return Drive Logs that have a Track (true) or have none (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DriveLogsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchDriveLogsRequestCreation(@Nullable LocalDate startFrom, @Nullable LocalDate startTo, @Nullable OffsetDateTime lastModifiedAfter, @Nullable List cars, @Nullable List driveLogCategories, @Nullable List statuses, @Nullable List users, @Nullable String details, @Nullable Boolean changed, @Nullable Boolean hasTrack, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DriveLogsSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_from", startFrom)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_to", startTo)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "cars", cars)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "drive_log_categories", driveLogCategories)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "statuses", statuses)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "users", users)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "details", details)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "changed", changed)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "has_track", hasTrack)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Drive Logs + * Lists the Drive Logs the authenticated user or API token can access. + *

200 - Page of Drive Logs. + *

400 - Bad Request + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param cars Only return entries recorded for these Cars. + * @param driveLogCategories Only return entries in these Drive Log Categories. + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param details Only return Drive Logs whose route, purpose or visited contains this text. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param hasTrack Only return Drive Logs that have a Track (true) or have none (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DriveLogsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DriveLogsPage fetchDriveLogs( LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, List cars, List driveLogCategories, List statuses, List users, String details, Boolean changed, Boolean hasTrack, String pageToken, Integer limit, SortDirection sortDirection, DriveLogsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDriveLogsRequestCreation(startFrom, startTo, lastModifiedAfter, cars, driveLogCategories, statuses, users, details, changed, hasTrack, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Drive Logs + * Lists the Drive Logs the authenticated user or API token can access. + *

200 - Page of Drive Logs. + *

400 - Bad Request + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param cars Only return entries recorded for these Cars. + * @param driveLogCategories Only return entries in these Drive Log Categories. + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param details Only return Drive Logs whose route, purpose or visited contains this text. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param hasTrack Only return Drive Logs that have a Track (true) or have none (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<DriveLogsPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDriveLogsWithHttpInfo( LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, List cars, List driveLogCategories, List statuses, List users, String details, Boolean changed, Boolean hasTrack, String pageToken, Integer limit, SortDirection sortDirection, DriveLogsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDriveLogsRequestCreation(startFrom, startTo, lastModifiedAfter, cars, driveLogCategories, statuses, users, details, changed, hasTrack, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Drive Logs + * Lists the Drive Logs the authenticated user or API token can access. + *

200 - Page of Drive Logs. + *

400 - Bad Request + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param cars Only return entries recorded for these Cars. + * @param driveLogCategories Only return entries in these Drive Log Categories. + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param details Only return Drive Logs whose route, purpose or visited contains this text. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param hasTrack Only return Drive Logs that have a Track (true) or have none (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchDriveLogsWithResponseSpec(@Nullable LocalDate startFrom, @Nullable LocalDate startTo, @Nullable OffsetDateTime lastModifiedAfter, @Nullable List cars, @Nullable List driveLogCategories, @Nullable List statuses, @Nullable List users, @Nullable String details, @Nullable Boolean changed, @Nullable Boolean hasTrack, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DriveLogsSortColumn sortBy) throws RestClientResponseException { + return fetchDriveLogsRequestCreation(startFrom, startTo, lastModifiedAfter, cars, driveLogCategories, statuses, users, details, changed, hasTrack, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Drive Log + * Returns a single Drive Log by its ID. + *

200 - The requested Drive Log. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log. + * @return DriveLog + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getDriveLogRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getDriveLog", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Drive Log + * Returns a single Drive Log by its ID. + *

200 - The requested Drive Log. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log. + * @return DriveLog + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DriveLog getDriveLog( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getDriveLogRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Drive Log + * Returns a single Drive Log by its ID. + *

200 - The requested Drive Log. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log. + * @return ResponseEntity<DriveLog> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getDriveLogWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getDriveLogRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Drive Log + * Returns a single Drive Log by its ID. + *

200 - The requested Drive Log. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getDriveLogWithResponseSpec(String id) throws RestClientResponseException { + return getDriveLogRequestCreation(id); + } + + /** + * Update a Drive Log + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Drive Log. + * @param driveLogUpdate Drive Log entity + * @return DriveLog + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec updateDriveLogRequestCreation(String id, DriveLogUpdate driveLogUpdate) throws RestClientResponseException { + Object postBody = driveLogUpdate; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling updateDriveLog", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'driveLogUpdate' is set + if (driveLogUpdate == null) { + throw new RestClientResponseException("Missing the required parameter 'driveLogUpdate' when calling updateDriveLog", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs/{id}", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Update a Drive Log + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Drive Log. + * @param driveLogUpdate Drive Log entity + * @return DriveLog + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DriveLog updateDriveLog( String id, DriveLogUpdate driveLogUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateDriveLogRequestCreation(id, driveLogUpdate).body(localVarReturnType); + } + + /** + * Update a Drive Log + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Drive Log. + * @param driveLogUpdate Drive Log entity + * @return ResponseEntity<DriveLog> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateDriveLogWithHttpInfo( String id, DriveLogUpdate driveLogUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateDriveLogRequestCreation(id, driveLogUpdate).toEntity(localVarReturnType); + } + + /** + * Update a Drive Log + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Drive Log. + * @param driveLogUpdate Drive Log entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateDriveLogWithResponseSpec(String id, DriveLogUpdate driveLogUpdate) throws RestClientResponseException { + return updateDriveLogRequestCreation(id, driveLogUpdate); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/DriveLogCategoryApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/DriveLogCategoryApi.java new file mode 100644 index 0000000..7021dc1 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/DriveLogCategoryApi.java @@ -0,0 +1,225 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.DriveLogCategoriesPage; +import com.timr.api.models.DriveLogCategoriesSortColumn; +import com.timr.api.models.DriveLogCategory; +import com.timr.api.models.Error; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogCategoryApi { + private ApiClient apiClient; + + public DriveLogCategoryApi() { + this(new ApiClient()); + } + + public DriveLogCategoryApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * List Drive Log Categories + * Lists the Drive Log Categories the authenticated user or API token can access. + *

200 - Page of Drive Log Categories. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DriveLogCategoriesPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchDriveLogCategoriesRequestCreation(@Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DriveLogCategoriesSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-log-categories", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Drive Log Categories + * Lists the Drive Log Categories the authenticated user or API token can access. + *

200 - Page of Drive Log Categories. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DriveLogCategoriesPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DriveLogCategoriesPage fetchDriveLogCategories( String pageToken, Integer limit, SortDirection sortDirection, DriveLogCategoriesSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDriveLogCategoriesRequestCreation(pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Drive Log Categories + * Lists the Drive Log Categories the authenticated user or API token can access. + *

200 - Page of Drive Log Categories. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<DriveLogCategoriesPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDriveLogCategoriesWithHttpInfo( String pageToken, Integer limit, SortDirection sortDirection, DriveLogCategoriesSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDriveLogCategoriesRequestCreation(pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Drive Log Categories + * Lists the Drive Log Categories the authenticated user or API token can access. + *

200 - Page of Drive Log Categories. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchDriveLogCategoriesWithResponseSpec(@Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DriveLogCategoriesSortColumn sortBy) throws RestClientResponseException { + return fetchDriveLogCategoriesRequestCreation(pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Drive Log Category + * Returns a single Drive Log Category by its ID. + *

200 - The requested Drive Log Category. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log Category. + * @return DriveLogCategory + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getDriveLogCategoryRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getDriveLogCategory", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-log-categories/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Drive Log Category + * Returns a single Drive Log Category by its ID. + *

200 - The requested Drive Log Category. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log Category. + * @return DriveLogCategory + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DriveLogCategory getDriveLogCategory( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getDriveLogCategoryRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Drive Log Category + * Returns a single Drive Log Category by its ID. + *

200 - The requested Drive Log Category. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log Category. + * @return ResponseEntity<DriveLogCategory> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getDriveLogCategoryWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getDriveLogCategoryRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Drive Log Category + * Returns a single Drive Log Category by its ID. + *

200 - The requested Drive Log Category. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log Category. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getDriveLogCategoryWithResponseSpec(String id) throws RestClientResponseException { + return getDriveLogCategoryRequestCreation(id); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/HolidayCalendarApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/HolidayCalendarApi.java new file mode 100644 index 0000000..f5a37a0 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/HolidayCalendarApi.java @@ -0,0 +1,335 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Error; +import com.timr.api.models.HolidayCalendarPartial; +import com.timr.api.models.HolidayCalendarsPage; +import com.timr.api.models.HolidayCalendarsSortColumn; +import com.timr.api.models.HolidaysPage; +import com.timr.api.models.HolidaysSortColumn; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HolidayCalendarApi { + private ApiClient apiClient; + + public HolidayCalendarApi() { + this(new ApiClient()); + } + + public HolidayCalendarApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * List Holiday Calendars + * Lists the Holiday Calendars the authenticated user or API token can access. + *

200 - Page of Holiday Calendars. + *

403 - Forbidden + *

404 - Not Found + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return HolidayCalendarsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchHolidayCalendarsRequestCreation(@Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable HolidayCalendarsSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/holiday-calendars", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Holiday Calendars + * Lists the Holiday Calendars the authenticated user or API token can access. + *

200 - Page of Holiday Calendars. + *

403 - Forbidden + *

404 - Not Found + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return HolidayCalendarsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public HolidayCalendarsPage fetchHolidayCalendars( String pageToken, Integer limit, SortDirection sortDirection, HolidayCalendarsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchHolidayCalendarsRequestCreation(pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Holiday Calendars + * Lists the Holiday Calendars the authenticated user or API token can access. + *

200 - Page of Holiday Calendars. + *

403 - Forbidden + *

404 - Not Found + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<HolidayCalendarsPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchHolidayCalendarsWithHttpInfo( String pageToken, Integer limit, SortDirection sortDirection, HolidayCalendarsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchHolidayCalendarsRequestCreation(pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Holiday Calendars + * Lists the Holiday Calendars the authenticated user or API token can access. + *

200 - Page of Holiday Calendars. + *

403 - Forbidden + *

404 - Not Found + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchHolidayCalendarsWithResponseSpec(@Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable HolidayCalendarsSortColumn sortBy) throws RestClientResponseException { + return fetchHolidayCalendarsRequestCreation(pageToken, limit, sortDirection, sortBy); + } + + /** + * List Holidays + * Lists the Holidays in the Holiday Calendar. + *

200 - Page of Holidays in the Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return HolidaysPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchHolidaysRequestCreation(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable HolidaysSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling fetchHolidays", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/holiday-calendars/{id}/holidays", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Holidays + * Lists the Holidays in the Holiday Calendar. + *

200 - Page of Holidays in the Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return HolidaysPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public HolidaysPage fetchHolidays( String id, String pageToken, Integer limit, SortDirection sortDirection, HolidaysSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchHolidaysRequestCreation(id, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Holidays + * Lists the Holidays in the Holiday Calendar. + *

200 - Page of Holidays in the Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<HolidaysPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchHolidaysWithHttpInfo( String id, String pageToken, Integer limit, SortDirection sortDirection, HolidaysSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchHolidaysRequestCreation(id, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Holidays + * Lists the Holidays in the Holiday Calendar. + *

200 - Page of Holidays in the Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchHolidaysWithResponseSpec(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable HolidaysSortColumn sortBy) throws RestClientResponseException { + return fetchHolidaysRequestCreation(id, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Holiday Calendar + * Returns a single Holiday Calendar by its ID. + *

200 - The requested Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. + * @return HolidayCalendarPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getHolidayCalendarRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getHolidayCalendar", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/holiday-calendars/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Holiday Calendar + * Returns a single Holiday Calendar by its ID. + *

200 - The requested Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. + * @return HolidayCalendarPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public HolidayCalendarPartial getHolidayCalendar( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getHolidayCalendarRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Holiday Calendar + * Returns a single Holiday Calendar by its ID. + *

200 - The requested Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. + * @return ResponseEntity<HolidayCalendarPartial> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getHolidayCalendarWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getHolidayCalendarRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Holiday Calendar + * Returns a single Holiday Calendar by its ID. + *

200 - The requested Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getHolidayCalendarWithResponseSpec(String id) throws RestClientResponseException { + return getHolidayCalendarRequestCreation(id); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/ProjectTimeApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/ProjectTimeApi.java new file mode 100644 index 0000000..9a0a883 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/ProjectTimeApi.java @@ -0,0 +1,653 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.DeletedEntrySortColumn; +import com.timr.api.models.DeletedEntryWithMetadataPage; +import com.timr.api.models.Error; +import java.time.LocalDate; +import org.jspecify.annotations.Nullable; +import java.time.OffsetDateTime; +import com.timr.api.models.ProjectTime; +import com.timr.api.models.ProjectTimeCreate; +import com.timr.api.models.ProjectTimeStatus; +import com.timr.api.models.ProjectTimeUpdate; +import com.timr.api.models.ProjectTimesPage; +import com.timr.api.models.ProjectTimesSortColumn; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTimeApi { + private ApiClient apiClient; + + public ProjectTimeApi() { + this(new ApiClient()); + } + + public ProjectTimeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a Project Time + * Creates a Project Time from the data in the request body. + *

201 - The created Project Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param projectTimeCreate Project Time entity + * @return ProjectTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createProjectTimeRequestCreation(ProjectTimeCreate projectTimeCreate) throws RestClientResponseException { + Object postBody = projectTimeCreate; + // verify the required parameter 'projectTimeCreate' is set + if (projectTimeCreate == null) { + throw new RestClientResponseException("Missing the required parameter 'projectTimeCreate' when calling createProjectTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/project-times", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Project Time + * Creates a Project Time from the data in the request body. + *

201 - The created Project Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param projectTimeCreate Project Time entity + * @return ProjectTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ProjectTime createProjectTime( ProjectTimeCreate projectTimeCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createProjectTimeRequestCreation(projectTimeCreate).body(localVarReturnType); + } + + /** + * Create a Project Time + * Creates a Project Time from the data in the request body. + *

201 - The created Project Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param projectTimeCreate Project Time entity + * @return ResponseEntity<ProjectTime> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createProjectTimeWithHttpInfo( ProjectTimeCreate projectTimeCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createProjectTimeRequestCreation(projectTimeCreate).toEntity(localVarReturnType); + } + + /** + * Create a Project Time + * Creates a Project Time from the data in the request body. + *

201 - The created Project Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param projectTimeCreate Project Time entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createProjectTimeWithResponseSpec(ProjectTimeCreate projectTimeCreate) throws RestClientResponseException { + return createProjectTimeRequestCreation(projectTimeCreate); + } + + /** + * Delete a Project Time + * Deletes the Project Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Project Time. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteProjectTimeRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling deleteProjectTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/project-times/{id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Project Time + * Deletes the Project Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Project Time. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteProjectTime( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteProjectTimeRequestCreation(id).body(localVarReturnType); + } + + /** + * Delete a Project Time + * Deletes the Project Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Project Time. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteProjectTimeWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteProjectTimeRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Delete a Project Time + * Deletes the Project Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Project Time. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteProjectTimeWithResponseSpec(String id) throws RestClientResponseException { + return deleteProjectTimeRequestCreation(id); + } + + /** + * List deleted Project Times + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Project Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DeletedEntryWithMetadataPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchDeletedProjectTimesRequestCreation(@Nullable OffsetDateTime lastModifiedAfter, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DeletedEntrySortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/project-times:deleted", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List deleted Project Times + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Project Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DeletedEntryWithMetadataPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DeletedEntryWithMetadataPage fetchDeletedProjectTimes( OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDeletedProjectTimesRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List deleted Project Times + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Project Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<DeletedEntryWithMetadataPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDeletedProjectTimesWithHttpInfo( OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDeletedProjectTimesRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List deleted Project Times + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Project Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchDeletedProjectTimesWithResponseSpec(@Nullable OffsetDateTime lastModifiedAfter, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DeletedEntrySortColumn sortBy) throws RestClientResponseException { + return fetchDeletedProjectTimesRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + } + + /** + * List Project Times + * Lists the Project Times the authenticated user or API token can access. + *

200 - Page of Project Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param task Only return entries recorded on the Task with this ID. + * @param traverseTaskTree Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ProjectTimesPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchProjectTimesRequestCreation(@Nullable String notes, @Nullable LocalDate startFrom, @Nullable LocalDate startTo, @Nullable OffsetDateTime lastModifiedAfter, @Nullable String task, @Nullable Boolean traverseTaskTree, @Nullable Boolean billable, @Nullable List statuses, @Nullable List users, @Nullable Boolean changed, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable ProjectTimesSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "notes", notes)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_from", startFrom)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_to", startTo)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "task", task)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "traverse_task_tree", traverseTaskTree)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "billable", billable)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "statuses", statuses)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "users", users)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "changed", changed)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/project-times", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Project Times + * Lists the Project Times the authenticated user or API token can access. + *

200 - Page of Project Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param task Only return entries recorded on the Task with this ID. + * @param traverseTaskTree Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ProjectTimesPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ProjectTimesPage fetchProjectTimes( String notes, LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, String task, Boolean traverseTaskTree, Boolean billable, List statuses, List users, Boolean changed, String pageToken, Integer limit, SortDirection sortDirection, ProjectTimesSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchProjectTimesRequestCreation(notes, startFrom, startTo, lastModifiedAfter, task, traverseTaskTree, billable, statuses, users, changed, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Project Times + * Lists the Project Times the authenticated user or API token can access. + *

200 - Page of Project Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param task Only return entries recorded on the Task with this ID. + * @param traverseTaskTree Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<ProjectTimesPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchProjectTimesWithHttpInfo( String notes, LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, String task, Boolean traverseTaskTree, Boolean billable, List statuses, List users, Boolean changed, String pageToken, Integer limit, SortDirection sortDirection, ProjectTimesSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchProjectTimesRequestCreation(notes, startFrom, startTo, lastModifiedAfter, task, traverseTaskTree, billable, statuses, users, changed, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Project Times + * Lists the Project Times the authenticated user or API token can access. + *

200 - Page of Project Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param task Only return entries recorded on the Task with this ID. + * @param traverseTaskTree Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchProjectTimesWithResponseSpec(@Nullable String notes, @Nullable LocalDate startFrom, @Nullable LocalDate startTo, @Nullable OffsetDateTime lastModifiedAfter, @Nullable String task, @Nullable Boolean traverseTaskTree, @Nullable Boolean billable, @Nullable List statuses, @Nullable List users, @Nullable Boolean changed, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable ProjectTimesSortColumn sortBy) throws RestClientResponseException { + return fetchProjectTimesRequestCreation(notes, startFrom, startTo, lastModifiedAfter, task, traverseTaskTree, billable, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Project Time + * Returns a single Project Time by its ID. + *

200 - The requested Project Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Project Time. + * @return ProjectTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getProjectTimeRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getProjectTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/project-times/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Project Time + * Returns a single Project Time by its ID. + *

200 - The requested Project Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Project Time. + * @return ProjectTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ProjectTime getProjectTime( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getProjectTimeRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Project Time + * Returns a single Project Time by its ID. + *

200 - The requested Project Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Project Time. + * @return ResponseEntity<ProjectTime> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getProjectTimeWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getProjectTimeRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Project Time + * Returns a single Project Time by its ID. + *

200 - The requested Project Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Project Time. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getProjectTimeWithResponseSpec(String id) throws RestClientResponseException { + return getProjectTimeRequestCreation(id); + } + + /** + * Update a Project Time + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Project Time. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Project Time. + * @param projectTimeUpdate Project Time entity + * @return ProjectTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec updateProjectTimeRequestCreation(String id, ProjectTimeUpdate projectTimeUpdate) throws RestClientResponseException { + Object postBody = projectTimeUpdate; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling updateProjectTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'projectTimeUpdate' is set + if (projectTimeUpdate == null) { + throw new RestClientResponseException("Missing the required parameter 'projectTimeUpdate' when calling updateProjectTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/project-times/{id}", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Update a Project Time + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Project Time. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Project Time. + * @param projectTimeUpdate Project Time entity + * @return ProjectTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ProjectTime updateProjectTime( String id, ProjectTimeUpdate projectTimeUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateProjectTimeRequestCreation(id, projectTimeUpdate).body(localVarReturnType); + } + + /** + * Update a Project Time + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Project Time. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Project Time. + * @param projectTimeUpdate Project Time entity + * @return ResponseEntity<ProjectTime> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateProjectTimeWithHttpInfo( String id, ProjectTimeUpdate projectTimeUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateProjectTimeRequestCreation(id, projectTimeUpdate).toEntity(localVarReturnType); + } + + /** + * Update a Project Time + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Project Time. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Project Time. + * @param projectTimeUpdate Project Time entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateProjectTimeWithResponseSpec(String id, ProjectTimeUpdate projectTimeUpdate) throws RestClientResponseException { + return updateProjectTimeRequestCreation(id, projectTimeUpdate); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskApi.java new file mode 100644 index 0000000..33b858c --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskApi.java @@ -0,0 +1,581 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Error; +import java.time.LocalDate; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import com.timr.api.models.Task; +import com.timr.api.models.TaskCreate; +import com.timr.api.models.TaskUpdate; +import com.timr.api.models.TasksPage; +import com.timr.api.models.TasksReducedPage; +import com.timr.api.models.TasksSortColumn; +import java.net.URI; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskApi { + private ApiClient apiClient; + + public TaskApi() { + this(new ApiClient()); + } + + public TaskApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a Task + * Creates a Task from the data in the request body. + *

201 - The created Task. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskCreate Project Time entity + * @return Task + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createTaskRequestCreation(TaskCreate taskCreate) throws RestClientResponseException { + Object postBody = taskCreate; + // verify the required parameter 'taskCreate' is set + if (taskCreate == null) { + throw new RestClientResponseException("Missing the required parameter 'taskCreate' when calling createTask", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Task + * Creates a Task from the data in the request body. + *

201 - The created Task. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskCreate Project Time entity + * @return Task + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Task createTask( TaskCreate taskCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTaskRequestCreation(taskCreate).body(localVarReturnType); + } + + /** + * Create a Task + * Creates a Task from the data in the request body. + *

201 - The created Task. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskCreate Project Time entity + * @return ResponseEntity<Task> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createTaskWithHttpInfo( TaskCreate taskCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTaskRequestCreation(taskCreate).toEntity(localVarReturnType); + } + + /** + * Create a Task + * Creates a Task from the data in the request body. + *

201 - The created Task. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskCreate Project Time entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createTaskWithResponseSpec(TaskCreate taskCreate) throws RestClientResponseException { + return createTaskRequestCreation(taskCreate); + } + + /** + * List Tasks + * Lists the Tasks the authenticated user or API token can access. + *

200 - Page of Tasks. + *

400 - Bad Request + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). + * @param name Only return Users whose name contains this text. + * @param bookable Only return entries that are billable (true) or not billable (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param activeAt Only return Tasks that are active on this day. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TasksPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchTasksRequestCreation(@Nullable String parentTaskId, @Nullable Boolean traverseTaskTree, @Nullable String name, @Nullable Boolean bookable, @Nullable Boolean billable, @Nullable LocalDate activeAt, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TasksSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "parent_task_id", parentTaskId)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "traverse_task_tree", traverseTaskTree)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "bookable", bookable)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "billable", billable)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "active_at", activeAt)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Tasks + * Lists the Tasks the authenticated user or API token can access. + *

200 - Page of Tasks. + *

400 - Bad Request + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). + * @param name Only return Users whose name contains this text. + * @param bookable Only return entries that are billable (true) or not billable (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param activeAt Only return Tasks that are active on this day. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TasksPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TasksPage fetchTasks( String parentTaskId, Boolean traverseTaskTree, String name, Boolean bookable, Boolean billable, LocalDate activeAt, String pageToken, Integer limit, SortDirection sortDirection, TasksSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTasksRequestCreation(parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Tasks + * Lists the Tasks the authenticated user or API token can access. + *

200 - Page of Tasks. + *

400 - Bad Request + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). + * @param name Only return Users whose name contains this text. + * @param bookable Only return entries that are billable (true) or not billable (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param activeAt Only return Tasks that are active on this day. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<TasksPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTasksWithHttpInfo( String parentTaskId, Boolean traverseTaskTree, String name, Boolean bookable, Boolean billable, LocalDate activeAt, String pageToken, Integer limit, SortDirection sortDirection, TasksSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTasksRequestCreation(parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Tasks + * Lists the Tasks the authenticated user or API token can access. + *

200 - Page of Tasks. + *

400 - Bad Request + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). + * @param name Only return Users whose name contains this text. + * @param bookable Only return entries that are billable (true) or not billable (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param activeAt Only return Tasks that are active on this day. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchTasksWithResponseSpec(@Nullable String parentTaskId, @Nullable Boolean traverseTaskTree, @Nullable String name, @Nullable Boolean bookable, @Nullable Boolean billable, @Nullable LocalDate activeAt, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TasksSortColumn sortBy) throws RestClientResponseException { + return fetchTasksRequestCreation(parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + } + + /** + * List a User's Tasks + * Lists the Tasks the User is assigned to and may record on. + *

200 - Page of Tasks the User is assigned to. + *

400 - Bad Request + * @param id ID of the User. + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). + * @param name Only return Users whose name contains this text. + * @param bookable Only return entries that are billable (true) or not billable (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param activeAt Only return Tasks that are active on this day. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TasksReducedPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchUserTasksRequestCreation(String id, @Nullable String parentTaskId, @Nullable Boolean traverseTaskTree, @Nullable String name, @Nullable Boolean bookable, @Nullable Boolean billable, @Nullable LocalDate activeAt, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TasksSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling fetchUserTasks", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "parent_task_id", parentTaskId)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "traverse_task_tree", traverseTaskTree)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "bookable", bookable)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "billable", billable)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "active_at", activeAt)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users/{id}/tasks", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List a User's Tasks + * Lists the Tasks the User is assigned to and may record on. + *

200 - Page of Tasks the User is assigned to. + *

400 - Bad Request + * @param id ID of the User. + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). + * @param name Only return Users whose name contains this text. + * @param bookable Only return entries that are billable (true) or not billable (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param activeAt Only return Tasks that are active on this day. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TasksReducedPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TasksReducedPage fetchUserTasks( String id, String parentTaskId, Boolean traverseTaskTree, String name, Boolean bookable, Boolean billable, LocalDate activeAt, String pageToken, Integer limit, SortDirection sortDirection, TasksSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchUserTasksRequestCreation(id, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List a User's Tasks + * Lists the Tasks the User is assigned to and may record on. + *

200 - Page of Tasks the User is assigned to. + *

400 - Bad Request + * @param id ID of the User. + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). + * @param name Only return Users whose name contains this text. + * @param bookable Only return entries that are billable (true) or not billable (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param activeAt Only return Tasks that are active on this day. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<TasksReducedPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchUserTasksWithHttpInfo( String id, String parentTaskId, Boolean traverseTaskTree, String name, Boolean bookable, Boolean billable, LocalDate activeAt, String pageToken, Integer limit, SortDirection sortDirection, TasksSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchUserTasksRequestCreation(id, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List a User's Tasks + * Lists the Tasks the User is assigned to and may record on. + *

200 - Page of Tasks the User is assigned to. + *

400 - Bad Request + * @param id ID of the User. + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). + * @param name Only return Users whose name contains this text. + * @param bookable Only return entries that are billable (true) or not billable (false). + * @param billable Only return entries that are billable (true) or not billable (false). + * @param activeAt Only return Tasks that are active on this day. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchUserTasksWithResponseSpec(String id, @Nullable String parentTaskId, @Nullable Boolean traverseTaskTree, @Nullable String name, @Nullable Boolean bookable, @Nullable Boolean billable, @Nullable LocalDate activeAt, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TasksSortColumn sortBy) throws RestClientResponseException { + return fetchUserTasksRequestCreation(id, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Task + * Returns a single Task by its ID. + *

200 - The requested Task. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Task. + * @return Task + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getTaskRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getTask", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Task + * Returns a single Task by its ID. + *

200 - The requested Task. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Task. + * @return Task + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Task getTask( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTaskRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Task + * Returns a single Task by its ID. + *

200 - The requested Task. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Task. + * @return ResponseEntity<Task> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTaskWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTaskRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Task + * Returns a single Task by its ID. + *

200 - The requested Task. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Task. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getTaskWithResponseSpec(String id) throws RestClientResponseException { + return getTaskRequestCreation(id); + } + + /** + * Update a Task + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Task. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Task. + * @param taskUpdate Task entity + * @return Task + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec updateTaskRequestCreation(String id, TaskUpdate taskUpdate) throws RestClientResponseException { + Object postBody = taskUpdate; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling updateTask", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'taskUpdate' is set + if (taskUpdate == null) { + throw new RestClientResponseException("Missing the required parameter 'taskUpdate' when calling updateTask", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{id}", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Update a Task + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Task. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Task. + * @param taskUpdate Task entity + * @return Task + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Task updateTask( String id, TaskUpdate taskUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateTaskRequestCreation(id, taskUpdate).body(localVarReturnType); + } + + /** + * Update a Task + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Task. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Task. + * @param taskUpdate Task entity + * @return ResponseEntity<Task> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateTaskWithHttpInfo( String id, TaskUpdate taskUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateTaskRequestCreation(id, taskUpdate).toEntity(localVarReturnType); + } + + /** + * Update a Task + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Task. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Task. + * @param taskUpdate Task entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateTaskWithResponseSpec(String id, TaskUpdate taskUpdate) throws RestClientResponseException { + return updateTaskRequestCreation(id, taskUpdate); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskToLeaderAssignmentApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskToLeaderAssignmentApi.java new file mode 100644 index 0000000..a5ecaa5 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskToLeaderAssignmentApi.java @@ -0,0 +1,441 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Error; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import com.timr.api.models.TaskToLeaderAssignment; +import com.timr.api.models.TaskToLeaderAssignmentsPage; +import com.timr.api.models.TaskToLeaderAssignmentsSortColumn; +import java.net.URI; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToLeaderAssignmentApi { + private ApiClient apiClient; + + public TaskToLeaderAssignmentApi() { + this(new ApiClient()); + } + + public TaskToLeaderAssignmentApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a Task to Leader Assignment + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The Task to Leader Assignment, which already existed. + *

201 - The created Task to Leader Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return TaskToLeaderAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createTaskToLeaderAssignmentRequestCreation(String taskId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling createTaskToLeaderAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling createTaskToLeaderAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/leaders/{user_id}", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Task to Leader Assignment + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The Task to Leader Assignment, which already existed. + *

201 - The created Task to Leader Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return TaskToLeaderAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TaskToLeaderAssignment createTaskToLeaderAssignment( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTaskToLeaderAssignmentRequestCreation(taskId, userId).body(localVarReturnType); + } + + /** + * Create a Task to Leader Assignment + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The Task to Leader Assignment, which already existed. + *

201 - The created Task to Leader Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ResponseEntity<TaskToLeaderAssignment> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createTaskToLeaderAssignmentWithHttpInfo( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTaskToLeaderAssignmentRequestCreation(taskId, userId).toEntity(localVarReturnType); + } + + /** + * Create a Task to Leader Assignment + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The Task to Leader Assignment, which already existed. + *

201 - The created Task to Leader Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createTaskToLeaderAssignmentWithResponseSpec(String taskId, String userId) throws RestClientResponseException { + return createTaskToLeaderAssignmentRequestCreation(taskId, userId); + } + + /** + * Delete a Task to Leader Assignment + * Removes the User's leader assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteTaskToLeaderAssignmentRequestCreation(String taskId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling deleteTaskToLeaderAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling deleteTaskToLeaderAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/leaders/{user_id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Task to Leader Assignment + * Removes the User's leader assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteTaskToLeaderAssignment( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteTaskToLeaderAssignmentRequestCreation(taskId, userId).body(localVarReturnType); + } + + /** + * Delete a Task to Leader Assignment + * Removes the User's leader assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTaskToLeaderAssignmentWithHttpInfo( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteTaskToLeaderAssignmentRequestCreation(taskId, userId).toEntity(localVarReturnType); + } + + /** + * Delete a Task to Leader Assignment + * Removes the User's leader assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteTaskToLeaderAssignmentWithResponseSpec(String taskId, String userId) throws RestClientResponseException { + return deleteTaskToLeaderAssignmentRequestCreation(taskId, userId); + } + + /** + * List Task to Leader Assignments + * Lists the Users assigned to the Task as leaders. + *

200 - Page of Task to Leader Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TaskToLeaderAssignmentsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchTaskToLeaderAssignmentsRequestCreation(String taskId, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TaskToLeaderAssignmentsSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling fetchTaskToLeaderAssignments", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/leaders", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Task to Leader Assignments + * Lists the Users assigned to the Task as leaders. + *

200 - Page of Task to Leader Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TaskToLeaderAssignmentsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TaskToLeaderAssignmentsPage fetchTaskToLeaderAssignments( String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToLeaderAssignmentsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTaskToLeaderAssignmentsRequestCreation(taskId, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Task to Leader Assignments + * Lists the Users assigned to the Task as leaders. + *

200 - Page of Task to Leader Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<TaskToLeaderAssignmentsPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTaskToLeaderAssignmentsWithHttpInfo( String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToLeaderAssignmentsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTaskToLeaderAssignmentsRequestCreation(taskId, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Task to Leader Assignments + * Lists the Users assigned to the Task as leaders. + *

200 - Page of Task to Leader Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchTaskToLeaderAssignmentsWithResponseSpec(String taskId, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TaskToLeaderAssignmentsSortColumn sortBy) throws RestClientResponseException { + return fetchTaskToLeaderAssignmentsRequestCreation(taskId, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Task to Leader Assignment + * Returns the leader assignment of a single User to the Task. + *

200 - The requested Task to Leader Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return TaskToLeaderAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getTaskToLeaderAssignmentRequestCreation(String taskId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling getTaskToLeaderAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling getTaskToLeaderAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/leaders/{user_id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Task to Leader Assignment + * Returns the leader assignment of a single User to the Task. + *

200 - The requested Task to Leader Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return TaskToLeaderAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TaskToLeaderAssignment getTaskToLeaderAssignment( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTaskToLeaderAssignmentRequestCreation(taskId, userId).body(localVarReturnType); + } + + /** + * Get a Task to Leader Assignment + * Returns the leader assignment of a single User to the Task. + *

200 - The requested Task to Leader Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ResponseEntity<TaskToLeaderAssignment> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTaskToLeaderAssignmentWithHttpInfo( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTaskToLeaderAssignmentRequestCreation(taskId, userId).toEntity(localVarReturnType); + } + + /** + * Get a Task to Leader Assignment + * Returns the leader assignment of a single User to the Task. + *

200 - The requested Task to Leader Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getTaskToLeaderAssignmentWithResponseSpec(String taskId, String userId) throws RestClientResponseException { + return getTaskToLeaderAssignmentRequestCreation(taskId, userId); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskToTeamAssignmentApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskToTeamAssignmentApi.java new file mode 100644 index 0000000..a208e68 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskToTeamAssignmentApi.java @@ -0,0 +1,441 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Error; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import com.timr.api.models.TaskToTeamAssignment; +import com.timr.api.models.TaskToTeamAssignmentsPage; +import com.timr.api.models.TaskToTeamAssignmentsSortColumn; +import java.net.URI; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToTeamAssignmentApi { + private ApiClient apiClient; + + public TaskToTeamAssignmentApi() { + this(new ApiClient()); + } + + public TaskToTeamAssignmentApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a Task to Team Assignment + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The updated Task to Team Assignment. + *

201 - The created Task to Team Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return TaskToTeamAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createTaskToTeamAssignmentRequestCreation(String taskId, String teamId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling createTaskToTeamAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new RestClientResponseException("Missing the required parameter 'teamId' when calling createTaskToTeamAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + pathParams.put("team_id", teamId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/teams/{team_id}", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Task to Team Assignment + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The updated Task to Team Assignment. + *

201 - The created Task to Team Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return TaskToTeamAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TaskToTeamAssignment createTaskToTeamAssignment( String taskId, String teamId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTaskToTeamAssignmentRequestCreation(taskId, teamId).body(localVarReturnType); + } + + /** + * Create a Task to Team Assignment + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The updated Task to Team Assignment. + *

201 - The created Task to Team Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return ResponseEntity<TaskToTeamAssignment> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createTaskToTeamAssignmentWithHttpInfo( String taskId, String teamId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTaskToTeamAssignmentRequestCreation(taskId, teamId).toEntity(localVarReturnType); + } + + /** + * Create a Task to Team Assignment + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The updated Task to Team Assignment. + *

201 - The created Task to Team Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createTaskToTeamAssignmentWithResponseSpec(String taskId, String teamId) throws RestClientResponseException { + return createTaskToTeamAssignmentRequestCreation(taskId, teamId); + } + + /** + * Delete a Task to Team Assignment + * Removes the Team's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteTaskToTeamAssignmentRequestCreation(String taskId, String teamId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling deleteTaskToTeamAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new RestClientResponseException("Missing the required parameter 'teamId' when calling deleteTaskToTeamAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + pathParams.put("team_id", teamId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/teams/{team_id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Task to Team Assignment + * Removes the Team's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteTaskToTeamAssignment( String taskId, String teamId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteTaskToTeamAssignmentRequestCreation(taskId, teamId).body(localVarReturnType); + } + + /** + * Delete a Task to Team Assignment + * Removes the Team's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTaskToTeamAssignmentWithHttpInfo( String taskId, String teamId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteTaskToTeamAssignmentRequestCreation(taskId, teamId).toEntity(localVarReturnType); + } + + /** + * Delete a Task to Team Assignment + * Removes the Team's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteTaskToTeamAssignmentWithResponseSpec(String taskId, String teamId) throws RestClientResponseException { + return deleteTaskToTeamAssignmentRequestCreation(taskId, teamId); + } + + /** + * List Task to Team Assignments + * Lists the Teams assigned to the Task. + *

200 - Page of Task to Team Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TaskToTeamAssignmentsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchTaskToTeamAssignmentsRequestCreation(String taskId, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TaskToTeamAssignmentsSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling fetchTaskToTeamAssignments", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/teams", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Task to Team Assignments + * Lists the Teams assigned to the Task. + *

200 - Page of Task to Team Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TaskToTeamAssignmentsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TaskToTeamAssignmentsPage fetchTaskToTeamAssignments( String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToTeamAssignmentsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTaskToTeamAssignmentsRequestCreation(taskId, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Task to Team Assignments + * Lists the Teams assigned to the Task. + *

200 - Page of Task to Team Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<TaskToTeamAssignmentsPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTaskToTeamAssignmentsWithHttpInfo( String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToTeamAssignmentsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTaskToTeamAssignmentsRequestCreation(taskId, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Task to Team Assignments + * Lists the Teams assigned to the Task. + *

200 - Page of Task to Team Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchTaskToTeamAssignmentsWithResponseSpec(String taskId, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TaskToTeamAssignmentsSortColumn sortBy) throws RestClientResponseException { + return fetchTaskToTeamAssignmentsRequestCreation(taskId, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Task to Team Assignment + * Returns the assignment of a single Team to the Task. + *

200 - The requested Task to Team Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return TaskToTeamAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getTaskToTeamAssignmentRequestCreation(String taskId, String teamId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling getTaskToTeamAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new RestClientResponseException("Missing the required parameter 'teamId' when calling getTaskToTeamAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + pathParams.put("team_id", teamId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/teams/{team_id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Task to Team Assignment + * Returns the assignment of a single Team to the Task. + *

200 - The requested Task to Team Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return TaskToTeamAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TaskToTeamAssignment getTaskToTeamAssignment( String taskId, String teamId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTaskToTeamAssignmentRequestCreation(taskId, teamId).body(localVarReturnType); + } + + /** + * Get a Task to Team Assignment + * Returns the assignment of a single Team to the Task. + *

200 - The requested Task to Team Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return ResponseEntity<TaskToTeamAssignment> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTaskToTeamAssignmentWithHttpInfo( String taskId, String teamId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTaskToTeamAssignmentRequestCreation(taskId, teamId).toEntity(localVarReturnType); + } + + /** + * Get a Task to Team Assignment + * Returns the assignment of a single Team to the Task. + *

200 - The requested Task to Team Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getTaskToTeamAssignmentWithResponseSpec(String taskId, String teamId) throws RestClientResponseException { + return getTaskToTeamAssignmentRequestCreation(taskId, teamId); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskToUserAssignmentApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskToUserAssignmentApi.java new file mode 100644 index 0000000..e671175 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskToUserAssignmentApi.java @@ -0,0 +1,452 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Error; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import com.timr.api.models.TaskToUserAssignment; +import com.timr.api.models.TaskToUserAssignmentUpsert; +import com.timr.api.models.TaskToUserAssignmentsPage; +import com.timr.api.models.TaskToUserAssignmentsSortColumn; +import java.net.URI; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToUserAssignmentApi { + private ApiClient apiClient; + + public TaskToUserAssignmentApi() { + this(new ApiClient()); + } + + public TaskToUserAssignmentApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete a Task to User Assignment + * Removes the User's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteTaskToUserAssignmentRequestCreation(String taskId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling deleteTaskToUserAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling deleteTaskToUserAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/users/{user_id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Task to User Assignment + * Removes the User's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteTaskToUserAssignment( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteTaskToUserAssignmentRequestCreation(taskId, userId).body(localVarReturnType); + } + + /** + * Delete a Task to User Assignment + * Removes the User's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTaskToUserAssignmentWithHttpInfo( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteTaskToUserAssignmentRequestCreation(taskId, userId).toEntity(localVarReturnType); + } + + /** + * Delete a Task to User Assignment + * Removes the User's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteTaskToUserAssignmentWithResponseSpec(String taskId, String userId) throws RestClientResponseException { + return deleteTaskToUserAssignmentRequestCreation(taskId, userId); + } + + /** + * List Task to User Assignments + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + *

200 - Page of Task to User Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TaskToUserAssignmentsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchTaskToUserAssignmentsRequestCreation(String taskId, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TaskToUserAssignmentsSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling fetchTaskToUserAssignments", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/users", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Task to User Assignments + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + *

200 - Page of Task to User Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TaskToUserAssignmentsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TaskToUserAssignmentsPage fetchTaskToUserAssignments( String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToUserAssignmentsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTaskToUserAssignmentsRequestCreation(taskId, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Task to User Assignments + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + *

200 - Page of Task to User Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<TaskToUserAssignmentsPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTaskToUserAssignmentsWithHttpInfo( String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToUserAssignmentsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTaskToUserAssignmentsRequestCreation(taskId, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Task to User Assignments + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + *

200 - Page of Task to User Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchTaskToUserAssignmentsWithResponseSpec(String taskId, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TaskToUserAssignmentsSortColumn sortBy) throws RestClientResponseException { + return fetchTaskToUserAssignmentsRequestCreation(taskId, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Task to User Assignment + * Returns the assignment of a single User to the Task. + *

200 - The requested Task to User Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return TaskToUserAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getTaskToUserAssignmentRequestCreation(String taskId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling getTaskToUserAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling getTaskToUserAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/users/{user_id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Task to User Assignment + * Returns the assignment of a single User to the Task. + *

200 - The requested Task to User Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return TaskToUserAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TaskToUserAssignment getTaskToUserAssignment( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTaskToUserAssignmentRequestCreation(taskId, userId).body(localVarReturnType); + } + + /** + * Get a Task to User Assignment + * Returns the assignment of a single User to the Task. + *

200 - The requested Task to User Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ResponseEntity<TaskToUserAssignment> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTaskToUserAssignmentWithHttpInfo( String taskId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTaskToUserAssignmentRequestCreation(taskId, userId).toEntity(localVarReturnType); + } + + /** + * Get a Task to User Assignment + * Returns the assignment of a single User to the Task. + *

200 - The requested Task to User Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getTaskToUserAssignmentWithResponseSpec(String taskId, String userId) throws RestClientResponseException { + return getTaskToUserAssignmentRequestCreation(taskId, userId); + } + + /** + * Create or update a Task to User Assignment + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + *

200 - The updated Task to User Assignment. + *

201 - The created Task to User Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param userId ID of the User. + * @param taskToUserAssignmentUpsert Task to User Assignment entity + * @return TaskToUserAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec upsertTaskToUserAssignmentRequestCreation(String taskId, String userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert) throws RestClientResponseException { + Object postBody = taskToUserAssignmentUpsert; + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new RestClientResponseException("Missing the required parameter 'taskId' when calling upsertTaskToUserAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling upsertTaskToUserAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'taskToUserAssignmentUpsert' is set + if (taskToUserAssignmentUpsert == null) { + throw new RestClientResponseException("Missing the required parameter 'taskToUserAssignmentUpsert' when calling upsertTaskToUserAssignment", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("task_id", taskId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{task_id}/users/{user_id}", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create or update a Task to User Assignment + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + *

200 - The updated Task to User Assignment. + *

201 - The created Task to User Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param userId ID of the User. + * @param taskToUserAssignmentUpsert Task to User Assignment entity + * @return TaskToUserAssignment + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TaskToUserAssignment upsertTaskToUserAssignment( String taskId, String userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return upsertTaskToUserAssignmentRequestCreation(taskId, userId, taskToUserAssignmentUpsert).body(localVarReturnType); + } + + /** + * Create or update a Task to User Assignment + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + *

200 - The updated Task to User Assignment. + *

201 - The created Task to User Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param userId ID of the User. + * @param taskToUserAssignmentUpsert Task to User Assignment entity + * @return ResponseEntity<TaskToUserAssignment> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity upsertTaskToUserAssignmentWithHttpInfo( String taskId, String userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return upsertTaskToUserAssignmentRequestCreation(taskId, userId, taskToUserAssignmentUpsert).toEntity(localVarReturnType); + } + + /** + * Create or update a Task to User Assignment + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + *

200 - The updated Task to User Assignment. + *

201 - The created Task to User Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. + * @param userId ID of the User. + * @param taskToUserAssignmentUpsert Task to User Assignment entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec upsertTaskToUserAssignmentWithResponseSpec(String taskId, String userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert) throws RestClientResponseException { + return upsertTaskToUserAssignmentRequestCreation(taskId, userId, taskToUserAssignmentUpsert); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/TeamApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/TeamApi.java new file mode 100644 index 0000000..f630abe --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/TeamApi.java @@ -0,0 +1,1281 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Error; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import com.timr.api.models.Team; +import com.timr.api.models.TeamCreate; +import com.timr.api.models.TeamUpdate; +import com.timr.api.models.TeamsPage; +import com.timr.api.models.TeamsSortColumn; +import java.net.URI; +import com.timr.api.models.UserPartial; +import com.timr.api.models.UsersPartialPage; +import com.timr.api.models.UsersSortColumn; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamApi { + private ApiClient apiClient; + + public TeamApi() { + this(new ApiClient()); + } + + public TeamApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Add a Team Leader + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + *

200 - The Team Leader, which was already assigned. + *

201 - The newly assigned Team Leader. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec addTeamLeaderRequestCreation(String teamId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new RestClientResponseException("Missing the required parameter 'teamId' when calling addTeamLeader", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling addTeamLeader", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("team_id", teamId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{team_id}/leaders/{user_id}", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Add a Team Leader + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + *

200 - The Team Leader, which was already assigned. + *

201 - The newly assigned Team Leader. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public UserPartial addTeamLeader( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return addTeamLeaderRequestCreation(teamId, userId).body(localVarReturnType); + } + + /** + * Add a Team Leader + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + *

200 - The Team Leader, which was already assigned. + *

201 - The newly assigned Team Leader. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseEntity<UserPartial> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity addTeamLeaderWithHttpInfo( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return addTeamLeaderRequestCreation(teamId, userId).toEntity(localVarReturnType); + } + + /** + * Add a Team Leader + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + *

200 - The Team Leader, which was already assigned. + *

201 - The newly assigned Team Leader. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec addTeamLeaderWithResponseSpec(String teamId, String userId) throws RestClientResponseException { + return addTeamLeaderRequestCreation(teamId, userId); + } + + /** + * Add a Team Member + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + *

200 - The Team Member, which was already assigned. + *

201 - The newly assigned Team Member. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec addTeamMemberRequestCreation(String teamId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new RestClientResponseException("Missing the required parameter 'teamId' when calling addTeamMember", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling addTeamMember", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("team_id", teamId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{team_id}/members/{user_id}", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Add a Team Member + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + *

200 - The Team Member, which was already assigned. + *

201 - The newly assigned Team Member. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public UserPartial addTeamMember( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return addTeamMemberRequestCreation(teamId, userId).body(localVarReturnType); + } + + /** + * Add a Team Member + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + *

200 - The Team Member, which was already assigned. + *

201 - The newly assigned Team Member. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseEntity<UserPartial> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity addTeamMemberWithHttpInfo( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return addTeamMemberRequestCreation(teamId, userId).toEntity(localVarReturnType); + } + + /** + * Add a Team Member + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + *

200 - The Team Member, which was already assigned. + *

201 - The newly assigned Team Member. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec addTeamMemberWithResponseSpec(String teamId, String userId) throws RestClientResponseException { + return addTeamMemberRequestCreation(teamId, userId); + } + + /** + * Create a Team + * Creates a Team from the data in the request body. + *

201 - The created Team. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamCreate Team entity + * @return Team + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createTeamRequestCreation(TeamCreate teamCreate) throws RestClientResponseException { + Object postBody = teamCreate; + // verify the required parameter 'teamCreate' is set + if (teamCreate == null) { + throw new RestClientResponseException("Missing the required parameter 'teamCreate' when calling createTeam", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Team + * Creates a Team from the data in the request body. + *

201 - The created Team. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamCreate Team entity + * @return Team + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Team createTeam( TeamCreate teamCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTeamRequestCreation(teamCreate).body(localVarReturnType); + } + + /** + * Create a Team + * Creates a Team from the data in the request body. + *

201 - The created Team. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamCreate Team entity + * @return ResponseEntity<Team> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createTeamWithHttpInfo( TeamCreate teamCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTeamRequestCreation(teamCreate).toEntity(localVarReturnType); + } + + /** + * Create a Team + * Creates a Team from the data in the request body. + *

201 - The created Team. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamCreate Team entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createTeamWithResponseSpec(TeamCreate teamCreate) throws RestClientResponseException { + return createTeamRequestCreation(teamCreate); + } + + /** + * Delete a Team + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Team. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteTeamRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling deleteTeam", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Team + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Team. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteTeam( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteTeamRequestCreation(id).body(localVarReturnType); + } + + /** + * Delete a Team + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Team. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTeamWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteTeamRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Delete a Team + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Team. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteTeamWithResponseSpec(String id) throws RestClientResponseException { + return deleteTeamRequestCreation(id); + } + + /** + * List Team Leaders + * Lists the Users who lead the Team. + *

200 - Page of Team Leaders. + *

400 - Bad Request + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return UsersPartialPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchTeamLeadersRequestCreation(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable UsersSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling fetchTeamLeaders", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{id}/leaders", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Team Leaders + * Lists the Users who lead the Team. + *

200 - Page of Team Leaders. + *

400 - Bad Request + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return UsersPartialPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public UsersPartialPage fetchTeamLeaders( String id, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTeamLeadersRequestCreation(id, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Team Leaders + * Lists the Users who lead the Team. + *

200 - Page of Team Leaders. + *

400 - Bad Request + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<UsersPartialPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTeamLeadersWithHttpInfo( String id, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTeamLeadersRequestCreation(id, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Team Leaders + * Lists the Users who lead the Team. + *

200 - Page of Team Leaders. + *

400 - Bad Request + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchTeamLeadersWithResponseSpec(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable UsersSortColumn sortBy) throws RestClientResponseException { + return fetchTeamLeadersRequestCreation(id, pageToken, limit, sortDirection, sortBy); + } + + /** + * List Team Members + * Lists the Users who are members of the Team. + *

200 - Page of Team Members. + *

400 - Bad Request + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return UsersPartialPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchTeamMembersRequestCreation(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable UsersSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling fetchTeamMembers", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{id}/members", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Team Members + * Lists the Users who are members of the Team. + *

200 - Page of Team Members. + *

400 - Bad Request + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return UsersPartialPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public UsersPartialPage fetchTeamMembers( String id, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTeamMembersRequestCreation(id, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Team Members + * Lists the Users who are members of the Team. + *

200 - Page of Team Members. + *

400 - Bad Request + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<UsersPartialPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTeamMembersWithHttpInfo( String id, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTeamMembersRequestCreation(id, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Team Members + * Lists the Users who are members of the Team. + *

200 - Page of Team Members. + *

400 - Bad Request + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchTeamMembersWithResponseSpec(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable UsersSortColumn sortBy) throws RestClientResponseException { + return fetchTeamMembersRequestCreation(id, pageToken, limit, sortDirection, sortBy); + } + + /** + * List Teams + * Lists the Teams the authenticated user or API token can access. + *

200 - Page of Teams. + *

400 - Bad Request + * @param name Only return Teams whose name matches this value in any segment of the breadcrumbs path. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TeamsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchTeamsRequestCreation(@Nullable String name, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TeamsSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Teams + * Lists the Teams the authenticated user or API token can access. + *

200 - Page of Teams. + *

400 - Bad Request + * @param name Only return Teams whose name matches this value in any segment of the breadcrumbs path. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TeamsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TeamsPage fetchTeams( String name, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTeamsRequestCreation(name, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Teams + * Lists the Teams the authenticated user or API token can access. + *

200 - Page of Teams. + *

400 - Bad Request + * @param name Only return Teams whose name matches this value in any segment of the breadcrumbs path. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<TeamsPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTeamsWithHttpInfo( String name, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchTeamsRequestCreation(name, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Teams + * Lists the Teams the authenticated user or API token can access. + *

200 - Page of Teams. + *

400 - Bad Request + * @param name Only return Teams whose name matches this value in any segment of the breadcrumbs path. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchTeamsWithResponseSpec(@Nullable String name, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TeamsSortColumn sortBy) throws RestClientResponseException { + return fetchTeamsRequestCreation(name, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Team + * Returns a single Team by its ID. + *

200 - The requested Team. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Team. + * @return Team + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getTeamRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getTeam", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Team + * Returns a single Team by its ID. + *

200 - The requested Team. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Team. + * @return Team + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Team getTeam( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTeamRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Team + * Returns a single Team by its ID. + *

200 - The requested Team. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Team. + * @return ResponseEntity<Team> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTeamWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTeamRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Team + * Returns a single Team by its ID. + *

200 - The requested Team. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Team. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getTeamWithResponseSpec(String id) throws RestClientResponseException { + return getTeamRequestCreation(id); + } + + /** + * Get a Team Leader + * Returns the leadership of a single User in the Team. + *

200 - The requested Team Leader. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getTeamLeaderRequestCreation(String teamId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new RestClientResponseException("Missing the required parameter 'teamId' when calling getTeamLeader", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling getTeamLeader", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("team_id", teamId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{team_id}/leaders/{user_id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Team Leader + * Returns the leadership of a single User in the Team. + *

200 - The requested Team Leader. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public UserPartial getTeamLeader( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTeamLeaderRequestCreation(teamId, userId).body(localVarReturnType); + } + + /** + * Get a Team Leader + * Returns the leadership of a single User in the Team. + *

200 - The requested Team Leader. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseEntity<UserPartial> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTeamLeaderWithHttpInfo( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTeamLeaderRequestCreation(teamId, userId).toEntity(localVarReturnType); + } + + /** + * Get a Team Leader + * Returns the leadership of a single User in the Team. + *

200 - The requested Team Leader. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getTeamLeaderWithResponseSpec(String teamId, String userId) throws RestClientResponseException { + return getTeamLeaderRequestCreation(teamId, userId); + } + + /** + * Get a Team Member + * Returns the membership of a single User in the Team. + *

200 - The requested Team Member. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getTeamMemberRequestCreation(String teamId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new RestClientResponseException("Missing the required parameter 'teamId' when calling getTeamMember", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling getTeamMember", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("team_id", teamId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{team_id}/members/{user_id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Team Member + * Returns the membership of a single User in the Team. + *

200 - The requested Team Member. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public UserPartial getTeamMember( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTeamMemberRequestCreation(teamId, userId).body(localVarReturnType); + } + + /** + * Get a Team Member + * Returns the membership of a single User in the Team. + *

200 - The requested Team Member. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseEntity<UserPartial> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTeamMemberWithHttpInfo( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTeamMemberRequestCreation(teamId, userId).toEntity(localVarReturnType); + } + + /** + * Get a Team Member + * Returns the membership of a single User in the Team. + *

200 - The requested Team Member. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getTeamMemberWithResponseSpec(String teamId, String userId) throws RestClientResponseException { + return getTeamMemberRequestCreation(teamId, userId); + } + + /** + * Remove a Team Leader + * Removes the User's leadership of the Team. The User itself is not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec removeTeamLeaderRequestCreation(String teamId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new RestClientResponseException("Missing the required parameter 'teamId' when calling removeTeamLeader", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling removeTeamLeader", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("team_id", teamId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{team_id}/leaders/{user_id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Remove a Team Leader + * Removes the User's leadership of the Team. The User itself is not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void removeTeamLeader( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + removeTeamLeaderRequestCreation(teamId, userId).body(localVarReturnType); + } + + /** + * Remove a Team Leader + * Removes the User's leadership of the Team. The User itself is not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity removeTeamLeaderWithHttpInfo( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return removeTeamLeaderRequestCreation(teamId, userId).toEntity(localVarReturnType); + } + + /** + * Remove a Team Leader + * Removes the User's leadership of the Team. The User itself is not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec removeTeamLeaderWithResponseSpec(String teamId, String userId) throws RestClientResponseException { + return removeTeamLeaderRequestCreation(teamId, userId); + } + + /** + * Remove a Team Member + * Removes the User's membership in the Team. The User itself is not deleted. + *

204 - Removed. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec removeTeamMemberRequestCreation(String teamId, String userId) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new RestClientResponseException("Missing the required parameter 'teamId' when calling removeTeamMember", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userId' is set + if (userId == null) { + throw new RestClientResponseException("Missing the required parameter 'userId' when calling removeTeamMember", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("team_id", teamId); + pathParams.put("user_id", userId); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{team_id}/members/{user_id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Remove a Team Member + * Removes the User's membership in the Team. The User itself is not deleted. + *

204 - Removed. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void removeTeamMember( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + removeTeamMemberRequestCreation(teamId, userId).body(localVarReturnType); + } + + /** + * Remove a Team Member + * Removes the User's membership in the Team. The User itself is not deleted. + *

204 - Removed. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. + * @param userId ID of the User. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity removeTeamMemberWithHttpInfo( String teamId, String userId) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return removeTeamMemberRequestCreation(teamId, userId).toEntity(localVarReturnType); + } + + /** + * Remove a Team Member + * Removes the User's membership in the Team. The User itself is not deleted. + *

204 - Removed. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec removeTeamMemberWithResponseSpec(String teamId, String userId) throws RestClientResponseException { + return removeTeamMemberRequestCreation(teamId, userId); + } + + /** + * Update a Team + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Team. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Team. + * @param teamUpdate Team entity + * @return Team + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec updateTeamRequestCreation(String id, TeamUpdate teamUpdate) throws RestClientResponseException { + Object postBody = teamUpdate; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling updateTeam", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'teamUpdate' is set + if (teamUpdate == null) { + throw new RestClientResponseException("Missing the required parameter 'teamUpdate' when calling updateTeam", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/teams/{id}", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Update a Team + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Team. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Team. + * @param teamUpdate Team entity + * @return Team + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Team updateTeam( String id, TeamUpdate teamUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateTeamRequestCreation(id, teamUpdate).body(localVarReturnType); + } + + /** + * Update a Team + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Team. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Team. + * @param teamUpdate Team entity + * @return ResponseEntity<Team> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateTeamWithHttpInfo( String id, TeamUpdate teamUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateTeamRequestCreation(id, teamUpdate).toEntity(localVarReturnType); + } + + /** + * Update a Team + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Team. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Team. + * @param teamUpdate Team entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateTeamWithResponseSpec(String id, TeamUpdate teamUpdate) throws RestClientResponseException { + return updateTeamRequestCreation(id, teamUpdate); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/TimeAccountApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/TimeAccountApi.java new file mode 100644 index 0000000..fbf3118 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/TimeAccountApi.java @@ -0,0 +1,232 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Accounts; +import com.timr.api.models.Error; +import java.time.LocalDate; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TimeAccountApi { + private ApiClient apiClient; + + public TimeAccountApi() { + this(new ApiClient()); + } + + public TimeAccountApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Get a User's accounts + * Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + *

200 - The User's account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @param date Day to return the balances for. + * @return Accounts + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getUserAccountsRequestCreation(String id, LocalDate date) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getUserAccounts", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'date' is set + if (date == null) { + throw new RestClientResponseException("Missing the required parameter 'date' when calling getUserAccounts", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + pathParams.put("date", date); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users/{id}/accounts/{date}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a User's accounts + * Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + *

200 - The User's account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @param date Day to return the balances for. + * @return Accounts + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Accounts getUserAccounts( String id, LocalDate date) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getUserAccountsRequestCreation(id, date).body(localVarReturnType); + } + + /** + * Get a User's accounts + * Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + *

200 - The User's account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @param date Day to return the balances for. + * @return ResponseEntity<Accounts> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserAccountsWithHttpInfo( String id, LocalDate date) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getUserAccountsRequestCreation(id, date).toEntity(localVarReturnType); + } + + /** + * Get a User's accounts + * Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + *

200 - The User's account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @param date Day to return the balances for. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getUserAccountsWithResponseSpec(String id, LocalDate date) throws RestClientResponseException { + return getUserAccountsRequestCreation(id, date); + } + + /** + * Get a User's working time accounts + * Returns the User's working time account balances as of the given day. + *

200 - The User's working time account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @param date Day to return the balances for. + * @return Accounts + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getUserWorkingTimeAccountsRequestCreation(String id, LocalDate date) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getUserWorkingTimeAccounts", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'date' is set + if (date == null) { + throw new RestClientResponseException("Missing the required parameter 'date' when calling getUserWorkingTimeAccounts", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + pathParams.put("date", date); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users/{id}/working-time-accounts/{date}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a User's working time accounts + * Returns the User's working time account balances as of the given day. + *

200 - The User's working time account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @param date Day to return the balances for. + * @return Accounts + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public Accounts getUserWorkingTimeAccounts( String id, LocalDate date) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getUserWorkingTimeAccountsRequestCreation(id, date).body(localVarReturnType); + } + + /** + * Get a User's working time accounts + * Returns the User's working time account balances as of the given day. + *

200 - The User's working time account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @param date Day to return the balances for. + * @return ResponseEntity<Accounts> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserWorkingTimeAccountsWithHttpInfo( String id, LocalDate date) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getUserWorkingTimeAccountsRequestCreation(id, date).toEntity(localVarReturnType); + } + + /** + * Get a User's working time accounts + * Returns the User's working time account balances as of the given day. + *

200 - The User's working time account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @param date Day to return the balances for. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getUserWorkingTimeAccountsWithResponseSpec(String id, LocalDate date) throws RestClientResponseException { + return getUserWorkingTimeAccountsRequestCreation(id, date); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/TrackApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/TrackApi.java new file mode 100644 index 0000000..0faf196 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/TrackApi.java @@ -0,0 +1,416 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Error; +import com.timr.api.models.Waypoint; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TrackApi { + private ApiClient apiClient; + + public TrackApi() { + this(new ApiClient()); + } + + public TrackApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a Drive Log's Track + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id + * @param waypoint Working Time Date Span entity + * @return List<Waypoint> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createTrackRequestCreation(String id, List waypoint) throws RestClientResponseException { + Object postBody = waypoint; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling createTrack", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'waypoint' is set + if (waypoint == null) { + throw new RestClientResponseException("Missing the required parameter 'waypoint' when calling createTrack", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs/{id}/track", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Drive Log's Track + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id + * @param waypoint Working Time Date Span entity + * @return List<Waypoint> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public List createTrack( String id, List waypoint) throws RestClientResponseException { + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTrackRequestCreation(id, waypoint).body(localVarReturnType); + } + + /** + * Create a Drive Log's Track + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id + * @param waypoint Working Time Date Span entity + * @return ResponseEntity<List<Waypoint>> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> createTrackWithHttpInfo( String id, List waypoint) throws RestClientResponseException { + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference<>() {}; + return createTrackRequestCreation(id, waypoint).toEntity(localVarReturnType); + } + + /** + * Create a Drive Log's Track + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id + * @param waypoint Working Time Date Span entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createTrackWithResponseSpec(String id, List waypoint) throws RestClientResponseException { + return createTrackRequestCreation(id, waypoint); + } + + /** + * Delete a Drive Log's Track + * Deletes the Drive Log's Track. The Drive Log itself is kept. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id drive log id + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteTrackRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling deleteTrack", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs/{id}/track", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Drive Log's Track + * Deletes the Drive Log's Track. The Drive Log itself is kept. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id drive log id + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteTrack( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteTrackRequestCreation(id).body(localVarReturnType); + } + + /** + * Delete a Drive Log's Track + * Deletes the Drive Log's Track. The Drive Log itself is kept. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id drive log id + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTrackWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteTrackRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Delete a Drive Log's Track + * Deletes the Drive Log's Track. The Drive Log itself is kept. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id drive log id + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteTrackWithResponseSpec(String id) throws RestClientResponseException { + return deleteTrackRequestCreation(id); + } + + /** + * Get a Drive Log's Track + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + *

200 - The Track of the Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + * @param id drive log id + * @return List<Waypoint> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getTrackRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getTrack", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs/{id}/track", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Drive Log's Track + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + *

200 - The Track of the Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + * @param id drive log id + * @return List<Waypoint> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public List getTrack( String id) throws RestClientResponseException { + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTrackRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Drive Log's Track + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + *

200 - The Track of the Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + * @param id drive log id + * @return ResponseEntity<List<Waypoint>> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> getTrackWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference<>() {}; + return getTrackRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Drive Log's Track + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + *

200 - The Track of the Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + * @param id drive log id + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getTrackWithResponseSpec(String id) throws RestClientResponseException { + return getTrackRequestCreation(id); + } + + /** + * Replace a Drive Log's Track + * Replaces the Drive Log's Track with the waypoints in the request body. + *

200 - The updated Working Time Date Span. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id + * @param waypoint working time date span entity + * @return List<Waypoint> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec updateTrackRequestCreation(String id, List waypoint) throws RestClientResponseException { + Object postBody = waypoint; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling updateTrack", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'waypoint' is set + if (waypoint == null) { + throw new RestClientResponseException("Missing the required parameter 'waypoint' when calling updateTrack", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/drive-logs/{id}/track", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Replace a Drive Log's Track + * Replaces the Drive Log's Track with the waypoints in the request body. + *

200 - The updated Working Time Date Span. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id + * @param waypoint working time date span entity + * @return List<Waypoint> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public List updateTrack( String id, List waypoint) throws RestClientResponseException { + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateTrackRequestCreation(id, waypoint).body(localVarReturnType); + } + + /** + * Replace a Drive Log's Track + * Replaces the Drive Log's Track with the waypoints in the request body. + *

200 - The updated Working Time Date Span. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id + * @param waypoint working time date span entity + * @return ResponseEntity<List<Waypoint>> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> updateTrackWithHttpInfo( String id, List waypoint) throws RestClientResponseException { + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateTrackRequestCreation(id, waypoint).toEntity(localVarReturnType); + } + + /** + * Replace a Drive Log's Track + * Replaces the Drive Log's Track with the waypoints in the request body. + *

200 - The updated Working Time Date Span. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id + * @param waypoint working time date span entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateTrackWithResponseSpec(String id, List waypoint) throws RestClientResponseException { + return updateTrackRequestCreation(id, waypoint); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/UserApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/UserApi.java new file mode 100644 index 0000000..392e3a7 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/UserApi.java @@ -0,0 +1,741 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Error; +import java.time.LocalDate; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import com.timr.api.models.TeamsPartialPage; +import com.timr.api.models.TeamsSortColumn; +import java.net.URI; +import com.timr.api.models.User; +import com.timr.api.models.UserCreate; +import com.timr.api.models.UserUpdate; +import com.timr.api.models.UsersPage; +import com.timr.api.models.UsersSortColumn; +import com.timr.api.models.WorkScheduleModel; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(new ApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a User + * Creates a User from the data in the request body. + *

201 - The created User. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param userCreate User entity + * @return User + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createUserRequestCreation(UserCreate userCreate) throws RestClientResponseException { + Object postBody = userCreate; + // verify the required parameter 'userCreate' is set + if (userCreate == null) { + throw new RestClientResponseException("Missing the required parameter 'userCreate' when calling createUser", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a User + * Creates a User from the data in the request body. + *

201 - The created User. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param userCreate User entity + * @return User + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public User createUser( UserCreate userCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createUserRequestCreation(userCreate).body(localVarReturnType); + } + + /** + * Create a User + * Creates a User from the data in the request body. + *

201 - The created User. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param userCreate User entity + * @return ResponseEntity<User> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createUserWithHttpInfo( UserCreate userCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createUserRequestCreation(userCreate).toEntity(localVarReturnType); + } + + /** + * Create a User + * Creates a User from the data in the request body. + *

201 - The created User. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param userCreate User entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createUserWithResponseSpec(UserCreate userCreate) throws RestClientResponseException { + return createUserRequestCreation(userCreate); + } + + /** + * List a User's Team leaderships + * Lists the Teams the User leads. + *

200 - Page of Teams the User leads. + *

400 - Bad Request + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TeamsPartialPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchUserTeamLeadershipsRequestCreation(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TeamsSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling fetchUserTeamLeaderships", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users/{id}/team-leaderships", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List a User's Team leaderships + * Lists the Teams the User leads. + *

200 - Page of Teams the User leads. + *

400 - Bad Request + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TeamsPartialPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TeamsPartialPage fetchUserTeamLeaderships( String id, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchUserTeamLeadershipsRequestCreation(id, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List a User's Team leaderships + * Lists the Teams the User leads. + *

200 - Page of Teams the User leads. + *

400 - Bad Request + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<TeamsPartialPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchUserTeamLeadershipsWithHttpInfo( String id, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchUserTeamLeadershipsRequestCreation(id, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List a User's Team leaderships + * Lists the Teams the User leads. + *

200 - Page of Teams the User leads. + *

400 - Bad Request + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchUserTeamLeadershipsWithResponseSpec(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TeamsSortColumn sortBy) throws RestClientResponseException { + return fetchUserTeamLeadershipsRequestCreation(id, pageToken, limit, sortDirection, sortBy); + } + + /** + * List a User's Team memberships + * Lists the Teams the User is a member of. + *

200 - Page of Teams the User is a member of. + *

400 - Bad Request + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TeamsPartialPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchUserTeamMembershipsRequestCreation(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TeamsSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling fetchUserTeamMemberships", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users/{id}/team-memberships", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List a User's Team memberships + * Lists the Teams the User is a member of. + *

200 - Page of Teams the User is a member of. + *

400 - Bad Request + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return TeamsPartialPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public TeamsPartialPage fetchUserTeamMemberships( String id, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchUserTeamMembershipsRequestCreation(id, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List a User's Team memberships + * Lists the Teams the User is a member of. + *

200 - Page of Teams the User is a member of. + *

400 - Bad Request + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<TeamsPartialPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchUserTeamMembershipsWithHttpInfo( String id, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchUserTeamMembershipsRequestCreation(id, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List a User's Team memberships + * Lists the Teams the User is a member of. + *

200 - Page of Teams the User is a member of. + *

400 - Bad Request + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchUserTeamMembershipsWithResponseSpec(String id, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable TeamsSortColumn sortBy) throws RestClientResponseException { + return fetchUserTeamMembershipsRequestCreation(id, pageToken, limit, sortDirection, sortBy); + } + + /** + * List Users + * Lists the Users the authenticated user or API token can access. + *

200 - Page of Users. + *

400 - Bad Request + * @param name Only return Users whose name contains this text. + * @param entryDateFrom Only return Users whose entry date is on or after this day. + * @param entryDateTo Only return Users whose entry date is on or before this day. + * @param resignDateFrom Only return Users whose resignation date is on or after this day. + * @param resignDateTo Only return Users whose resignation date is on or before this day. + * @param resigned Only return Users who have resigned (true) or have not resigned (false). + * @param employeeNumber Only return Users with this employee number. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return UsersPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchUsersRequestCreation(@Nullable String name, @Nullable LocalDate entryDateFrom, @Nullable LocalDate entryDateTo, @Nullable LocalDate resignDateFrom, @Nullable LocalDate resignDateTo, @Nullable Boolean resigned, @Nullable String employeeNumber, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable UsersSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "entry_date_from", entryDateFrom)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "entry_date_to", entryDateTo)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "resign_date_from", resignDateFrom)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "resign_date_to", resignDateTo)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "resigned", resigned)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "employee_number", employeeNumber)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Users + * Lists the Users the authenticated user or API token can access. + *

200 - Page of Users. + *

400 - Bad Request + * @param name Only return Users whose name contains this text. + * @param entryDateFrom Only return Users whose entry date is on or after this day. + * @param entryDateTo Only return Users whose entry date is on or before this day. + * @param resignDateFrom Only return Users whose resignation date is on or after this day. + * @param resignDateTo Only return Users whose resignation date is on or before this day. + * @param resigned Only return Users who have resigned (true) or have not resigned (false). + * @param employeeNumber Only return Users with this employee number. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return UsersPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public UsersPage fetchUsers( String name, LocalDate entryDateFrom, LocalDate entryDateTo, LocalDate resignDateFrom, LocalDate resignDateTo, Boolean resigned, String employeeNumber, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchUsersRequestCreation(name, entryDateFrom, entryDateTo, resignDateFrom, resignDateTo, resigned, employeeNumber, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Users + * Lists the Users the authenticated user or API token can access. + *

200 - Page of Users. + *

400 - Bad Request + * @param name Only return Users whose name contains this text. + * @param entryDateFrom Only return Users whose entry date is on or after this day. + * @param entryDateTo Only return Users whose entry date is on or before this day. + * @param resignDateFrom Only return Users whose resignation date is on or after this day. + * @param resignDateTo Only return Users whose resignation date is on or before this day. + * @param resigned Only return Users who have resigned (true) or have not resigned (false). + * @param employeeNumber Only return Users with this employee number. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<UsersPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchUsersWithHttpInfo( String name, LocalDate entryDateFrom, LocalDate entryDateTo, LocalDate resignDateFrom, LocalDate resignDateTo, Boolean resigned, String employeeNumber, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchUsersRequestCreation(name, entryDateFrom, entryDateTo, resignDateFrom, resignDateTo, resigned, employeeNumber, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Users + * Lists the Users the authenticated user or API token can access. + *

200 - Page of Users. + *

400 - Bad Request + * @param name Only return Users whose name contains this text. + * @param entryDateFrom Only return Users whose entry date is on or after this day. + * @param entryDateTo Only return Users whose entry date is on or before this day. + * @param resignDateFrom Only return Users whose resignation date is on or after this day. + * @param resignDateTo Only return Users whose resignation date is on or before this day. + * @param resigned Only return Users who have resigned (true) or have not resigned (false). + * @param employeeNumber Only return Users with this employee number. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchUsersWithResponseSpec(@Nullable String name, @Nullable LocalDate entryDateFrom, @Nullable LocalDate entryDateTo, @Nullable LocalDate resignDateFrom, @Nullable LocalDate resignDateTo, @Nullable Boolean resigned, @Nullable String employeeNumber, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable UsersSortColumn sortBy) throws RestClientResponseException { + return fetchUsersRequestCreation(name, entryDateFrom, entryDateTo, resignDateFrom, resignDateTo, resigned, employeeNumber, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a User + * Returns a single User by its ID. + *

200 - The requested User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @return User + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getUserRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getUser", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a User + * Returns a single User by its ID. + *

200 - The requested User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @return User + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public User getUser( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getUserRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a User + * Returns a single User by its ID. + *

200 - The requested User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @return ResponseEntity<User> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getUserRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a User + * Returns a single User by its ID. + *

200 - The requested User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getUserWithResponseSpec(String id) throws RestClientResponseException { + return getUserRequestCreation(id); + } + + /** + * Get a User's Work Schedule Model + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + *

200 - The Work Schedule Model assigned to the User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @return WorkScheduleModel + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getUserWorkScheduleModelRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getUserWorkScheduleModel", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users/{id}/work-schedule-model", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a User's Work Schedule Model + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + *

200 - The Work Schedule Model assigned to the User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @return WorkScheduleModel + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkScheduleModel getUserWorkScheduleModel( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getUserWorkScheduleModelRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a User's Work Schedule Model + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + *

200 - The Work Schedule Model assigned to the User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @return ResponseEntity<WorkScheduleModel> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserWorkScheduleModelWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getUserWorkScheduleModelRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a User's Work Schedule Model + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + *

200 - The Work Schedule Model assigned to the User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getUserWorkScheduleModelWithResponseSpec(String id) throws RestClientResponseException { + return getUserWorkScheduleModelRequestCreation(id); + } + + /** + * Update a User + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated User. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the User. + * @param userUpdate User entity + * @return User + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec updateUserRequestCreation(String id, UserUpdate userUpdate) throws RestClientResponseException { + Object postBody = userUpdate; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling updateUser", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'userUpdate' is set + if (userUpdate == null) { + throw new RestClientResponseException("Missing the required parameter 'userUpdate' when calling updateUser", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/users/{id}", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Update a User + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated User. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the User. + * @param userUpdate User entity + * @return User + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public User updateUser( String id, UserUpdate userUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateUserRequestCreation(id, userUpdate).body(localVarReturnType); + } + + /** + * Update a User + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated User. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the User. + * @param userUpdate User entity + * @return ResponseEntity<User> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateUserWithHttpInfo( String id, UserUpdate userUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateUserRequestCreation(id, userUpdate).toEntity(localVarReturnType); + } + + /** + * Update a User + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated User. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the User. + * @param userUpdate User entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateUserWithResponseSpec(String id, UserUpdate userUpdate) throws RestClientResponseException { + return updateUserRequestCreation(id, userUpdate); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkScheduleModelApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkScheduleModelApi.java new file mode 100644 index 0000000..4cc38ee --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkScheduleModelApi.java @@ -0,0 +1,309 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.Error; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.SortDirection; +import java.net.URI; +import com.timr.api.models.WorkScheduleModel; +import com.timr.api.models.WorkScheduleModelSortColumn; +import com.timr.api.models.WorkScheduleModelsPage; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkScheduleModelApi { + private ApiClient apiClient; + + public WorkScheduleModelApi() { + this(new ApiClient()); + } + + public WorkScheduleModelApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete a Work Schedule Model + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Work Schedule Model. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteWorkScheduleModelRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling deleteWorkScheduleModel", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/work-schedule-models/{id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Work Schedule Model + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Work Schedule Model. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteWorkScheduleModel( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteWorkScheduleModelRequestCreation(id).body(localVarReturnType); + } + + /** + * Delete a Work Schedule Model + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Work Schedule Model. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteWorkScheduleModelWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteWorkScheduleModelRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Delete a Work Schedule Model + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Work Schedule Model. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteWorkScheduleModelWithResponseSpec(String id) throws RestClientResponseException { + return deleteWorkScheduleModelRequestCreation(id); + } + + /** + * List Work Schedule Models + * Lists the Work Schedule Models the authenticated user or API token can access. + *

200 - Page of Work Schedule Models. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return WorkScheduleModelsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchWorkScheduleModelsRequestCreation(@Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable WorkScheduleModelSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/work-schedule-models", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Work Schedule Models + * Lists the Work Schedule Models the authenticated user or API token can access. + *

200 - Page of Work Schedule Models. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return WorkScheduleModelsPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkScheduleModelsPage fetchWorkScheduleModels( String pageToken, Integer limit, SortDirection sortDirection, WorkScheduleModelSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchWorkScheduleModelsRequestCreation(pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Work Schedule Models + * Lists the Work Schedule Models the authenticated user or API token can access. + *

200 - Page of Work Schedule Models. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<WorkScheduleModelsPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchWorkScheduleModelsWithHttpInfo( String pageToken, Integer limit, SortDirection sortDirection, WorkScheduleModelSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchWorkScheduleModelsRequestCreation(pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Work Schedule Models + * Lists the Work Schedule Models the authenticated user or API token can access. + *

200 - Page of Work Schedule Models. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchWorkScheduleModelsWithResponseSpec(@Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable WorkScheduleModelSortColumn sortBy) throws RestClientResponseException { + return fetchWorkScheduleModelsRequestCreation(pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Work Schedule Model + * Returns a single Work Schedule Model by its ID. + *

200 - The requested Work Schedule Model. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Work Schedule Model. + * @return WorkScheduleModel + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getWorkScheduleModelRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getWorkScheduleModel", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/work-schedule-models/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Work Schedule Model + * Returns a single Work Schedule Model by its ID. + *

200 - The requested Work Schedule Model. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Work Schedule Model. + * @return WorkScheduleModel + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkScheduleModel getWorkScheduleModel( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getWorkScheduleModelRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Work Schedule Model + * Returns a single Work Schedule Model by its ID. + *

200 - The requested Work Schedule Model. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Work Schedule Model. + * @return ResponseEntity<WorkScheduleModel> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getWorkScheduleModelWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getWorkScheduleModelRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Work Schedule Model + * Returns a single Work Schedule Model by its ID. + *

200 - The requested Work Schedule Model. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Work Schedule Model. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getWorkScheduleModelWithResponseSpec(String id) throws RestClientResponseException { + return getWorkScheduleModelRequestCreation(id); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkingTimeApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkingTimeApi.java new file mode 100644 index 0000000..6c9b1cc --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkingTimeApi.java @@ -0,0 +1,653 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.DeletedEntrySortColumn; +import com.timr.api.models.DeletedEntryWithMetadataPage; +import com.timr.api.models.Error; +import java.time.LocalDate; +import org.jspecify.annotations.Nullable; +import java.time.OffsetDateTime; +import com.timr.api.models.SortDirection; +import java.net.URI; +import com.timr.api.models.WorkingTime; +import com.timr.api.models.WorkingTimeCreate; +import com.timr.api.models.WorkingTimeStatus; +import com.timr.api.models.WorkingTimeTypeCategory; +import com.timr.api.models.WorkingTimeUpdate; +import com.timr.api.models.WorkingTimesPage; +import com.timr.api.models.WorkingTimesSortColumn; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeApi { + private ApiClient apiClient; + + public WorkingTimeApi() { + this(new ApiClient()); + } + + public WorkingTimeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a Working Time + * Creates a Working Time from the data in the request body. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeCreate Working Time entity + * @return WorkingTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createWorkingTimeRequestCreation(WorkingTimeCreate workingTimeCreate) throws RestClientResponseException { + Object postBody = workingTimeCreate; + // verify the required parameter 'workingTimeCreate' is set + if (workingTimeCreate == null) { + throw new RestClientResponseException("Missing the required parameter 'workingTimeCreate' when calling createWorkingTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-times", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Working Time + * Creates a Working Time from the data in the request body. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeCreate Working Time entity + * @return WorkingTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTime createWorkingTime( WorkingTimeCreate workingTimeCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createWorkingTimeRequestCreation(workingTimeCreate).body(localVarReturnType); + } + + /** + * Create a Working Time + * Creates a Working Time from the data in the request body. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeCreate Working Time entity + * @return ResponseEntity<WorkingTime> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createWorkingTimeWithHttpInfo( WorkingTimeCreate workingTimeCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createWorkingTimeRequestCreation(workingTimeCreate).toEntity(localVarReturnType); + } + + /** + * Create a Working Time + * Creates a Working Time from the data in the request body. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeCreate Working Time entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createWorkingTimeWithResponseSpec(WorkingTimeCreate workingTimeCreate) throws RestClientResponseException { + return createWorkingTimeRequestCreation(workingTimeCreate); + } + + /** + * Delete a Working Time + * Deletes the Working Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteWorkingTimeRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling deleteWorkingTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-times/{id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Working Time + * Deletes the Working Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteWorkingTime( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteWorkingTimeRequestCreation(id).body(localVarReturnType); + } + + /** + * Delete a Working Time + * Deletes the Working Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteWorkingTimeWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteWorkingTimeRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Delete a Working Time + * Deletes the Working Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteWorkingTimeWithResponseSpec(String id) throws RestClientResponseException { + return deleteWorkingTimeRequestCreation(id); + } + + /** + * List deleted Working Times + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DeletedEntryWithMetadataPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchDeletedWorkingTimesRequestCreation(@Nullable OffsetDateTime lastModifiedAfter, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DeletedEntrySortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-times:deleted", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List deleted Working Times + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DeletedEntryWithMetadataPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DeletedEntryWithMetadataPage fetchDeletedWorkingTimes( OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDeletedWorkingTimesRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List deleted Working Times + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<DeletedEntryWithMetadataPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDeletedWorkingTimesWithHttpInfo( OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDeletedWorkingTimesRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List deleted Working Times + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchDeletedWorkingTimesWithResponseSpec(@Nullable OffsetDateTime lastModifiedAfter, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DeletedEntrySortColumn sortBy) throws RestClientResponseException { + return fetchDeletedWorkingTimesRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + } + + /** + * List Working Times + * Lists the Working Times the authenticated user or API token can access. + *

200 - Page of Working Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param workingTimeTypes Only return entries of these Working Time Types. + * @param workingTimeTypeCategories Only return entries whose Working Time Type is in one of these categories. + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return WorkingTimesPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchWorkingTimesRequestCreation(@Nullable String notes, @Nullable LocalDate startFrom, @Nullable LocalDate startTo, @Nullable OffsetDateTime lastModifiedAfter, @Nullable List workingTimeTypes, @Nullable List workingTimeTypeCategories, @Nullable List statuses, @Nullable List users, @Nullable Boolean changed, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable WorkingTimesSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "notes", notes)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_from", startFrom)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_to", startTo)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "working_time_types", workingTimeTypes)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "working_time_type_categories", workingTimeTypeCategories)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "statuses", statuses)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "users", users)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "changed", changed)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-times", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Working Times + * Lists the Working Times the authenticated user or API token can access. + *

200 - Page of Working Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param workingTimeTypes Only return entries of these Working Time Types. + * @param workingTimeTypeCategories Only return entries whose Working Time Type is in one of these categories. + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return WorkingTimesPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTimesPage fetchWorkingTimes( String notes, LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, List workingTimeTypes, List workingTimeTypeCategories, List statuses, List users, Boolean changed, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimesSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchWorkingTimesRequestCreation(notes, startFrom, startTo, lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, changed, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Working Times + * Lists the Working Times the authenticated user or API token can access. + *

200 - Page of Working Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param workingTimeTypes Only return entries of these Working Time Types. + * @param workingTimeTypeCategories Only return entries whose Working Time Type is in one of these categories. + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<WorkingTimesPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchWorkingTimesWithHttpInfo( String notes, LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, List workingTimeTypes, List workingTimeTypeCategories, List statuses, List users, Boolean changed, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimesSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchWorkingTimesRequestCreation(notes, startFrom, startTo, lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, changed, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Working Times + * Lists the Working Times the authenticated user or API token can access. + *

200 - Page of Working Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. + * @param startFrom Only return entries starting on or after this day. + * @param startTo Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param workingTimeTypes Only return entries of these Working Time Types. + * @param workingTimeTypeCategories Only return entries whose Working Time Type is in one of these categories. + * @param statuses Only return entries in one of these statuses. + * @param users Only return entries belonging to these users. + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchWorkingTimesWithResponseSpec(@Nullable String notes, @Nullable LocalDate startFrom, @Nullable LocalDate startTo, @Nullable OffsetDateTime lastModifiedAfter, @Nullable List workingTimeTypes, @Nullable List workingTimeTypeCategories, @Nullable List statuses, @Nullable List users, @Nullable Boolean changed, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable WorkingTimesSortColumn sortBy) throws RestClientResponseException { + return fetchWorkingTimesRequestCreation(notes, startFrom, startTo, lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, changed, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Working Time + * Returns a single Working Time by its ID. + *

200 - The requested Working Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time. + * @return WorkingTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getWorkingTimeRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getWorkingTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-times/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Working Time + * Returns a single Working Time by its ID. + *

200 - The requested Working Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time. + * @return WorkingTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTime getWorkingTime( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getWorkingTimeRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Working Time + * Returns a single Working Time by its ID. + *

200 - The requested Working Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time. + * @return ResponseEntity<WorkingTime> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getWorkingTimeWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getWorkingTimeRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Working Time + * Returns a single Working Time by its ID. + *

200 - The requested Working Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getWorkingTimeWithResponseSpec(String id) throws RestClientResponseException { + return getWorkingTimeRequestCreation(id); + } + + /** + * Update a Working Time + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Working Time. + *

302 - No Working Time was created because the working time type requires a request (recordingMode BY_REQUEST); a Working Time Request was created instead. The Location header points to the created Working Time Request. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time. + * @param workingTimeUpdate Working Time entity + * @return WorkingTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec updateWorkingTimeRequestCreation(String id, WorkingTimeUpdate workingTimeUpdate) throws RestClientResponseException { + Object postBody = workingTimeUpdate; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling updateWorkingTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'workingTimeUpdate' is set + if (workingTimeUpdate == null) { + throw new RestClientResponseException("Missing the required parameter 'workingTimeUpdate' when calling updateWorkingTime", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-times/{id}", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Update a Working Time + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Working Time. + *

302 - No Working Time was created because the working time type requires a request (recordingMode BY_REQUEST); a Working Time Request was created instead. The Location header points to the created Working Time Request. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time. + * @param workingTimeUpdate Working Time entity + * @return WorkingTime + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTime updateWorkingTime( String id, WorkingTimeUpdate workingTimeUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateWorkingTimeRequestCreation(id, workingTimeUpdate).body(localVarReturnType); + } + + /** + * Update a Working Time + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Working Time. + *

302 - No Working Time was created because the working time type requires a request (recordingMode BY_REQUEST); a Working Time Request was created instead. The Location header points to the created Working Time Request. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time. + * @param workingTimeUpdate Working Time entity + * @return ResponseEntity<WorkingTime> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateWorkingTimeWithHttpInfo( String id, WorkingTimeUpdate workingTimeUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateWorkingTimeRequestCreation(id, workingTimeUpdate).toEntity(localVarReturnType); + } + + /** + * Update a Working Time + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Working Time. + *

302 - No Working Time was created because the working time type requires a request (recordingMode BY_REQUEST); a Working Time Request was created instead. The Location header points to the created Working Time Request. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time. + * @param workingTimeUpdate Working Time entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateWorkingTimeWithResponseSpec(String id, WorkingTimeUpdate workingTimeUpdate) throws RestClientResponseException { + return updateWorkingTimeRequestCreation(id, workingTimeUpdate); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkingTimeDateSpanApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkingTimeDateSpanApi.java new file mode 100644 index 0000000..41afc60 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkingTimeDateSpanApi.java @@ -0,0 +1,631 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.DeletedEntrySortColumn; +import com.timr.api.models.DeletedEntryWithMetadataPage; +import com.timr.api.models.Error; +import java.time.LocalDate; +import org.jspecify.annotations.Nullable; +import java.time.OffsetDateTime; +import com.timr.api.models.SortDirection; +import java.net.URI; +import com.timr.api.models.WorkingTimeDateSpan; +import com.timr.api.models.WorkingTimeDateSpanCreate; +import com.timr.api.models.WorkingTimeDateSpanPage; +import com.timr.api.models.WorkingTimeDateSpanUpdate; +import com.timr.api.models.WorkingTimeDateSpansSortColumn; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpanApi { + private ApiClient apiClient; + + public WorkingTimeDateSpanApi() { + this(new ApiClient()); + } + + public WorkingTimeDateSpanApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Create a Working Time Date Span + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeDateSpanCreate Working Time Date Span entity + * @return WorkingTimeDateSpan + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createWorkingTimeDateSpanRequestCreation(WorkingTimeDateSpanCreate workingTimeDateSpanCreate) throws RestClientResponseException { + Object postBody = workingTimeDateSpanCreate; + // verify the required parameter 'workingTimeDateSpanCreate' is set + if (workingTimeDateSpanCreate == null) { + throw new RestClientResponseException("Missing the required parameter 'workingTimeDateSpanCreate' when calling createWorkingTimeDateSpan", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-time-date-spans", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Create a Working Time Date Span + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeDateSpanCreate Working Time Date Span entity + * @return WorkingTimeDateSpan + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTimeDateSpan createWorkingTimeDateSpan( WorkingTimeDateSpanCreate workingTimeDateSpanCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createWorkingTimeDateSpanRequestCreation(workingTimeDateSpanCreate).body(localVarReturnType); + } + + /** + * Create a Working Time Date Span + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeDateSpanCreate Working Time Date Span entity + * @return ResponseEntity<WorkingTimeDateSpan> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createWorkingTimeDateSpanWithHttpInfo( WorkingTimeDateSpanCreate workingTimeDateSpanCreate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return createWorkingTimeDateSpanRequestCreation(workingTimeDateSpanCreate).toEntity(localVarReturnType); + } + + /** + * Create a Working Time Date Span + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeDateSpanCreate Working Time Date Span entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec createWorkingTimeDateSpanWithResponseSpec(WorkingTimeDateSpanCreate workingTimeDateSpanCreate) throws RestClientResponseException { + return createWorkingTimeDateSpanRequestCreation(workingTimeDateSpanCreate); + } + + /** + * Delete a Working Time Date Span + * Deletes the Working Time Date Span together with the Working Times it covers. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Date Span. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteWorkingTimeDateSpanRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling deleteWorkingTimeDateSpan", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-time-date-spans/{id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Working Time Date Span + * Deletes the Working Time Date Span together with the Working Times it covers. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Date Span. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteWorkingTimeDateSpan( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteWorkingTimeDateSpanRequestCreation(id).body(localVarReturnType); + } + + /** + * Delete a Working Time Date Span + * Deletes the Working Time Date Span together with the Working Times it covers. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Date Span. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteWorkingTimeDateSpanWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteWorkingTimeDateSpanRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Delete a Working Time Date Span + * Deletes the Working Time Date Span together with the Working Times it covers. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Date Span. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteWorkingTimeDateSpanWithResponseSpec(String id) throws RestClientResponseException { + return deleteWorkingTimeDateSpanRequestCreation(id); + } + + /** + * List deleted Working Time Date Spans + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Time Date Spans. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DeletedEntryWithMetadataPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchDeletedWorkingTimeDateSpansRequestCreation(@Nullable OffsetDateTime lastModifiedAfter, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DeletedEntrySortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-time-date-spans:deleted", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List deleted Working Time Date Spans + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Time Date Spans. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return DeletedEntryWithMetadataPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public DeletedEntryWithMetadataPage fetchDeletedWorkingTimeDateSpans( OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDeletedWorkingTimeDateSpansRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List deleted Working Time Date Spans + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Time Date Spans. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<DeletedEntryWithMetadataPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDeletedWorkingTimeDateSpansWithHttpInfo( OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchDeletedWorkingTimeDateSpansRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List deleted Working Time Date Spans + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Time Date Spans. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchDeletedWorkingTimeDateSpansWithResponseSpec(@Nullable OffsetDateTime lastModifiedAfter, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable DeletedEntrySortColumn sortBy) throws RestClientResponseException { + return fetchDeletedWorkingTimeDateSpansRequestCreation(lastModifiedAfter, pageToken, limit, sortDirection, sortBy); + } + + /** + * List Working Time Date Spans + * Lists the Working Time Date Spans the authenticated user or API token can access. + *

200 - Page of Working Time Date Spans. + *

400 - Bad Request + * @param from Only return Working Time Date Spans that end on or after this day. + * @param to Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param workingTimeTypes Only return entries of these Working Time Types. + * @param users Only return entries belonging to these users. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return WorkingTimeDateSpanPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchWorkingTimeDateSpansRequestCreation(@Nullable LocalDate from, @Nullable LocalDate to, @Nullable OffsetDateTime lastModifiedAfter, @Nullable List workingTimeTypes, @Nullable List users, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable WorkingTimeDateSpansSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "from", from)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "to", to)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "working_time_types", workingTimeTypes)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "users", users)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-time-date-spans", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Working Time Date Spans + * Lists the Working Time Date Spans the authenticated user or API token can access. + *

200 - Page of Working Time Date Spans. + *

400 - Bad Request + * @param from Only return Working Time Date Spans that end on or after this day. + * @param to Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param workingTimeTypes Only return entries of these Working Time Types. + * @param users Only return entries belonging to these users. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return WorkingTimeDateSpanPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTimeDateSpanPage fetchWorkingTimeDateSpans( LocalDate from, LocalDate to, OffsetDateTime lastModifiedAfter, List workingTimeTypes, List users, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimeDateSpansSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchWorkingTimeDateSpansRequestCreation(from, to, lastModifiedAfter, workingTimeTypes, users, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Working Time Date Spans + * Lists the Working Time Date Spans the authenticated user or API token can access. + *

200 - Page of Working Time Date Spans. + *

400 - Bad Request + * @param from Only return Working Time Date Spans that end on or after this day. + * @param to Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param workingTimeTypes Only return entries of these Working Time Types. + * @param users Only return entries belonging to these users. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<WorkingTimeDateSpanPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchWorkingTimeDateSpansWithHttpInfo( LocalDate from, LocalDate to, OffsetDateTime lastModifiedAfter, List workingTimeTypes, List users, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimeDateSpansSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchWorkingTimeDateSpansRequestCreation(from, to, lastModifiedAfter, workingTimeTypes, users, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Working Time Date Spans + * Lists the Working Time Date Spans the authenticated user or API token can access. + *

200 - Page of Working Time Date Spans. + *

400 - Bad Request + * @param from Only return Working Time Date Spans that end on or after this day. + * @param to Only return entries starting on or before this day. + * @param lastModifiedAfter Only return entries modified after this instant. + * @param workingTimeTypes Only return entries of these Working Time Types. + * @param users Only return entries belonging to these users. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchWorkingTimeDateSpansWithResponseSpec(@Nullable LocalDate from, @Nullable LocalDate to, @Nullable OffsetDateTime lastModifiedAfter, @Nullable List workingTimeTypes, @Nullable List users, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable WorkingTimeDateSpansSortColumn sortBy) throws RestClientResponseException { + return fetchWorkingTimeDateSpansRequestCreation(from, to, lastModifiedAfter, workingTimeTypes, users, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Working Time Date Span + * Returns a single Working Time Date Span by its ID. + *

200 - The requested Working Time Date Span. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Date Span. + * @return WorkingTimeDateSpan + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getWorkingTimeDateSpanRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getWorkingTimeDateSpan", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-time-date-spans/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Working Time Date Span + * Returns a single Working Time Date Span by its ID. + *

200 - The requested Working Time Date Span. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Date Span. + * @return WorkingTimeDateSpan + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTimeDateSpan getWorkingTimeDateSpan( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getWorkingTimeDateSpanRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Working Time Date Span + * Returns a single Working Time Date Span by its ID. + *

200 - The requested Working Time Date Span. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Date Span. + * @return ResponseEntity<WorkingTimeDateSpan> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getWorkingTimeDateSpanWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getWorkingTimeDateSpanRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Working Time Date Span + * Returns a single Working Time Date Span by its ID. + *

200 - The requested Working Time Date Span. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Date Span. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getWorkingTimeDateSpanWithResponseSpec(String id) throws RestClientResponseException { + return getWorkingTimeDateSpanRequestCreation(id); + } + + /** + * Update a Working Time Date Span + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + *

200 - The updated Working Time Date Span. + *

204 - Empty response indicating that a date span got deleted. This can happen when it is updated to a day where no working hours can be booked. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time Date Span. + * @param workingTimeDateSpanUpdate working time date span entity + * @return WorkingTimeDateSpan + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec updateWorkingTimeDateSpanRequestCreation(String id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate) throws RestClientResponseException { + Object postBody = workingTimeDateSpanUpdate; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling updateWorkingTimeDateSpan", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // verify the required parameter 'workingTimeDateSpanUpdate' is set + if (workingTimeDateSpanUpdate == null) { + throw new RestClientResponseException("Missing the required parameter 'workingTimeDateSpanUpdate' when calling updateWorkingTimeDateSpan", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-time-date-spans/{id}", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Update a Working Time Date Span + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + *

200 - The updated Working Time Date Span. + *

204 - Empty response indicating that a date span got deleted. This can happen when it is updated to a day where no working hours can be booked. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time Date Span. + * @param workingTimeDateSpanUpdate working time date span entity + * @return WorkingTimeDateSpan + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTimeDateSpan updateWorkingTimeDateSpan( String id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateWorkingTimeDateSpanRequestCreation(id, workingTimeDateSpanUpdate).body(localVarReturnType); + } + + /** + * Update a Working Time Date Span + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + *

200 - The updated Working Time Date Span. + *

204 - Empty response indicating that a date span got deleted. This can happen when it is updated to a day where no working hours can be booked. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time Date Span. + * @param workingTimeDateSpanUpdate working time date span entity + * @return ResponseEntity<WorkingTimeDateSpan> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateWorkingTimeDateSpanWithHttpInfo( String id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return updateWorkingTimeDateSpanRequestCreation(id, workingTimeDateSpanUpdate).toEntity(localVarReturnType); + } + + /** + * Update a Working Time Date Span + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + *

200 - The updated Working Time Date Span. + *

204 - Empty response indicating that a date span got deleted. This can happen when it is updated to a day where no working hours can be booked. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time Date Span. + * @param workingTimeDateSpanUpdate working time date span entity + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec updateWorkingTimeDateSpanWithResponseSpec(String id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate) throws RestClientResponseException { + return updateWorkingTimeDateSpanRequestCreation(id, workingTimeDateSpanUpdate); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkingTimeTypeApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkingTimeTypeApi.java new file mode 100644 index 0000000..7417299 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/WorkingTimeTypeApi.java @@ -0,0 +1,353 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; + +import com.timr.api.models.DurationUnit; +import com.timr.api.models.Error; +import org.jspecify.annotations.Nullable; +import com.timr.api.models.RecordingModeUser; +import com.timr.api.models.SortDirection; +import java.net.URI; +import com.timr.api.models.WorkingTimeType; +import com.timr.api.models.WorkingTimeTypeCategory; +import com.timr.api.models.WorkingTimeTypeSubCategory; +import com.timr.api.models.WorkingTimeTypesPage; +import com.timr.api.models.WorkingTimeTypesSortColumn; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClient.ResponseSpec; +import org.springframework.web.client.RestClientResponseException; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeTypeApi { + private ApiClient apiClient; + + public WorkingTimeTypeApi() { + this(new ApiClient()); + } + + public WorkingTimeTypeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Delete a Working Time Type + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Type. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteWorkingTimeTypeRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling deleteWorkingTimeType", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-time-types/{id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Working Time Type + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Type. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteWorkingTimeType( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteWorkingTimeTypeRequestCreation(id).body(localVarReturnType); + } + + /** + * Delete a Working Time Type + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Type. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteWorkingTimeTypeWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteWorkingTimeTypeRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Delete a Working Time Type + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Type. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteWorkingTimeTypeWithResponseSpec(String id) throws RestClientResponseException { + return deleteWorkingTimeTypeRequestCreation(id); + } + + /** + * List Working Time Types + * Lists the Working Time Types the authenticated user or API token can access. + *

200 - Page of Working Time Types. + *

400 - Bad Request + * @param name Only return entries whose name contains this text. + * @param shortName filter by short name + * @param description filter by description + * @param categories filter by WorkingTimeTypeCategory + * @param subCategories filter by WorkingTimeTypeSubCategory + * @param editUnits filter by WorkingTimeType's DurationUnit + * @param archived Only return entries that are archived (true) or not archived (false). + * @param recordingModes filter entries bAWS on their RecordingMode + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return WorkingTimeTypesPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec fetchWorkingTimeTypesRequestCreation(@Nullable String name, @Nullable String shortName, @Nullable String description, @Nullable List categories, @Nullable List subCategories, @Nullable List editUnits, @Nullable Boolean archived, @Nullable List recordingModes, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable WorkingTimeTypesSortColumn sortBy) throws RestClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap<>(); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "short_name", shortName)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "description", description)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "categories", categories)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "sub_categories", subCategories)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "edit_units", editUnits)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "archived", archived)); + queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "recording_modes", recordingModes)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + queryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-time-types", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * List Working Time Types + * Lists the Working Time Types the authenticated user or API token can access. + *

200 - Page of Working Time Types. + *

400 - Bad Request + * @param name Only return entries whose name contains this text. + * @param shortName filter by short name + * @param description filter by description + * @param categories filter by WorkingTimeTypeCategory + * @param subCategories filter by WorkingTimeTypeSubCategory + * @param editUnits filter by WorkingTimeType's DurationUnit + * @param archived Only return entries that are archived (true) or not archived (false). + * @param recordingModes filter entries bAWS on their RecordingMode + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return WorkingTimeTypesPage + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTimeTypesPage fetchWorkingTimeTypes( String name, String shortName, String description, List categories, List subCategories, List editUnits, Boolean archived, List recordingModes, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimeTypesSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchWorkingTimeTypesRequestCreation(name, shortName, description, categories, subCategories, editUnits, archived, recordingModes, pageToken, limit, sortDirection, sortBy).body(localVarReturnType); + } + + /** + * List Working Time Types + * Lists the Working Time Types the authenticated user or API token can access. + *

200 - Page of Working Time Types. + *

400 - Bad Request + * @param name Only return entries whose name contains this text. + * @param shortName filter by short name + * @param description filter by description + * @param categories filter by WorkingTimeTypeCategory + * @param subCategories filter by WorkingTimeTypeSubCategory + * @param editUnits filter by WorkingTimeType's DurationUnit + * @param archived Only return entries that are archived (true) or not archived (false). + * @param recordingModes filter entries bAWS on their RecordingMode + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseEntity<WorkingTimeTypesPage> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchWorkingTimeTypesWithHttpInfo( String name, String shortName, String description, List categories, List subCategories, List editUnits, Boolean archived, List recordingModes, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimeTypesSortColumn sortBy) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return fetchWorkingTimeTypesRequestCreation(name, shortName, description, categories, subCategories, editUnits, archived, recordingModes, pageToken, limit, sortDirection, sortBy).toEntity(localVarReturnType); + } + + /** + * List Working Time Types + * Lists the Working Time Types the authenticated user or API token can access. + *

200 - Page of Working Time Types. + *

400 - Bad Request + * @param name Only return entries whose name contains this text. + * @param shortName filter by short name + * @param description filter by description + * @param categories filter by WorkingTimeTypeCategory + * @param subCategories filter by WorkingTimeTypeSubCategory + * @param editUnits filter by WorkingTimeType's DurationUnit + * @param archived Only return entries that are archived (true) or not archived (false). + * @param recordingModes filter entries bAWS on their RecordingMode + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. + * @param sortDirection Direction to sort the entries in. + * @param sortBy Property to sort the entries by. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec fetchWorkingTimeTypesWithResponseSpec(@Nullable String name, @Nullable String shortName, @Nullable String description, @Nullable List categories, @Nullable List subCategories, @Nullable List editUnits, @Nullable Boolean archived, @Nullable List recordingModes, @Nullable String pageToken, @Nullable Integer limit, @Nullable SortDirection sortDirection, @Nullable WorkingTimeTypesSortColumn sortBy) throws RestClientResponseException { + return fetchWorkingTimeTypesRequestCreation(name, shortName, description, categories, subCategories, editUnits, archived, recordingModes, pageToken, limit, sortDirection, sortBy); + } + + /** + * Get a Working Time Type + * Returns a single Working Time Type by its ID. + *

200 - The requested Working Time Type. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Type. + * @return WorkingTimeType + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec getWorkingTimeTypeRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling getWorkingTimeType", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap queryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/working-time-types/{id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Get a Working Time Type + * Returns a single Working Time Type by its ID. + *

200 - The requested Working Time Type. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Type. + * @return WorkingTimeType + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public WorkingTimeType getWorkingTimeType( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getWorkingTimeTypeRequestCreation(id).body(localVarReturnType); + } + + /** + * Get a Working Time Type + * Returns a single Working Time Type by its ID. + *

200 - The requested Working Time Type. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Type. + * @return ResponseEntity<WorkingTimeType> + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getWorkingTimeTypeWithHttpInfo( String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return getWorkingTimeTypeRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Get a Working Time Type + * Returns a single Working Time Type by its ID. + *

200 - The requested Working Time Type. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Type. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec getWorkingTimeTypeWithResponseSpec(String id) throws RestClientResponseException { + return getWorkingTimeTypeRequestCreation(id); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/package-info.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/package-info.java new file mode 100644 index 0000000..6baec72 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/package-info.java @@ -0,0 +1,2 @@ +@org.jspecify.annotations.NullMarked +package com.timr.api.apis; diff --git a/sdk/java-restclient/src/main/java/com/timr/api/auth/ApiKeyAuth.java b/sdk/java-restclient/src/main/java/com/timr/api/auth/ApiKeyAuth.java new file mode 100644 index 0000000..c62fc26 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/auth/ApiKeyAuth.java @@ -0,0 +1,75 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location.equals("query")) { + queryParams.add(paramName, value); + } else if (location.equals("header")) { + headerParams.add(paramName, value); + } else if (location.equals("cookie")) { + cookieParams.add(paramName, value); + } + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/auth/Authentication.java b/sdk/java-restclient/src/main/java/com/timr/api/auth/Authentication.java new file mode 100644 index 0000000..b453ce3 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/auth/Authentication.java @@ -0,0 +1,29 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public interface Authentication { + /** + * Apply authentication settings to header and / or query parameters. + * + * @param queryParams The query parameters for the request + * @param headerParams The header parameters for the request + * @param cookieParams The cookie parameters for the request + */ + void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams); +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/auth/HttpBasicAuth.java b/sdk/java-restclient/src/main/java/com/timr/api/auth/HttpBasicAuth.java new file mode 100644 index 0000000..cb4452f --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/auth/HttpBasicAuth.java @@ -0,0 +1,51 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/auth/HttpBearerAuth.java b/sdk/java-restclient/src/main/java/com/timr/api/auth/HttpBearerAuth.java new file mode 100644 index 0000000..3cd16f1 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/auth/HttpBearerAuth.java @@ -0,0 +1,69 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import java.util.Optional; +import java.util.function.Supplier; +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private Supplier tokenSupplier; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return tokenSupplier.get(); + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { + return; + } + headerParams.add(HttpHeaders.AUTHORIZATION, (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/auth/OAuth.java b/sdk/java-restclient/src/main/java/com/timr/api/auth/OAuth.java new file mode 100644 index 0000000..ef6ccf0 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/auth/OAuth.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import java.util.Optional; +import java.util.function.Supplier; +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +/** + * Provides support for RFC 6750 - Bearer Token usage for OAUTH 2.0 Authorization. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class OAuth implements Authentication { + private Supplier tokenSupplier; + + /** + * Returns the bearer token used for Authorization. + * + * @return The bearer token + */ + public String getAccessToken() { + return tokenSupplier.get(); + } + + /** + * Sets the bearer access token used for Authorization. + * + * @param accessToken The bearer token to send in the Authorization header + */ + public void setAccessToken(String accessToken) { + setAccessToken(() -> accessToken); + } + + /** + * Sets the supplier of bearer tokens used for Authorization. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setAccessToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + Optional.ofNullable(tokenSupplier).map(Supplier::get).ifPresent(accessToken -> + headerParams.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) + ); + } +} diff --git a/sdk/java-restclient/src/main/java/com/timr/api/auth/OAuthFlow.java b/sdk/java-restclient/src/main/java/com/timr/api/auth/OAuthFlow.java new file mode 100644 index 0000000..afcd5c1 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/auth/OAuthFlow.java @@ -0,0 +1,18 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Accounts.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Accounts.java new file mode 100644 index 0000000..214f569 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Accounts.java @@ -0,0 +1,234 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.OvertimeSurchargeAccounts; +import com.timr.api.models.TimeAccount; +import com.timr.api.models.VacationAccount; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Accounts + */ +@JsonPropertyOrder({ + Accounts.JSON_PROPERTY_LAST_BALANCE_DATE, + Accounts.JSON_PROPERTY_TIME_ACCOUNT, + Accounts.JSON_PROPERTY_OVERTIME_SURCHARGE_ACCOUNTS, + Accounts.JSON_PROPERTY_VACATION_ACCOUNT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Accounts { + public static final String JSON_PROPERTY_LAST_BALANCE_DATE = "last_balance_date"; + + private @Nullable LocalDate lastBalanceDate; + + public static final String JSON_PROPERTY_TIME_ACCOUNT = "time_account"; + + private JsonNullable<@Nullable TimeAccount> timeAccount = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_OVERTIME_SURCHARGE_ACCOUNTS = "overtime_surcharge_accounts"; + + private JsonNullable<@Nullable List> overtimeSurchargeAccounts = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_VACATION_ACCOUNT = "vacation_account"; + + private JsonNullable<@Nullable VacationAccount> vacationAccount = JsonNullable.undefined(); + + public Accounts() { + } + + public Accounts lastBalanceDate(@Nullable LocalDate lastBalanceDate) { + + this.lastBalanceDate = lastBalanceDate; + return this; + } + + /** + * date of last balance + * @return lastBalanceDate + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_BALANCE_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable LocalDate getLastBalanceDate() { + return lastBalanceDate; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_BALANCE_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastBalanceDate(@Nullable LocalDate lastBalanceDate) { + this.lastBalanceDate = lastBalanceDate; + } + + + public Accounts timeAccount(@Nullable TimeAccount timeAccount) { + this.timeAccount = JsonNullable.of(timeAccount); + + return this; + } + + /** + * Get timeAccount + * @return timeAccount + */ + + @JsonProperty(value = JSON_PROPERTY_TIME_ACCOUNT, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable TimeAccount> getTimeAccount() { + return timeAccount; + } + + @JsonProperty(JSON_PROPERTY_TIME_ACCOUNT) + public void setTimeAccount(JsonNullable timeAccount) { + this.timeAccount = timeAccount; + } + + + + public Accounts overtimeSurchargeAccounts(@Nullable List overtimeSurchargeAccounts) { + this.overtimeSurchargeAccounts = JsonNullable.>of(overtimeSurchargeAccounts); + + return this; + } + + public Accounts addOvertimeSurchargeAccountsItem(OvertimeSurchargeAccounts overtimeSurchargeAccountsItem) { + if (this.overtimeSurchargeAccounts == null || !this.overtimeSurchargeAccounts.isPresent()) { + this.overtimeSurchargeAccounts = JsonNullable.>of(new ArrayList<>()); + } + try { + this.overtimeSurchargeAccounts.get().add(overtimeSurchargeAccountsItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get overtimeSurchargeAccounts + * @return overtimeSurchargeAccounts + */ + + @JsonProperty(value = JSON_PROPERTY_OVERTIME_SURCHARGE_ACCOUNTS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable List> getOvertimeSurchargeAccounts() { + return overtimeSurchargeAccounts; + } + + @JsonProperty(JSON_PROPERTY_OVERTIME_SURCHARGE_ACCOUNTS) + public void setOvertimeSurchargeAccounts(JsonNullable> overtimeSurchargeAccounts) { + this.overtimeSurchargeAccounts = overtimeSurchargeAccounts; + } + + + + public Accounts vacationAccount(@Nullable VacationAccount vacationAccount) { + this.vacationAccount = JsonNullable.of(vacationAccount); + + return this; + } + + /** + * Get vacationAccount + * @return vacationAccount + */ + + @JsonProperty(value = JSON_PROPERTY_VACATION_ACCOUNT, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable VacationAccount> getVacationAccount() { + return vacationAccount; + } + + @JsonProperty(JSON_PROPERTY_VACATION_ACCOUNT) + public void setVacationAccount(JsonNullable vacationAccount) { + this.vacationAccount = vacationAccount; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Accounts accounts = (Accounts) o; + return Objects.equals(this.lastBalanceDate, accounts.lastBalanceDate) && + equalsNullable(this.timeAccount, accounts.timeAccount) && + equalsNullable(this.overtimeSurchargeAccounts, accounts.overtimeSurchargeAccounts) && + equalsNullable(this.vacationAccount, accounts.vacationAccount); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lastBalanceDate, hashCodeNullable(timeAccount), hashCodeNullable(overtimeSurchargeAccounts), hashCodeNullable(vacationAccount)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Accounts {\n"); + sb.append(" lastBalanceDate: ").append(toIndentedString(lastBalanceDate)).append("\n"); + sb.append(" timeAccount: ").append(toIndentedString(timeAccount)).append("\n"); + sb.append(" overtimeSurchargeAccounts: ").append(!overtimeSurchargeAccounts.isPresent() || overtimeSurchargeAccounts.get() == null ? "null" : overtimeSurchargeAccounts.get().size() + " entries").append("\n"); + sb.append(" vacationAccount: ").append(toIndentedString(vacationAccount)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTime.java b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTime.java new file mode 100644 index 0000000..c1e20c8 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTime.java @@ -0,0 +1,50 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeAutomatic; +import com.timr.api.models.BreakTimeManual; +import com.timr.api.models.BreakTimeOngoing; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@JsonIgnoreProperties( + value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the type to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = BreakTimeAutomatic.class, name = "automatic"), + @JsonSubTypes.Type(value = BreakTimeManual.class, name = "manual"), + @JsonSubTypes.Type(value = BreakTimeOngoing.class, name = "ongoing"), +}) + +public interface BreakTime { + public BreakTimeType getType(); +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeAutomatic.java b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeAutomatic.java new file mode 100644 index 0000000..83329e9 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeAutomatic.java @@ -0,0 +1,190 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeBase; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * BreakTimeAutomatic + */ +@JsonPropertyOrder({ + BreakTimeAutomatic.JSON_PROPERTY_DURATION_MINUTES, + BreakTimeAutomatic.JSON_PROPERTY_START, + BreakTimeAutomatic.JSON_PROPERTY_END +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class BreakTimeAutomatic extends BreakTimeBase implements BreakTime { + public static final String JSON_PROPERTY_DURATION_MINUTES = "duration_minutes"; + + private Integer durationMinutes; + + public static final String JSON_PROPERTY_START = "start"; + + private @Nullable OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + + private @Nullable OffsetDateTime end; + + public BreakTimeAutomatic() { + + } + + public BreakTimeAutomatic durationMinutes(Integer durationMinutes) { + + this.durationMinutes = durationMinutes; + return this; + } + + /** + * Duration of break in minutes + * @return durationMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getDurationMinutes() { + return durationMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDurationMinutes(Integer durationMinutes) { + this.durationMinutes = durationMinutes; + } + + + public BreakTimeAutomatic start(@Nullable OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@Nullable OffsetDateTime start) { + this.start = start; + } + + + public BreakTimeAutomatic end(@Nullable OffsetDateTime end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable OffsetDateTime getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@Nullable OffsetDateTime end) { + this.end = end; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BreakTimeAutomatic breakTimeAutomatic = (BreakTimeAutomatic) o; + return Objects.equals(this.durationMinutes, breakTimeAutomatic.durationMinutes) && + Objects.equals(this.start, breakTimeAutomatic.start) && + Objects.equals(this.end, breakTimeAutomatic.end) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(durationMinutes, start, end, super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BreakTimeAutomatic {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" durationMinutes: ").append(toIndentedString(durationMinutes)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeBase.java b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeBase.java new file mode 100644 index 0000000..81cc33b --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeBase.java @@ -0,0 +1,119 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeType; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Members shared by every kind of break time, including the discriminator. + */ +@JsonPropertyOrder({ + BreakTimeBase.JSON_PROPERTY_TYPE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class BreakTimeBase { + public static final String JSON_PROPERTY_TYPE = "type"; + + protected BreakTimeType type; + + public BreakTimeBase() { + } + + public BreakTimeBase type(BreakTimeType type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public BreakTimeType getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(BreakTimeType type) { + this.type = type; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BreakTimeBase breakTimeBase = (BreakTimeBase) o; + return Objects.equals(this.type, breakTimeBase.type); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BreakTimeBase {\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeManual.java b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeManual.java new file mode 100644 index 0000000..563fe5e --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeManual.java @@ -0,0 +1,190 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeBase; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * BreakTimeManual + */ +@JsonPropertyOrder({ + BreakTimeManual.JSON_PROPERTY_DURATION_MINUTES, + BreakTimeManual.JSON_PROPERTY_START, + BreakTimeManual.JSON_PROPERTY_END +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class BreakTimeManual extends BreakTimeBase implements BreakTime, BreakTimeUpdate { + public static final String JSON_PROPERTY_DURATION_MINUTES = "duration_minutes"; + + private Integer durationMinutes; + + public static final String JSON_PROPERTY_START = "start"; + + private JsonNullable<@Nullable OffsetDateTime> start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public BreakTimeManual() { + + } + + public BreakTimeManual durationMinutes(Integer durationMinutes) { + + this.durationMinutes = durationMinutes; + return this; + } + + /** + * Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. + * @return durationMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getDurationMinutes() { + return durationMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDurationMinutes(Integer durationMinutes) { + this.durationMinutes = durationMinutes; + } + + + public BreakTimeManual start(@Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public BreakTimeManual end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BreakTimeManual breakTimeManual = (BreakTimeManual) o; + return Objects.equals(this.durationMinutes, breakTimeManual.durationMinutes) && + equalsNullable(this.start, breakTimeManual.start) && + equalsNullable(this.end, breakTimeManual.end) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(durationMinutes, hashCodeNullable(start), hashCodeNullable(end), super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BreakTimeManual {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" durationMinutes: ").append(toIndentedString(durationMinutes)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeOngoing.java b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeOngoing.java new file mode 100644 index 0000000..998c08d --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeOngoing.java @@ -0,0 +1,124 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeBase; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * BreakTimeOngoing + */ +@JsonPropertyOrder({ + BreakTimeOngoing.JSON_PROPERTY_START +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class BreakTimeOngoing extends BreakTimeBase implements BreakTime, BreakTimeUpdate { + public static final String JSON_PROPERTY_START = "start"; + + private OffsetDateTime start; + + public BreakTimeOngoing() { + + } + + public BreakTimeOngoing start(OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(OffsetDateTime start) { + this.start = start; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BreakTimeOngoing breakTimeOngoing = (BreakTimeOngoing) o; + return Objects.equals(this.start, breakTimeOngoing.start) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BreakTimeOngoing {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeType.java b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeType.java new file mode 100644 index 0000000..301c5b6 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeType.java @@ -0,0 +1,63 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Kind of break. `manual` was entered by the user, `automatic` was deducted by timr, `ongoing` is a break that has started and not yet ended. + */ +public enum BreakTimeType { + + MANUAL("manual"), + + ONGOING("ongoing"), + + AUTOMATIC("automatic"); + + private String value; + + BreakTimeType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static BreakTimeType fromValue(String value) { + for (BreakTimeType b : BreakTimeType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeUpdate.java new file mode 100644 index 0000000..ccb56ca --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/BreakTimeUpdate.java @@ -0,0 +1,52 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeManual; +import com.timr.api.models.BreakTimeOngoing; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@JsonIgnoreProperties( + value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the type to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = BreakTimeManual.class, name = "manual"), + @JsonSubTypes.Type(value = BreakTimeOngoing.class, name = "ongoing"), +}) + +public interface BreakTimeUpdate { + public BreakTimeType getType(); +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/BudgetPlanningType.java b/sdk/java-restclient/src/main/java/com/timr/api/models/BudgetPlanningType.java new file mode 100644 index 0000000..e62c9c5 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/BudgetPlanningType.java @@ -0,0 +1,65 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set for the remaining two types all budget properties are supported + */ +public enum BudgetPlanningType { + + NONE("none"), + + TASK_HOURLY_RATE("task_hourly_rate"), + + USER_HOURLY_RATE("user_hourly_rate"), + + FIXED_PRICE("fixed_price"); + + private String value; + + BudgetPlanningType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static BudgetPlanningType fromValue(String value) { + for (BudgetPlanningType b : BudgetPlanningType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/BudgetPlanningTypeRequest.java b/sdk/java-restclient/src/main/java/com/timr/api/models/BudgetPlanningTypeRequest.java new file mode 100644 index 0000000..d5f28d4 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/BudgetPlanningTypeRequest.java @@ -0,0 +1,67 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set * inherited: budget settings are inherited from the parent task for the remaining two types all budget properties are supported + */ +public enum BudgetPlanningTypeRequest { + + NONE("none"), + + TASK_HOURLY_RATE("task_hourly_rate"), + + USER_HOURLY_RATE("user_hourly_rate"), + + FIXED_PRICE("fixed_price"), + + INHERITED("inherited"); + + private String value; + + BudgetPlanningTypeRequest(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static BudgetPlanningTypeRequest fromValue(String value) { + for (BudgetPlanningTypeRequest b : BudgetPlanningTypeRequest.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Car.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Car.java new file mode 100644 index 0000000..a5692ff --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Car.java @@ -0,0 +1,295 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A vehicle identified by `name` and license `plate`. `usable` says whether it can currently be selected. + */ +@JsonPropertyOrder({ + Car.JSON_PROPERTY_ID, + Car.JSON_PROPERTY_NAME, + Car.JSON_PROPERTY_PLATE, + Car.JSON_PROPERTY_EXTERNAL_ID, + Car.JSON_PROPERTY_USABLE, + Car.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Car { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_PLATE = "plate"; + + private String plate; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public static final String JSON_PROPERTY_USABLE = "usable"; + + private Boolean usable; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public Car() { + } + + public Car id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public Car name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public Car plate(String plate) { + + this.plate = plate; + return this; + } + + /** + * Get plate + * @return plate + */ + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getPlate() { + return plate; + } + + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPlate(String plate) { + this.plate = plate; + } + + + public Car externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + public Car usable(Boolean usable) { + + this.usable = usable; + return this; + } + + /** + * Get usable + * @return usable + */ + + @JsonProperty(value = JSON_PROPERTY_USABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getUsable() { + return usable; + } + + + @JsonProperty(value = JSON_PROPERTY_USABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUsable(Boolean usable) { + this.usable = usable; + } + + + public Car metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public Car putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Car car = (Car) o; + return Objects.equals(this.id, car.id) && + Objects.equals(this.name, car.name) && + Objects.equals(this.plate, car.plate) && + Objects.equals(this.externalId, car.externalId) && + Objects.equals(this.usable, car.usable) && + equalsNullable(this.metadata, car.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, plate, externalId, usable, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Car {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" usable: ").append(toIndentedString(usable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/CarCreate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/CarCreate.java new file mode 100644 index 0000000..4342b7b --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/CarCreate.java @@ -0,0 +1,258 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * CarCreate + */ +@JsonPropertyOrder({ + CarCreate.JSON_PROPERTY_NAME, + CarCreate.JSON_PROPERTY_PLATE, + CarCreate.JSON_PROPERTY_EXTERNAL_ID, + CarCreate.JSON_PROPERTY_USABLE, + CarCreate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class CarCreate { + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_PLATE = "plate"; + + private String plate; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private JsonNullable<@Nullable String> externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_USABLE = "usable"; + + private JsonNullable<@Nullable Boolean> usable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public CarCreate() { + } + + public CarCreate name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public CarCreate plate(String plate) { + + this.plate = plate; + return this; + } + + /** + * Get plate + * @return plate + */ + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getPlate() { + return plate; + } + + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPlate(String plate) { + this.plate = plate; + } + + + public CarCreate externalId(@Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public CarCreate usable(@Nullable Boolean usable) { + this.usable = JsonNullable.of(usable); + + return this; + } + + /** + * Get usable + * @return usable + */ + + @JsonProperty(value = JSON_PROPERTY_USABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getUsable() { + return usable; + } + + @JsonProperty(JSON_PROPERTY_USABLE) + public void setUsable(JsonNullable usable) { + this.usable = usable; + } + + + + public CarCreate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public CarCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CarCreate carCreate = (CarCreate) o; + return Objects.equals(this.name, carCreate.name) && + Objects.equals(this.plate, carCreate.plate) && + equalsNullable(this.externalId, carCreate.externalId) && + equalsNullable(this.usable, carCreate.usable) && + equalsNullable(this.metadata, carCreate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(name, plate, hashCodeNullable(externalId), hashCodeNullable(usable), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CarCreate {\n"); + sb.append(" usable: ").append(toIndentedString(usable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/CarPartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/CarPartial.java new file mode 100644 index 0000000..b97a3ed --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/CarPartial.java @@ -0,0 +1,214 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * CarPartial + */ +@JsonPropertyOrder({ + CarPartial.JSON_PROPERTY_ID, + CarPartial.JSON_PROPERTY_NAME, + CarPartial.JSON_PROPERTY_PLATE, + CarPartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class CarPartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_PLATE = "plate"; + + private String plate; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public CarPartial() { + } + + public CarPartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public CarPartial name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public CarPartial plate(String plate) { + + this.plate = plate; + return this; + } + + /** + * Get plate + * @return plate + */ + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getPlate() { + return plate; + } + + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPlate(String plate) { + this.plate = plate; + } + + + public CarPartial externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CarPartial carPartial = (CarPartial) o; + return Objects.equals(this.id, carPartial.id) && + Objects.equals(this.name, carPartial.name) && + Objects.equals(this.plate, carPartial.plate) && + Objects.equals(this.externalId, carPartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, plate, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CarPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/CarUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/CarUpdate.java new file mode 100644 index 0000000..cf58f7c --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/CarUpdate.java @@ -0,0 +1,254 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * CarUpdate + */ +@JsonPropertyOrder({ + CarUpdate.JSON_PROPERTY_NAME, + CarUpdate.JSON_PROPERTY_PLATE, + CarUpdate.JSON_PROPERTY_EXTERNAL_ID, + CarUpdate.JSON_PROPERTY_USABLE, + CarUpdate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class CarUpdate { + public static final String JSON_PROPERTY_NAME = "name"; + + private JsonNullable<@Nullable String> name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PLATE = "plate"; + + private JsonNullable<@Nullable String> plate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private JsonNullable<@Nullable String> externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_USABLE = "usable"; + + private JsonNullable<@Nullable Boolean> usable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public CarUpdate() { + } + + public CarUpdate name(@Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public CarUpdate plate(@Nullable String plate) { + this.plate = JsonNullable.of(plate); + + return this; + } + + /** + * Get plate + * @return plate + */ + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getPlate() { + return plate; + } + + @JsonProperty(JSON_PROPERTY_PLATE) + public void setPlate(JsonNullable plate) { + this.plate = plate; + } + + + + public CarUpdate externalId(@Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public CarUpdate usable(@Nullable Boolean usable) { + this.usable = JsonNullable.of(usable); + + return this; + } + + /** + * Get usable + * @return usable + */ + + @JsonProperty(value = JSON_PROPERTY_USABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getUsable() { + return usable; + } + + @JsonProperty(JSON_PROPERTY_USABLE) + public void setUsable(JsonNullable usable) { + this.usable = usable; + } + + + + public CarUpdate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public CarUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CarUpdate carUpdate = (CarUpdate) o; + return equalsNullable(this.name, carUpdate.name) && + equalsNullable(this.plate, carUpdate.plate) && + equalsNullable(this.externalId, carUpdate.externalId) && + equalsNullable(this.usable, carUpdate.usable) && + equalsNullable(this.metadata, carUpdate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(name), hashCodeNullable(plate), hashCodeNullable(externalId), hashCodeNullable(usable), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CarUpdate {\n"); + sb.append(" usable: ").append(toIndentedString(usable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/CarsPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/CarsPage.java new file mode 100644 index 0000000..0029bd8 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/CarsPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.Car; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * CarsPage + */ +@JsonPropertyOrder({ + CarsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + CarsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class CarsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public CarsPage() { + } + + public CarsPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public CarsPage data(List data) { + + this.data = data; + return this; + } + + public CarsPage addDataItem(Car dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CarsPage carsPage = (CarsPage) o; + return Objects.equals(this.nextPageToken, carsPage.nextPageToken) && + Objects.equals(this.data, carsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CarsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/CarsSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/CarsSortColumn.java new file mode 100644 index 0000000..1b2c6f4 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/CarsSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Cars. + */ +public enum CarsSortColumn { + + NAME("name"); + + private String value; + + CarsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static CarsSortColumn fromValue(String value) { + for (CarsSortColumn b : CarsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DailyWorkSchedule.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DailyWorkSchedule.java new file mode 100644 index 0000000..6019a1a --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DailyWorkSchedule.java @@ -0,0 +1,164 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.NormalWorkingTimes; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DailyWorkSchedule + */ +@JsonPropertyOrder({ + DailyWorkSchedule.JSON_PROPERTY_TARGET_DURATION_MINUTES, + DailyWorkSchedule.JSON_PROPERTY_NORMAL_WORKING_TIMES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DailyWorkSchedule { + public static final String JSON_PROPERTY_TARGET_DURATION_MINUTES = "target_duration_minutes"; + + private Long targetDurationMinutes; + + public static final String JSON_PROPERTY_NORMAL_WORKING_TIMES = "normal_working_times"; + + private JsonNullable<@Nullable List> normalWorkingTimes = JsonNullable.>undefined(); + + public DailyWorkSchedule() { + } + + public DailyWorkSchedule targetDurationMinutes(Long targetDurationMinutes) { + + this.targetDurationMinutes = targetDurationMinutes; + return this; + } + + /** + * value in minutes + * @return targetDurationMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_TARGET_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getTargetDurationMinutes() { + return targetDurationMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_TARGET_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTargetDurationMinutes(Long targetDurationMinutes) { + this.targetDurationMinutes = targetDurationMinutes; + } + + + public DailyWorkSchedule normalWorkingTimes(@Nullable List normalWorkingTimes) { + this.normalWorkingTimes = JsonNullable.>of(normalWorkingTimes); + + return this; + } + + public DailyWorkSchedule addNormalWorkingTimesItem(NormalWorkingTimes normalWorkingTimesItem) { + if (this.normalWorkingTimes == null || !this.normalWorkingTimes.isPresent()) { + this.normalWorkingTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.normalWorkingTimes.get().add(normalWorkingTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set + * @return normalWorkingTimes + */ + + @JsonProperty(value = JSON_PROPERTY_NORMAL_WORKING_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable List> getNormalWorkingTimes() { + return normalWorkingTimes; + } + + @JsonProperty(JSON_PROPERTY_NORMAL_WORKING_TIMES) + public void setNormalWorkingTimes(JsonNullable> normalWorkingTimes) { + this.normalWorkingTimes = normalWorkingTimes; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DailyWorkSchedule dailyWorkSchedule = (DailyWorkSchedule) o; + return Objects.equals(this.targetDurationMinutes, dailyWorkSchedule.targetDurationMinutes) && + equalsNullable(this.normalWorkingTimes, dailyWorkSchedule.normalWorkingTimes); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(targetDurationMinutes, hashCodeNullable(normalWorkingTimes)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DailyWorkSchedule {\n"); + sb.append(" normalWorkingTimes: ").append(toIndentedString(normalWorkingTimes)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryPage.java new file mode 100644 index 0000000..47517a0 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DeletedEntryPartial; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DeletedEntryPage + */ +@JsonPropertyOrder({ + DeletedEntryPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + DeletedEntryPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DeletedEntryPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public DeletedEntryPage() { + } + + public DeletedEntryPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public DeletedEntryPage data(List data) { + + this.data = data; + return this; + } + + public DeletedEntryPage addDataItem(DeletedEntryPartial dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeletedEntryPage deletedEntryPage = (DeletedEntryPage) o; + return Objects.equals(this.nextPageToken, deletedEntryPage.nextPageToken) && + Objects.equals(this.data, deletedEntryPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeletedEntryPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryPartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryPartial.java new file mode 100644 index 0000000..7ba03fc --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryPartial.java @@ -0,0 +1,186 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DeletedEntryPartial + */ +@JsonPropertyOrder({ + DeletedEntryPartial.JSON_PROPERTY_ID, + DeletedEntryPartial.JSON_PROPERTY_LAST_MODIFIED, + DeletedEntryPartial.JSON_PROPERTY_LAST_MODIFIED_BY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DeletedEntryPartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + + private @Nullable UserPartial lastModifiedBy; + + public DeletedEntryPartial() { + } + + public DeletedEntryPartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public DeletedEntryPartial lastModified(OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public DeletedEntryPartial lastModifiedBy(@Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeletedEntryPartial deletedEntryPartial = (DeletedEntryPartial) o; + return Objects.equals(this.id, deletedEntryPartial.id) && + Objects.equals(this.lastModified, deletedEntryPartial.lastModified) && + Objects.equals(this.lastModifiedBy, deletedEntryPartial.lastModifiedBy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, lastModified, lastModifiedBy); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeletedEntryPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" lastModified: ").append(toIndentedString(lastModified)).append("\n"); + sb.append(" lastModifiedBy: ").append(toIndentedString(lastModifiedBy)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntrySortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntrySortColumn.java new file mode 100644 index 0000000..1e1400c --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntrySortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for deleted entries. + */ +public enum DeletedEntrySortColumn { + + LAST_MODIFIED("last_modified"); + + private String value; + + DeletedEntrySortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DeletedEntrySortColumn fromValue(String value) { + for (DeletedEntrySortColumn b : DeletedEntrySortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryWithMetadata.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryWithMetadata.java new file mode 100644 index 0000000..2a6b34e --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryWithMetadata.java @@ -0,0 +1,234 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DeletedEntryWithMetadata + */ +@JsonPropertyOrder({ + DeletedEntryWithMetadata.JSON_PROPERTY_ID, + DeletedEntryWithMetadata.JSON_PROPERTY_LAST_MODIFIED, + DeletedEntryWithMetadata.JSON_PROPERTY_LAST_MODIFIED_BY, + DeletedEntryWithMetadata.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DeletedEntryWithMetadata { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + + private @Nullable UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public DeletedEntryWithMetadata() { + } + + public DeletedEntryWithMetadata id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public DeletedEntryWithMetadata lastModified(OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public DeletedEntryWithMetadata lastModifiedBy(@Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public DeletedEntryWithMetadata metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DeletedEntryWithMetadata putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeletedEntryWithMetadata deletedEntryWithMetadata = (DeletedEntryWithMetadata) o; + return Objects.equals(this.id, deletedEntryWithMetadata.id) && + Objects.equals(this.lastModified, deletedEntryWithMetadata.lastModified) && + Objects.equals(this.lastModifiedBy, deletedEntryWithMetadata.lastModifiedBy) && + equalsNullable(this.metadata, deletedEntryWithMetadata.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, lastModified, lastModifiedBy, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeletedEntryWithMetadata {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" lastModified: ").append(toIndentedString(lastModified)).append("\n"); + sb.append(" lastModifiedBy: ").append(toIndentedString(lastModifiedBy)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryWithMetadataPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryWithMetadataPage.java new file mode 100644 index 0000000..2a22721 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DeletedEntryWithMetadataPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DeletedEntryWithMetadata; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DeletedEntryWithMetadataPage + */ +@JsonPropertyOrder({ + DeletedEntryWithMetadataPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + DeletedEntryWithMetadataPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DeletedEntryWithMetadataPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public DeletedEntryWithMetadataPage() { + } + + public DeletedEntryWithMetadataPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public DeletedEntryWithMetadataPage data(List data) { + + this.data = data; + return this; + } + + public DeletedEntryWithMetadataPage addDataItem(DeletedEntryWithMetadata dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeletedEntryWithMetadataPage deletedEntryWithMetadataPage = (DeletedEntryWithMetadataPage) o; + return Objects.equals(this.nextPageToken, deletedEntryWithMetadataPage.nextPageToken) && + Objects.equals(this.data, deletedEntryWithMetadataPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeletedEntryWithMetadataPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLog.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLog.java new file mode 100644 index 0000000..88bf390 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLog.java @@ -0,0 +1,922 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.CarPartial; +import com.timr.api.models.DriveLogCategoryPartial; +import com.timr.api.models.DriveLogStatus; +import com.timr.api.models.Duration; +import com.timr.api.models.Location; +import com.timr.api.models.Platform; +import com.timr.api.models.UserPartial; +import com.timr.api.models.VenuePartial; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * One trip in a `car`: `start` and `end`, `start_mileage` and `end_mileage` with the resulting `distance`, the `purpose`, the places `visited`, and its `drive_log_category`. May include a recorded GPS `route`. + */ +@JsonPropertyOrder({ + DriveLog.JSON_PROPERTY_ID, + DriveLog.JSON_PROPERTY_START, + DriveLog.JSON_PROPERTY_END, + DriveLog.JSON_PROPERTY_DURATION, + DriveLog.JSON_PROPERTY_CHANGED, + DriveLog.JSON_PROPERTY_START_MILEAGE, + DriveLog.JSON_PROPERTY_END_MILEAGE, + DriveLog.JSON_PROPERTY_DISTANCE, + DriveLog.JSON_PROPERTY_ROUTE, + DriveLog.JSON_PROPERTY_PURPOSE, + DriveLog.JSON_PROPERTY_VISITED, + DriveLog.JSON_PROPERTY_USER, + DriveLog.JSON_PROPERTY_CAR, + DriveLog.JSON_PROPERTY_DRIVE_LOG_CATEGORY, + DriveLog.JSON_PROPERTY_START_VENUE, + DriveLog.JSON_PROPERTY_END_VENUE, + DriveLog.JSON_PROPERTY_HAS_TRACK, + DriveLog.JSON_PROPERTY_START_LOCATION, + DriveLog.JSON_PROPERTY_END_LOCATION, + DriveLog.JSON_PROPERTY_START_PLATFORM, + DriveLog.JSON_PROPERTY_END_PLATFORM, + DriveLog.JSON_PROPERTY_LAST_MODIFIED, + DriveLog.JSON_PROPERTY_LAST_MODIFIED_BY, + DriveLog.JSON_PROPERTY_STATUS, + DriveLog.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLog { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_START = "start"; + + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + + private @Nullable OffsetDateTime end; + + public static final String JSON_PROPERTY_DURATION = "duration"; + + private @Nullable Duration duration; + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private Boolean changed; + + public static final String JSON_PROPERTY_START_MILEAGE = "start_mileage"; + + private Long startMileage; + + public static final String JSON_PROPERTY_END_MILEAGE = "end_mileage"; + + private @Nullable Long endMileage; + + public static final String JSON_PROPERTY_DISTANCE = "distance"; + + private @Nullable Long distance; + + public static final String JSON_PROPERTY_ROUTE = "route"; + + private @Nullable String route; + + public static final String JSON_PROPERTY_PURPOSE = "purpose"; + + private @Nullable String purpose; + + public static final String JSON_PROPERTY_VISITED = "visited"; + + private @Nullable String visited; + + public static final String JSON_PROPERTY_USER = "user"; + + private UserPartial user; + + public static final String JSON_PROPERTY_CAR = "car"; + + private CarPartial car; + + public static final String JSON_PROPERTY_DRIVE_LOG_CATEGORY = "drive_log_category"; + + private DriveLogCategoryPartial driveLogCategory; + + public static final String JSON_PROPERTY_START_VENUE = "start_venue"; + + private @Nullable VenuePartial startVenue; + + public static final String JSON_PROPERTY_END_VENUE = "end_venue"; + + private @Nullable VenuePartial endVenue; + + public static final String JSON_PROPERTY_HAS_TRACK = "has_track"; + + private Boolean hasTrack; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + + private @Nullable Location startLocation; + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + + private @Nullable Location endLocation; + + public static final String JSON_PROPERTY_START_PLATFORM = "start_platform"; + + private @Nullable Platform startPlatform; + + public static final String JSON_PROPERTY_END_PLATFORM = "end_platform"; + + private @Nullable Platform endPlatform; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + + private @Nullable UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_STATUS = "status"; + + private DriveLogStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public DriveLog() { + } + + public DriveLog id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public DriveLog start(OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(OffsetDateTime start) { + this.start = start; + } + + + public DriveLog end(@Nullable OffsetDateTime end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable OffsetDateTime getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@Nullable OffsetDateTime end) { + this.end = end; + } + + + public DriveLog duration(@Nullable Duration duration) { + + this.duration = duration; + return this; + } + + /** + * Get duration + * @return duration + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Duration getDuration() { + return duration; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDuration(@Nullable Duration duration) { + this.duration = duration; + } + + + public DriveLog changed(Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(Boolean changed) { + this.changed = changed; + } + + + public DriveLog startMileage(Long startMileage) { + + this.startMileage = startMileage; + return this; + } + + /** + * Get startMileage + * @return startMileage + */ + + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getStartMileage() { + return startMileage; + } + + + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartMileage(Long startMileage) { + this.startMileage = startMileage; + } + + + public DriveLog endMileage(@Nullable Long endMileage) { + + this.endMileage = endMileage; + return this; + } + + /** + * Get endMileage + * @return endMileage + */ + + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Long getEndMileage() { + return endMileage; + } + + + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndMileage(@Nullable Long endMileage) { + this.endMileage = endMileage; + } + + + public DriveLog distance(@Nullable Long distance) { + + this.distance = distance; + return this; + } + + /** + * Driven distance in kilometers + * @return distance + */ + + @JsonProperty(value = JSON_PROPERTY_DISTANCE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Long getDistance() { + return distance; + } + + + @JsonProperty(value = JSON_PROPERTY_DISTANCE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDistance(@Nullable Long distance) { + this.distance = distance; + } + + + public DriveLog route(@Nullable String route) { + + this.route = route; + return this; + } + + /** + * Get route + * @return route + */ + + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getRoute() { + return route; + } + + + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRoute(@Nullable String route) { + this.route = route; + } + + + public DriveLog purpose(@Nullable String purpose) { + + this.purpose = purpose; + return this; + } + + /** + * Get purpose + * @return purpose + */ + + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getPurpose() { + return purpose; + } + + + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPurpose(@Nullable String purpose) { + this.purpose = purpose; + } + + + public DriveLog visited(@Nullable String visited) { + + this.visited = visited; + return this; + } + + /** + * Get visited + * @return visited + */ + + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getVisited() { + return visited; + } + + + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setVisited(@Nullable String visited) { + this.visited = visited; + } + + + public DriveLog user(UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(UserPartial user) { + this.user = user; + } + + + public DriveLog car(CarPartial car) { + + this.car = car; + return this; + } + + /** + * Get car + * @return car + */ + + @JsonProperty(value = JSON_PROPERTY_CAR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public CarPartial getCar() { + return car; + } + + + @JsonProperty(value = JSON_PROPERTY_CAR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCar(CarPartial car) { + this.car = car; + } + + + public DriveLog driveLogCategory(DriveLogCategoryPartial driveLogCategory) { + + this.driveLogCategory = driveLogCategory; + return this; + } + + /** + * Get driveLogCategory + * @return driveLogCategory + */ + + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DriveLogCategoryPartial getDriveLogCategory() { + return driveLogCategory; + } + + + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDriveLogCategory(DriveLogCategoryPartial driveLogCategory) { + this.driveLogCategory = driveLogCategory; + } + + + public DriveLog startVenue(@Nullable VenuePartial startVenue) { + + this.startVenue = startVenue; + return this; + } + + /** + * Get startVenue + * @return startVenue + */ + + @JsonProperty(value = JSON_PROPERTY_START_VENUE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable VenuePartial getStartVenue() { + return startVenue; + } + + + @JsonProperty(value = JSON_PROPERTY_START_VENUE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartVenue(@Nullable VenuePartial startVenue) { + this.startVenue = startVenue; + } + + + public DriveLog endVenue(@Nullable VenuePartial endVenue) { + + this.endVenue = endVenue; + return this; + } + + /** + * Get endVenue + * @return endVenue + */ + + @JsonProperty(value = JSON_PROPERTY_END_VENUE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable VenuePartial getEndVenue() { + return endVenue; + } + + + @JsonProperty(value = JSON_PROPERTY_END_VENUE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndVenue(@Nullable VenuePartial endVenue) { + this.endVenue = endVenue; + } + + + public DriveLog hasTrack(Boolean hasTrack) { + + this.hasTrack = hasTrack; + return this; + } + + /** + * Get hasTrack + * @return hasTrack + */ + + @JsonProperty(value = JSON_PROPERTY_HAS_TRACK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getHasTrack() { + return hasTrack; + } + + + @JsonProperty(value = JSON_PROPERTY_HAS_TRACK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setHasTrack(Boolean hasTrack) { + this.hasTrack = hasTrack; + } + + + public DriveLog startLocation(@Nullable Location startLocation) { + + this.startLocation = startLocation; + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Location getStartLocation() { + return startLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartLocation(@Nullable Location startLocation) { + this.startLocation = startLocation; + } + + + public DriveLog endLocation(@Nullable Location endLocation) { + + this.endLocation = endLocation; + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Location getEndLocation() { + return endLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndLocation(@Nullable Location endLocation) { + this.endLocation = endLocation; + } + + + public DriveLog startPlatform(@Nullable Platform startPlatform) { + + this.startPlatform = startPlatform; + return this; + } + + /** + * Get startPlatform + * @return startPlatform + */ + + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Platform getStartPlatform() { + return startPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartPlatform(@Nullable Platform startPlatform) { + this.startPlatform = startPlatform; + } + + + public DriveLog endPlatform(@Nullable Platform endPlatform) { + + this.endPlatform = endPlatform; + return this; + } + + /** + * Get endPlatform + * @return endPlatform + */ + + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Platform getEndPlatform() { + return endPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndPlatform(@Nullable Platform endPlatform) { + this.endPlatform = endPlatform; + } + + + public DriveLog lastModified(OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public DriveLog lastModifiedBy(@Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public DriveLog status(DriveLogStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DriveLogStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(DriveLogStatus status) { + this.status = status; + } + + + public DriveLog metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DriveLog putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLog driveLog = (DriveLog) o; + return Objects.equals(this.id, driveLog.id) && + Objects.equals(this.start, driveLog.start) && + Objects.equals(this.end, driveLog.end) && + Objects.equals(this.duration, driveLog.duration) && + Objects.equals(this.changed, driveLog.changed) && + Objects.equals(this.startMileage, driveLog.startMileage) && + Objects.equals(this.endMileage, driveLog.endMileage) && + Objects.equals(this.distance, driveLog.distance) && + Objects.equals(this.route, driveLog.route) && + Objects.equals(this.purpose, driveLog.purpose) && + Objects.equals(this.visited, driveLog.visited) && + Objects.equals(this.user, driveLog.user) && + Objects.equals(this.car, driveLog.car) && + Objects.equals(this.driveLogCategory, driveLog.driveLogCategory) && + Objects.equals(this.startVenue, driveLog.startVenue) && + Objects.equals(this.endVenue, driveLog.endVenue) && + Objects.equals(this.hasTrack, driveLog.hasTrack) && + Objects.equals(this.startLocation, driveLog.startLocation) && + Objects.equals(this.endLocation, driveLog.endLocation) && + Objects.equals(this.startPlatform, driveLog.startPlatform) && + Objects.equals(this.endPlatform, driveLog.endPlatform) && + Objects.equals(this.lastModified, driveLog.lastModified) && + Objects.equals(this.lastModifiedBy, driveLog.lastModifiedBy) && + Objects.equals(this.status, driveLog.status) && + equalsNullable(this.metadata, driveLog.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, start, end, duration, changed, startMileage, endMileage, distance, route, purpose, visited, user, car, driveLogCategory, startVenue, endVenue, hasTrack, startLocation, endLocation, startPlatform, endPlatform, lastModified, lastModifiedBy, status, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLog {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" startMileage: ").append(toIndentedString(startMileage)).append("\n"); + sb.append(" endMileage: ").append(toIndentedString(endMileage)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" car: ").append(toIndentedString(car)).append("\n"); + sb.append(" driveLogCategory: ").append(toIndentedString(driveLogCategory)).append("\n"); + sb.append(" startVenue: ").append(toIndentedString(startVenue)).append("\n"); + sb.append(" endVenue: ").append(toIndentedString(endVenue)).append("\n"); + sb.append(" hasTrack: ").append(toIndentedString(hasTrack)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategoriesPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategoriesPage.java new file mode 100644 index 0000000..cdac283 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategoriesPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLogCategory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogCategoriesPage + */ +@JsonPropertyOrder({ + DriveLogCategoriesPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + DriveLogCategoriesPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogCategoriesPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public DriveLogCategoriesPage() { + } + + public DriveLogCategoriesPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public DriveLogCategoriesPage data(List data) { + + this.data = data; + return this; + } + + public DriveLogCategoriesPage addDataItem(DriveLogCategory dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogCategoriesPage driveLogCategoriesPage = (DriveLogCategoriesPage) o; + return Objects.equals(this.nextPageToken, driveLogCategoriesPage.nextPageToken) && + Objects.equals(this.data, driveLogCategoriesPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogCategoriesPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategoriesSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategoriesSortColumn.java new file mode 100644 index 0000000..173120d --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategoriesSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Drive Log Categories. + */ +public enum DriveLogCategoriesSortColumn { + + NAME("name"); + + private String value; + + DriveLogCategoriesSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DriveLogCategoriesSortColumn fromValue(String value) { + for (DriveLogCategoriesSortColumn b : DriveLogCategoriesSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategory.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategory.java new file mode 100644 index 0000000..b3008fc --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategory.java @@ -0,0 +1,281 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A drive log category with a `name` and a display `color`; `business` marks it as business travel. + */ +@JsonPropertyOrder({ + DriveLogCategory.JSON_PROPERTY_ID, + DriveLogCategory.JSON_PROPERTY_NAME, + DriveLogCategory.JSON_PROPERTY_BUSINESS, + DriveLogCategory.JSON_PROPERTY_COLOR, + DriveLogCategory.JSON_PROPERTY_LAST_MODIFIED, + DriveLogCategory.JSON_PROPERTY_LAST_MODIFIED_BY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogCategory { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_BUSINESS = "business"; + + private Boolean business; + + public static final String JSON_PROPERTY_COLOR = "color"; + + private String color; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + + private @Nullable UserPartial lastModifiedBy; + + public DriveLogCategory() { + } + + public DriveLogCategory id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public DriveLogCategory name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public DriveLogCategory business(Boolean business) { + + this.business = business; + return this; + } + + /** + * Get business + * @return business + */ + + @JsonProperty(value = JSON_PROPERTY_BUSINESS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBusiness() { + return business; + } + + + @JsonProperty(value = JSON_PROPERTY_BUSINESS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBusiness(Boolean business) { + this.business = business; + } + + + public DriveLogCategory color(String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + */ + + @JsonProperty(value = JSON_PROPERTY_COLOR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getColor() { + return color; + } + + + @JsonProperty(value = JSON_PROPERTY_COLOR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setColor(String color) { + this.color = color; + } + + + public DriveLogCategory lastModified(OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public DriveLogCategory lastModifiedBy(@Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogCategory driveLogCategory = (DriveLogCategory) o; + return Objects.equals(this.id, driveLogCategory.id) && + Objects.equals(this.name, driveLogCategory.name) && + Objects.equals(this.business, driveLogCategory.business) && + Objects.equals(this.color, driveLogCategory.color) && + Objects.equals(this.lastModified, driveLogCategory.lastModified) && + Objects.equals(this.lastModifiedBy, driveLogCategory.lastModifiedBy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, business, color, lastModified, lastModifiedBy); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogCategory {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" business: ").append(toIndentedString(business)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategoryPartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategoryPartial.java new file mode 100644 index 0000000..89a1026 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCategoryPartial.java @@ -0,0 +1,215 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogCategoryPartial + */ +@JsonPropertyOrder({ + DriveLogCategoryPartial.JSON_PROPERTY_ID, + DriveLogCategoryPartial.JSON_PROPERTY_NAME, + DriveLogCategoryPartial.JSON_PROPERTY_BUSINESS, + DriveLogCategoryPartial.JSON_PROPERTY_COLOR +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogCategoryPartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_BUSINESS = "business"; + + private Boolean business; + + public static final String JSON_PROPERTY_COLOR = "color"; + + private String color; + + public DriveLogCategoryPartial() { + } + + public DriveLogCategoryPartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public DriveLogCategoryPartial name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public DriveLogCategoryPartial business(Boolean business) { + + this.business = business; + return this; + } + + /** + * Get business + * @return business + */ + + @JsonProperty(value = JSON_PROPERTY_BUSINESS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBusiness() { + return business; + } + + + @JsonProperty(value = JSON_PROPERTY_BUSINESS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBusiness(Boolean business) { + this.business = business; + } + + + public DriveLogCategoryPartial color(String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + */ + + @JsonProperty(value = JSON_PROPERTY_COLOR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getColor() { + return color; + } + + + @JsonProperty(value = JSON_PROPERTY_COLOR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setColor(String color) { + this.color = color; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogCategoryPartial driveLogCategoryPartial = (DriveLogCategoryPartial) o; + return Objects.equals(this.id, driveLogCategoryPartial.id) && + Objects.equals(this.name, driveLogCategoryPartial.name) && + Objects.equals(this.business, driveLogCategoryPartial.business) && + Objects.equals(this.color, driveLogCategoryPartial.color); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, business, color); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogCategoryPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" business: ").append(toIndentedString(business)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCreate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCreate.java new file mode 100644 index 0000000..af3247e --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogCreate.java @@ -0,0 +1,576 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLogStatus; +import com.timr.api.models.LocationCreate; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogCreate + */ +@JsonPropertyOrder({ + DriveLogCreate.JSON_PROPERTY_START, + DriveLogCreate.JSON_PROPERTY_END, + DriveLogCreate.JSON_PROPERTY_CHANGED, + DriveLogCreate.JSON_PROPERTY_START_MILEAGE, + DriveLogCreate.JSON_PROPERTY_END_MILEAGE, + DriveLogCreate.JSON_PROPERTY_ROUTE, + DriveLogCreate.JSON_PROPERTY_PURPOSE, + DriveLogCreate.JSON_PROPERTY_VISITED, + DriveLogCreate.JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, + DriveLogCreate.JSON_PROPERTY_STATUS, + DriveLogCreate.JSON_PROPERTY_METADATA, + DriveLogCreate.JSON_PROPERTY_USER_ID, + DriveLogCreate.JSON_PROPERTY_CAR_ID, + DriveLogCreate.JSON_PROPERTY_START_LOCATION, + DriveLogCreate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogCreate { + public static final String JSON_PROPERTY_START = "start"; + + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private Boolean changed; + + public static final String JSON_PROPERTY_START_MILEAGE = "start_mileage"; + + private Long startMileage; + + public static final String JSON_PROPERTY_END_MILEAGE = "end_mileage"; + + private JsonNullable<@Nullable Long> endMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ROUTE = "route"; + + private JsonNullable<@Nullable String> route = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PURPOSE = "purpose"; + + private JsonNullable<@Nullable String> purpose = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_VISITED = "visited"; + + private JsonNullable<@Nullable String> visited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID = "drive_log_category_id"; + + private String driveLogCategoryId; + + public static final String JSON_PROPERTY_STATUS = "status"; + + private DriveLogStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_USER_ID = "user_id"; + + private String userId; + + public static final String JSON_PROPERTY_CAR_ID = "car_id"; + + private String carId; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + + private JsonNullable<@Nullable LocationCreate> startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + + private JsonNullable<@Nullable LocationCreate> endLocation = JsonNullable.undefined(); + + public DriveLogCreate() { + } + + public DriveLogCreate start(OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(OffsetDateTime start) { + this.start = start; + } + + + public DriveLogCreate end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public DriveLogCreate changed(Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(Boolean changed) { + this.changed = changed; + } + + + public DriveLogCreate startMileage(Long startMileage) { + + this.startMileage = startMileage; + return this; + } + + /** + * Get startMileage + * @return startMileage + */ + + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getStartMileage() { + return startMileage; + } + + + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartMileage(Long startMileage) { + this.startMileage = startMileage; + } + + + public DriveLogCreate endMileage(@Nullable Long endMileage) { + this.endMileage = JsonNullable.of(endMileage); + + return this; + } + + /** + * Get endMileage + * @return endMileage + */ + + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Long> getEndMileage() { + return endMileage; + } + + @JsonProperty(JSON_PROPERTY_END_MILEAGE) + public void setEndMileage(JsonNullable endMileage) { + this.endMileage = endMileage; + } + + + + public DriveLogCreate route(@Nullable String route) { + this.route = JsonNullable.of(route); + + return this; + } + + /** + * Get route + * @return route + */ + + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getRoute() { + return route; + } + + @JsonProperty(JSON_PROPERTY_ROUTE) + public void setRoute(JsonNullable route) { + this.route = route; + } + + + + public DriveLogCreate purpose(@Nullable String purpose) { + this.purpose = JsonNullable.of(purpose); + + return this; + } + + /** + * Get purpose + * @return purpose + */ + + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getPurpose() { + return purpose; + } + + @JsonProperty(JSON_PROPERTY_PURPOSE) + public void setPurpose(JsonNullable purpose) { + this.purpose = purpose; + } + + + + public DriveLogCreate visited(@Nullable String visited) { + this.visited = JsonNullable.of(visited); + + return this; + } + + /** + * Get visited + * @return visited + */ + + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getVisited() { + return visited; + } + + @JsonProperty(JSON_PROPERTY_VISITED) + public void setVisited(JsonNullable visited) { + this.visited = visited; + } + + + + public DriveLogCreate driveLogCategoryId(String driveLogCategoryId) { + + this.driveLogCategoryId = driveLogCategoryId; + return this; + } + + /** + * Get driveLogCategoryId + * @return driveLogCategoryId + */ + + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDriveLogCategoryId() { + return driveLogCategoryId; + } + + + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDriveLogCategoryId(String driveLogCategoryId) { + this.driveLogCategoryId = driveLogCategoryId; + } + + + public DriveLogCreate status(DriveLogStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DriveLogStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(DriveLogStatus status) { + this.status = status; + } + + + public DriveLogCreate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DriveLogCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public DriveLogCreate userId(String userId) { + + this.userId = userId; + return this; + } + + /** + * Get userId + * @return userId + */ + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getUserId() { + return userId; + } + + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUserId(String userId) { + this.userId = userId; + } + + + public DriveLogCreate carId(String carId) { + + this.carId = carId; + return this; + } + + /** + * Get carId + * @return carId + */ + + @JsonProperty(value = JSON_PROPERTY_CAR_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCarId() { + return carId; + } + + + @JsonProperty(value = JSON_PROPERTY_CAR_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCarId(String carId) { + this.carId = carId; + } + + + public DriveLogCreate startLocation(@Nullable LocationCreate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationCreate> getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public DriveLogCreate endLocation(@Nullable LocationCreate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationCreate> getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogCreate driveLogCreate = (DriveLogCreate) o; + return Objects.equals(this.start, driveLogCreate.start) && + equalsNullable(this.end, driveLogCreate.end) && + Objects.equals(this.changed, driveLogCreate.changed) && + Objects.equals(this.startMileage, driveLogCreate.startMileage) && + equalsNullable(this.endMileage, driveLogCreate.endMileage) && + equalsNullable(this.route, driveLogCreate.route) && + equalsNullable(this.purpose, driveLogCreate.purpose) && + equalsNullable(this.visited, driveLogCreate.visited) && + Objects.equals(this.driveLogCategoryId, driveLogCreate.driveLogCategoryId) && + Objects.equals(this.status, driveLogCreate.status) && + equalsNullable(this.metadata, driveLogCreate.metadata) && + Objects.equals(this.userId, driveLogCreate.userId) && + Objects.equals(this.carId, driveLogCreate.carId) && + equalsNullable(this.startLocation, driveLogCreate.startLocation) && + equalsNullable(this.endLocation, driveLogCreate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, hashCodeNullable(end), changed, startMileage, hashCodeNullable(endMileage), hashCodeNullable(route), hashCodeNullable(purpose), hashCodeNullable(visited), driveLogCategoryId, status, hashCodeNullable(metadata), userId, carId, hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogCreate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" driveLogCategoryId: ").append(toIndentedString(driveLogCategoryId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); + sb.append(" carId: ").append(toIndentedString(carId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogStatus.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogStatus.java new file mode 100644 index 0000000..b8e00da --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogStatus.java @@ -0,0 +1,71 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Processing state of a Drive Log. `running` means the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + */ +public enum DriveLogStatus { + + CHANGEABLE("changeable"), + + LOCKED("locked"), + + APPROVED("approved"), + + CLEARED("cleared"), + + CLOSED("closed"), + + ARCHIVED("archived"), + + RUNNING("running"); + + private String value; + + DriveLogStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DriveLogStatus fromValue(String value) { + for (DriveLogStatus b : DriveLogStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogUpdate.java new file mode 100644 index 0000000..ae71525 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogUpdate.java @@ -0,0 +1,500 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLogStatus; +import com.timr.api.models.LocationUpdate; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogUpdate + */ +@JsonPropertyOrder({ + DriveLogUpdate.JSON_PROPERTY_START, + DriveLogUpdate.JSON_PROPERTY_END, + DriveLogUpdate.JSON_PROPERTY_CHANGED, + DriveLogUpdate.JSON_PROPERTY_START_MILEAGE, + DriveLogUpdate.JSON_PROPERTY_END_MILEAGE, + DriveLogUpdate.JSON_PROPERTY_ROUTE, + DriveLogUpdate.JSON_PROPERTY_PURPOSE, + DriveLogUpdate.JSON_PROPERTY_VISITED, + DriveLogUpdate.JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, + DriveLogUpdate.JSON_PROPERTY_STATUS, + DriveLogUpdate.JSON_PROPERTY_METADATA, + DriveLogUpdate.JSON_PROPERTY_START_LOCATION, + DriveLogUpdate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogUpdate { + public static final String JSON_PROPERTY_START = "start"; + + private JsonNullable<@Nullable OffsetDateTime> start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private JsonNullable<@Nullable Boolean> changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_MILEAGE = "start_mileage"; + + private JsonNullable<@Nullable Long> startMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_MILEAGE = "end_mileage"; + + private JsonNullable<@Nullable Long> endMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ROUTE = "route"; + + private JsonNullable<@Nullable String> route = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PURPOSE = "purpose"; + + private JsonNullable<@Nullable String> purpose = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_VISITED = "visited"; + + private JsonNullable<@Nullable String> visited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID = "drive_log_category_id"; + + private JsonNullable<@Nullable String> driveLogCategoryId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + + private JsonNullable<@Nullable DriveLogStatus> status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + + private JsonNullable<@Nullable LocationUpdate> startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + + private JsonNullable<@Nullable LocationUpdate> endLocation = JsonNullable.undefined(); + + public DriveLogUpdate() { + } + + public DriveLogUpdate start(@Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public DriveLogUpdate end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public DriveLogUpdate changed(@Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public DriveLogUpdate startMileage(@Nullable Long startMileage) { + this.startMileage = JsonNullable.of(startMileage); + + return this; + } + + /** + * Get startMileage + * @return startMileage + */ + + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Long> getStartMileage() { + return startMileage; + } + + @JsonProperty(JSON_PROPERTY_START_MILEAGE) + public void setStartMileage(JsonNullable startMileage) { + this.startMileage = startMileage; + } + + + + public DriveLogUpdate endMileage(@Nullable Long endMileage) { + this.endMileage = JsonNullable.of(endMileage); + + return this; + } + + /** + * Get endMileage + * @return endMileage + */ + + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Long> getEndMileage() { + return endMileage; + } + + @JsonProperty(JSON_PROPERTY_END_MILEAGE) + public void setEndMileage(JsonNullable endMileage) { + this.endMileage = endMileage; + } + + + + public DriveLogUpdate route(@Nullable String route) { + this.route = JsonNullable.of(route); + + return this; + } + + /** + * Get route + * @return route + */ + + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getRoute() { + return route; + } + + @JsonProperty(JSON_PROPERTY_ROUTE) + public void setRoute(JsonNullable route) { + this.route = route; + } + + + + public DriveLogUpdate purpose(@Nullable String purpose) { + this.purpose = JsonNullable.of(purpose); + + return this; + } + + /** + * Get purpose + * @return purpose + */ + + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getPurpose() { + return purpose; + } + + @JsonProperty(JSON_PROPERTY_PURPOSE) + public void setPurpose(JsonNullable purpose) { + this.purpose = purpose; + } + + + + public DriveLogUpdate visited(@Nullable String visited) { + this.visited = JsonNullable.of(visited); + + return this; + } + + /** + * Get visited + * @return visited + */ + + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getVisited() { + return visited; + } + + @JsonProperty(JSON_PROPERTY_VISITED) + public void setVisited(JsonNullable visited) { + this.visited = visited; + } + + + + public DriveLogUpdate driveLogCategoryId(@Nullable String driveLogCategoryId) { + this.driveLogCategoryId = JsonNullable.of(driveLogCategoryId); + + return this; + } + + /** + * Get driveLogCategoryId + * @return driveLogCategoryId + */ + + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDriveLogCategoryId() { + return driveLogCategoryId; + } + + @JsonProperty(JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID) + public void setDriveLogCategoryId(JsonNullable driveLogCategoryId) { + this.driveLogCategoryId = driveLogCategoryId; + } + + + + public DriveLogUpdate status(@Nullable DriveLogStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable DriveLogStatus> getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public DriveLogUpdate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DriveLogUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public DriveLogUpdate startLocation(@Nullable LocationUpdate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationUpdate> getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public DriveLogUpdate endLocation(@Nullable LocationUpdate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationUpdate> getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogUpdate driveLogUpdate = (DriveLogUpdate) o; + return equalsNullable(this.start, driveLogUpdate.start) && + equalsNullable(this.end, driveLogUpdate.end) && + equalsNullable(this.changed, driveLogUpdate.changed) && + equalsNullable(this.startMileage, driveLogUpdate.startMileage) && + equalsNullable(this.endMileage, driveLogUpdate.endMileage) && + equalsNullable(this.route, driveLogUpdate.route) && + equalsNullable(this.purpose, driveLogUpdate.purpose) && + equalsNullable(this.visited, driveLogUpdate.visited) && + equalsNullable(this.driveLogCategoryId, driveLogUpdate.driveLogCategoryId) && + equalsNullable(this.status, driveLogUpdate.status) && + equalsNullable(this.metadata, driveLogUpdate.metadata) && + equalsNullable(this.startLocation, driveLogUpdate.startLocation) && + equalsNullable(this.endLocation, driveLogUpdate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(changed), hashCodeNullable(startMileage), hashCodeNullable(endMileage), hashCodeNullable(route), hashCodeNullable(purpose), hashCodeNullable(visited), hashCodeNullable(driveLogCategoryId), hashCodeNullable(status), hashCodeNullable(metadata), hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogUpdate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" driveLogCategoryId: ").append(toIndentedString(driveLogCategoryId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogUpsert.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogUpsert.java new file mode 100644 index 0000000..a691475 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogUpsert.java @@ -0,0 +1,439 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLogStatus; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogUpsert + */ +@JsonPropertyOrder({ + DriveLogUpsert.JSON_PROPERTY_START, + DriveLogUpsert.JSON_PROPERTY_END, + DriveLogUpsert.JSON_PROPERTY_CHANGED, + DriveLogUpsert.JSON_PROPERTY_START_MILEAGE, + DriveLogUpsert.JSON_PROPERTY_END_MILEAGE, + DriveLogUpsert.JSON_PROPERTY_ROUTE, + DriveLogUpsert.JSON_PROPERTY_PURPOSE, + DriveLogUpsert.JSON_PROPERTY_VISITED, + DriveLogUpsert.JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, + DriveLogUpsert.JSON_PROPERTY_STATUS, + DriveLogUpsert.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogUpsert { + public static final String JSON_PROPERTY_START = "start"; + + private JsonNullable<@Nullable OffsetDateTime> start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private JsonNullable<@Nullable Boolean> changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_MILEAGE = "start_mileage"; + + private JsonNullable<@Nullable Long> startMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_MILEAGE = "end_mileage"; + + private JsonNullable<@Nullable Long> endMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ROUTE = "route"; + + private JsonNullable<@Nullable String> route = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PURPOSE = "purpose"; + + private JsonNullable<@Nullable String> purpose = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_VISITED = "visited"; + + private JsonNullable<@Nullable String> visited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID = "drive_log_category_id"; + + private JsonNullable<@Nullable String> driveLogCategoryId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + + private JsonNullable<@Nullable DriveLogStatus> status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public DriveLogUpsert() { + } + + public DriveLogUpsert start(@Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public DriveLogUpsert end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public DriveLogUpsert changed(@Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public DriveLogUpsert startMileage(@Nullable Long startMileage) { + this.startMileage = JsonNullable.of(startMileage); + + return this; + } + + /** + * Get startMileage + * @return startMileage + */ + + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Long> getStartMileage() { + return startMileage; + } + + @JsonProperty(JSON_PROPERTY_START_MILEAGE) + public void setStartMileage(JsonNullable startMileage) { + this.startMileage = startMileage; + } + + + + public DriveLogUpsert endMileage(@Nullable Long endMileage) { + this.endMileage = JsonNullable.of(endMileage); + + return this; + } + + /** + * Get endMileage + * @return endMileage + */ + + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Long> getEndMileage() { + return endMileage; + } + + @JsonProperty(JSON_PROPERTY_END_MILEAGE) + public void setEndMileage(JsonNullable endMileage) { + this.endMileage = endMileage; + } + + + + public DriveLogUpsert route(@Nullable String route) { + this.route = JsonNullable.of(route); + + return this; + } + + /** + * Get route + * @return route + */ + + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getRoute() { + return route; + } + + @JsonProperty(JSON_PROPERTY_ROUTE) + public void setRoute(JsonNullable route) { + this.route = route; + } + + + + public DriveLogUpsert purpose(@Nullable String purpose) { + this.purpose = JsonNullable.of(purpose); + + return this; + } + + /** + * Get purpose + * @return purpose + */ + + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getPurpose() { + return purpose; + } + + @JsonProperty(JSON_PROPERTY_PURPOSE) + public void setPurpose(JsonNullable purpose) { + this.purpose = purpose; + } + + + + public DriveLogUpsert visited(@Nullable String visited) { + this.visited = JsonNullable.of(visited); + + return this; + } + + /** + * Get visited + * @return visited + */ + + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getVisited() { + return visited; + } + + @JsonProperty(JSON_PROPERTY_VISITED) + public void setVisited(JsonNullable visited) { + this.visited = visited; + } + + + + public DriveLogUpsert driveLogCategoryId(@Nullable String driveLogCategoryId) { + this.driveLogCategoryId = JsonNullable.of(driveLogCategoryId); + + return this; + } + + /** + * Get driveLogCategoryId + * @return driveLogCategoryId + */ + + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDriveLogCategoryId() { + return driveLogCategoryId; + } + + @JsonProperty(JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID) + public void setDriveLogCategoryId(JsonNullable driveLogCategoryId) { + this.driveLogCategoryId = driveLogCategoryId; + } + + + + public DriveLogUpsert status(@Nullable DriveLogStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable DriveLogStatus> getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public DriveLogUpsert metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DriveLogUpsert putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogUpsert driveLogUpsert = (DriveLogUpsert) o; + return equalsNullable(this.start, driveLogUpsert.start) && + equalsNullable(this.end, driveLogUpsert.end) && + equalsNullable(this.changed, driveLogUpsert.changed) && + equalsNullable(this.startMileage, driveLogUpsert.startMileage) && + equalsNullable(this.endMileage, driveLogUpsert.endMileage) && + equalsNullable(this.route, driveLogUpsert.route) && + equalsNullable(this.purpose, driveLogUpsert.purpose) && + equalsNullable(this.visited, driveLogUpsert.visited) && + equalsNullable(this.driveLogCategoryId, driveLogUpsert.driveLogCategoryId) && + equalsNullable(this.status, driveLogUpsert.status) && + equalsNullable(this.metadata, driveLogUpsert.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(changed), hashCodeNullable(startMileage), hashCodeNullable(endMileage), hashCodeNullable(route), hashCodeNullable(purpose), hashCodeNullable(visited), hashCodeNullable(driveLogCategoryId), hashCodeNullable(status), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogUpsert {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" driveLogCategoryId: ").append(toIndentedString(driveLogCategoryId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogsPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogsPage.java new file mode 100644 index 0000000..5983b0f --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogsPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLog; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogsPage + */ +@JsonPropertyOrder({ + DriveLogsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + DriveLogsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public DriveLogsPage() { + } + + public DriveLogsPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public DriveLogsPage data(List data) { + + this.data = data; + return this; + } + + public DriveLogsPage addDataItem(DriveLog dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogsPage driveLogsPage = (DriveLogsPage) o; + return Objects.equals(this.nextPageToken, driveLogsPage.nextPageToken) && + Objects.equals(this.data, driveLogsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogsSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogsSortColumn.java new file mode 100644 index 0000000..bdf4176 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DriveLogsSortColumn.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Drive Logs. + */ +public enum DriveLogsSortColumn { + + START("start"), + + LAST_MODIFIED("last_modified"); + + private String value; + + DriveLogsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DriveLogsSortColumn fromValue(String value) { + for (DriveLogsSortColumn b : DriveLogsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Duration.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Duration.java new file mode 100644 index 0000000..0325e52 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Duration.java @@ -0,0 +1,184 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DurationType; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Duration + */ +@JsonPropertyOrder({ + Duration.JSON_PROPERTY_TYPE, + Duration.JSON_PROPERTY_MINUTES, + Duration.JSON_PROPERTY_MINUTES_ROUNDED +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Duration { + public static final String JSON_PROPERTY_TYPE = "type"; + + private DurationType type; + + public static final String JSON_PROPERTY_MINUTES = "minutes"; + + private Long minutes; + + public static final String JSON_PROPERTY_MINUTES_ROUNDED = "minutes_rounded"; + + private Long minutesRounded; + + public Duration() { + } + + public Duration type(DurationType type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DurationType getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(DurationType type) { + this.type = type; + } + + + public Duration minutes(Long minutes) { + + this.minutes = minutes; + return this; + } + + /** + * Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + * @return minutes + */ + + @JsonProperty(value = JSON_PROPERTY_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getMinutes() { + return minutes; + } + + + @JsonProperty(value = JSON_PROPERTY_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setMinutes(Long minutes) { + this.minutes = minutes; + } + + + public Duration minutesRounded(Long minutesRounded) { + + this.minutesRounded = minutesRounded; + return this; + } + + /** + * Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + * @return minutesRounded + */ + + @JsonProperty(value = JSON_PROPERTY_MINUTES_ROUNDED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getMinutesRounded() { + return minutesRounded; + } + + + @JsonProperty(value = JSON_PROPERTY_MINUTES_ROUNDED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setMinutesRounded(Long minutesRounded) { + this.minutesRounded = minutesRounded; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Duration duration = (Duration) o; + return Objects.equals(this.type, duration.type) && + Objects.equals(this.minutes, duration.minutes) && + Objects.equals(this.minutesRounded, duration.minutesRounded); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type, minutes, minutesRounded); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Duration {\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" minutes: ").append(toIndentedString(minutes)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DurationType.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DurationType.java new file mode 100644 index 0000000..1798e8c --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DurationType.java @@ -0,0 +1,63 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * How the duration of a single recording is expressed. Not to be confused with `DurationUnit`, which states the unit a Working Time Type is recorded in. + */ +public enum DurationType { + + MINUTES("minutes"), + + FULL_DAY("full_day"), + + HALF_DAY("half_day"); + + private String value; + + DurationType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DurationType fromValue(String value) { + for (DurationType b : DurationType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/DurationUnit.java b/sdk/java-restclient/src/main/java/com/timr/api/models/DurationUnit.java new file mode 100644 index 0000000..745e807 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/DurationUnit.java @@ -0,0 +1,63 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Unit a Working Time Type is recorded in. Not to be confused with `DurationType`, which states how an individual recording's duration is expressed. + */ +public enum DurationUnit { + + MINUTES("minutes"), + + HALF_DAYS("half_days"), + + DAYS("days"); + + private String value; + + DurationUnit(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DurationUnit fromValue(String value) { + for (DurationUnit b : DurationUnit.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Error.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Error.java new file mode 100644 index 0000000..7458a08 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Error.java @@ -0,0 +1,355 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.ErrorEntry; +import java.net.URI; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TIMR error response body, extending the Problem Details base with `timestamp`, `trace_id` and per-field `errors[]` for validation, binding, constraint, request-body deserialization, and reference-not-found errors. The semantic identifier is encoded in the `type` URI (e.g. `https://errors.timr.com/conflict/resource-outdated`). Slugs in the `type` URI are lowercase kebab-case: a top-level category (`validation`, `reference-not-found`, `conflict`, `forbidden`, `internal`) optionally followed by a specific sub-slug (`conflict/resource-outdated`, `validation/end-time-required`, `reference-not-found/user`). + */ +@JsonPropertyOrder({ + Error.JSON_PROPERTY_TYPE, + Error.JSON_PROPERTY_TITLE, + Error.JSON_PROPERTY_STATUS, + Error.JSON_PROPERTY_DETAIL, + Error.JSON_PROPERTY_INSTANCE, + Error.JSON_PROPERTY_TIMESTAMP, + Error.JSON_PROPERTY_TRACE_ID, + Error.JSON_PROPERTY_ERRORS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Error { + public static final String JSON_PROPERTY_TYPE = "type"; + + private URI type; + + public static final String JSON_PROPERTY_TITLE = "title"; + + private String title; + + public static final String JSON_PROPERTY_STATUS = "status"; + + private Integer status; + + public static final String JSON_PROPERTY_DETAIL = "detail"; + + private JsonNullable<@Nullable String> detail = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_INSTANCE = "instance"; + + private JsonNullable<@Nullable String> instance = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TIMESTAMP = "timestamp"; + + private OffsetDateTime timestamp; + + public static final String JSON_PROPERTY_TRACE_ID = "trace_id"; + + private JsonNullable<@Nullable String> traceId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ERRORS = "errors"; + + private JsonNullable<@Nullable List> errors = JsonNullable.>undefined(); + + public Error() { + } + + public Error type(URI type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public URI getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(URI type) { + this.type = type; + } + + + public Error title(String title) { + + this.title = title; + return this; + } + + /** + * Get title + * @return title + */ + + @JsonProperty(value = JSON_PROPERTY_TITLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getTitle() { + return title; + } + + + @JsonProperty(value = JSON_PROPERTY_TITLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTitle(String title) { + this.title = title; + } + + + public Error status(Integer status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(Integer status) { + this.status = status; + } + + + public Error detail(@Nullable String detail) { + this.detail = JsonNullable.of(detail); + + return this; + } + + /** + * Get detail + * @return detail + */ + + @JsonProperty(value = JSON_PROPERTY_DETAIL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDetail() { + return detail; + } + + @JsonProperty(JSON_PROPERTY_DETAIL) + public void setDetail(JsonNullable detail) { + this.detail = detail; + } + + + + public Error instance(@Nullable String instance) { + this.instance = JsonNullable.of(instance); + + return this; + } + + /** + * Get instance + * @return instance + */ + + @JsonProperty(value = JSON_PROPERTY_INSTANCE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getInstance() { + return instance; + } + + @JsonProperty(JSON_PROPERTY_INSTANCE) + public void setInstance(JsonNullable instance) { + this.instance = instance; + } + + + + public Error timestamp(OffsetDateTime timestamp) { + + this.timestamp = timestamp; + return this; + } + + /** + * Get timestamp + * @return timestamp + */ + + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getTimestamp() { + return timestamp; + } + + + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTimestamp(OffsetDateTime timestamp) { + this.timestamp = timestamp; + } + + + public Error traceId(@Nullable String traceId) { + this.traceId = JsonNullable.of(traceId); + + return this; + } + + /** + * Get traceId + * @return traceId + */ + + @JsonProperty(value = JSON_PROPERTY_TRACE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getTraceId() { + return traceId; + } + + @JsonProperty(JSON_PROPERTY_TRACE_ID) + public void setTraceId(JsonNullable traceId) { + this.traceId = traceId; + } + + + + public Error errors(@Nullable List errors) { + this.errors = JsonNullable.>of(errors); + + return this; + } + + public Error addErrorsItem(ErrorEntry errorsItem) { + if (this.errors == null || !this.errors.isPresent()) { + this.errors = JsonNullable.>of(new ArrayList<>()); + } + try { + this.errors.get().add(errorsItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get errors + * @return errors + */ + + @JsonProperty(value = JSON_PROPERTY_ERRORS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable List> getErrors() { + return errors; + } + + @JsonProperty(JSON_PROPERTY_ERRORS) + public void setErrors(JsonNullable> errors) { + this.errors = errors; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Error error = (Error) o; + return Objects.equals(this.type, error.type) && + Objects.equals(this.title, error.title) && + Objects.equals(this.status, error.status) && + equalsNullable(this.detail, error.detail) && + equalsNullable(this.instance, error.instance) && + Objects.equals(this.timestamp, error.timestamp) && + equalsNullable(this.traceId, error.traceId) && + equalsNullable(this.errors, error.errors); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type, title, status, hashCodeNullable(detail), hashCodeNullable(instance), timestamp, hashCodeNullable(traceId), hashCodeNullable(errors)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Error {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/ErrorEntry.java b/sdk/java-restclient/src/main/java/com/timr/api/models/ErrorEntry.java new file mode 100644 index 0000000..0604259 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/ErrorEntry.java @@ -0,0 +1,184 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.net.URI; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Field-level or sub-error entry, shaped like a sub-ProblemDetail. The `type` URI identifies the specific constraint or sub-error category (e.g. `validation/not-null` for a Bean Validation `@NotNull`, `validation/paused-working-time` for a TIMR custom validator code, `validation/type-mismatch` for a value that does not fit its target type, `validation/unknown-property` for a property the resource does not declare, `reference-not-found/user` for a `MappingException`). `field` is the JSONPath of the offending property in the request body, rooted at `$` — array elements included. An error about a query parameter names it plainly instead, without the `$.` prefix. + */ +@JsonPropertyOrder({ + ErrorEntry.JSON_PROPERTY_TYPE, + ErrorEntry.JSON_PROPERTY_FIELD, + ErrorEntry.JSON_PROPERTY_DETAIL +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ErrorEntry { + public static final String JSON_PROPERTY_TYPE = "type"; + + private URI type; + + public static final String JSON_PROPERTY_FIELD = "field"; + + private JsonNullable<@Nullable String> field = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DETAIL = "detail"; + + private String detail; + + public ErrorEntry() { + } + + public ErrorEntry type(URI type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public URI getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(URI type) { + this.type = type; + } + + + public ErrorEntry field(@Nullable String field) { + this.field = JsonNullable.of(field); + + return this; + } + + /** + * Get field + * @return field + */ + + @JsonProperty(value = JSON_PROPERTY_FIELD, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getField() { + return field; + } + + @JsonProperty(JSON_PROPERTY_FIELD) + public void setField(JsonNullable field) { + this.field = field; + } + + + + public ErrorEntry detail(String detail) { + + this.detail = detail; + return this; + } + + /** + * Get detail + * @return detail + */ + + @JsonProperty(value = JSON_PROPERTY_DETAIL, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDetail() { + return detail; + } + + + @JsonProperty(value = JSON_PROPERTY_DETAIL, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDetail(String detail) { + this.detail = detail; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ErrorEntry errorEntry = (ErrorEntry) o; + return Objects.equals(this.type, errorEntry.type) && + equalsNullable(this.field, errorEntry.field) && + Objects.equals(this.detail, errorEntry.detail); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type, hashCodeNullable(field), detail); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ErrorEntry {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/FlexTimeIndicator.java b/sdk/java-restclient/src/main/java/com/timr/api/models/FlexTimeIndicator.java new file mode 100644 index 0000000..241e6f1 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/FlexTimeIndicator.java @@ -0,0 +1,63 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Traffic-light rating of the flex time balance. The thresholds are an account setting and are not part of this contract. + */ +public enum FlexTimeIndicator { + + GREEN("green"), + + YELLOW("yellow"), + + RED("red"); + + private String value; + + FlexTimeIndicator(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static FlexTimeIndicator fromValue(String value) { + for (FlexTimeIndicator b : FlexTimeIndicator.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Holiday.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Holiday.java new file mode 100644 index 0000000..02a8791 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Holiday.java @@ -0,0 +1,183 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Holiday + */ +@JsonPropertyOrder({ + Holiday.JSON_PROPERTY_DATE, + Holiday.JSON_PROPERTY_DESCRIPTION, + Holiday.JSON_PROPERTY_HALF_DAY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Holiday { + public static final String JSON_PROPERTY_DATE = "date"; + + private LocalDate date; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private String description; + + public static final String JSON_PROPERTY_HALF_DAY = "half_day"; + + private Boolean halfDay; + + public Holiday() { + } + + public Holiday date(LocalDate date) { + + this.date = date; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return date + */ + + @JsonProperty(value = JSON_PROPERTY_DATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getDate() { + return date; + } + + + @JsonProperty(value = JSON_PROPERTY_DATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDate(LocalDate date) { + this.date = date; + } + + + public Holiday description(String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(String description) { + this.description = description; + } + + + public Holiday halfDay(Boolean halfDay) { + + this.halfDay = halfDay; + return this; + } + + /** + * Get halfDay + * @return halfDay + */ + + @JsonProperty(value = JSON_PROPERTY_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getHalfDay() { + return halfDay; + } + + + @JsonProperty(value = JSON_PROPERTY_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setHalfDay(Boolean halfDay) { + this.halfDay = halfDay; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Holiday holiday = (Holiday) o; + return Objects.equals(this.date, holiday.date) && + Objects.equals(this.description, holiday.description) && + Objects.equals(this.halfDay, holiday.halfDay); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(date, description, halfDay); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Holiday {\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/HolidayCalendarPartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidayCalendarPartial.java new file mode 100644 index 0000000..39ec9f7 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidayCalendarPartial.java @@ -0,0 +1,150 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A holiday calendar. Its holidays are either generated automatically or maintained manually. + */ +@JsonPropertyOrder({ + HolidayCalendarPartial.JSON_PROPERTY_ID, + HolidayCalendarPartial.JSON_PROPERTY_DESCRIPTION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HolidayCalendarPartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private String description; + + public HolidayCalendarPartial() { + } + + public HolidayCalendarPartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public HolidayCalendarPartial description(String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(String description) { + this.description = description; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HolidayCalendarPartial holidayCalendarPartial = (HolidayCalendarPartial) o; + return Objects.equals(this.id, holidayCalendarPartial.id) && + Objects.equals(this.description, holidayCalendarPartial.description); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, description); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HolidayCalendarPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/HolidayCalendarsPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidayCalendarsPage.java new file mode 100644 index 0000000..71f8637 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidayCalendarsPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.HolidayCalendarPartial; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * HolidayCalendarsPage + */ +@JsonPropertyOrder({ + HolidayCalendarsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + HolidayCalendarsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HolidayCalendarsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public HolidayCalendarsPage() { + } + + public HolidayCalendarsPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public HolidayCalendarsPage data(List data) { + + this.data = data; + return this; + } + + public HolidayCalendarsPage addDataItem(HolidayCalendarPartial dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HolidayCalendarsPage holidayCalendarsPage = (HolidayCalendarsPage) o; + return Objects.equals(this.nextPageToken, holidayCalendarsPage.nextPageToken) && + Objects.equals(this.data, holidayCalendarsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HolidayCalendarsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/HolidayCalendarsSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidayCalendarsSortColumn.java new file mode 100644 index 0000000..ad7d451 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidayCalendarsSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Holiday Calendars. + */ +public enum HolidayCalendarsSortColumn { + + DESCRIPTION("description"); + + private String value; + + HolidayCalendarsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static HolidayCalendarsSortColumn fromValue(String value) { + for (HolidayCalendarsSortColumn b : HolidayCalendarsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/HolidaysPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidaysPage.java new file mode 100644 index 0000000..f948d2f --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidaysPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.Holiday; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * HolidaysPage + */ +@JsonPropertyOrder({ + HolidaysPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + HolidaysPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HolidaysPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public HolidaysPage() { + } + + public HolidaysPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public HolidaysPage data(List data) { + + this.data = data; + return this; + } + + public HolidaysPage addDataItem(Holiday dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HolidaysPage holidaysPage = (HolidaysPage) o; + return Objects.equals(this.nextPageToken, holidaysPage.nextPageToken) && + Objects.equals(this.data, holidaysPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HolidaysPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/HolidaysSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidaysSortColumn.java new file mode 100644 index 0000000..4544a64 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/HolidaysSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Holidays. + */ +public enum HolidaysSortColumn { + + DATE("date"); + + private String value; + + HolidaysSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static HolidaysSortColumn fromValue(String value) { + for (HolidaysSortColumn b : HolidaysSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Location.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Location.java new file mode 100644 index 0000000..f6f860a --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Location.java @@ -0,0 +1,246 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Location + */ +@JsonPropertyOrder({ + Location.JSON_PROPERTY_LAT, + Location.JSON_PROPERTY_LON, + Location.JSON_PROPERTY_TIMESTAMP, + Location.JSON_PROPERTY_FORMATTED_ADDRESS, + Location.JSON_PROPERTY_ACCURACY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Location { + public static final String JSON_PROPERTY_LAT = "lat"; + + private @Nullable Float lat; + + public static final String JSON_PROPERTY_LON = "lon"; + + private @Nullable Float lon; + + public static final String JSON_PROPERTY_TIMESTAMP = "timestamp"; + + private JsonNullable<@Nullable OffsetDateTime> timestamp = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_FORMATTED_ADDRESS = "formatted_address"; + + private JsonNullable<@Nullable String> formattedAddress = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACCURACY = "accuracy"; + + private @Nullable Float accuracy; + + public Location() { + } + + public Location lat(@Nullable Float lat) { + + this.lat = lat; + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Float getLat() { + return lat; + } + + + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLat(@Nullable Float lat) { + this.lat = lat; + } + + + public Location lon(@Nullable Float lon) { + + this.lon = lon; + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Float getLon() { + return lon; + } + + + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLon(@Nullable Float lon) { + this.lon = lon; + } + + + public Location timestamp(@Nullable OffsetDateTime timestamp) { + this.timestamp = JsonNullable.of(timestamp); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return timestamp + */ + + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getTimestamp() { + return timestamp; + } + + @JsonProperty(JSON_PROPERTY_TIMESTAMP) + public void setTimestamp(JsonNullable timestamp) { + this.timestamp = timestamp; + } + + + + public Location formattedAddress(@Nullable String formattedAddress) { + this.formattedAddress = JsonNullable.of(formattedAddress); + + return this; + } + + /** + * Get formattedAddress + * @return formattedAddress + */ + + @JsonProperty(value = JSON_PROPERTY_FORMATTED_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getFormattedAddress() { + return formattedAddress; + } + + @JsonProperty(JSON_PROPERTY_FORMATTED_ADDRESS) + public void setFormattedAddress(JsonNullable formattedAddress) { + this.formattedAddress = formattedAddress; + } + + + + public Location accuracy(@Nullable Float accuracy) { + + this.accuracy = accuracy; + return this; + } + + /** + * Horizontal GPS accuracy in meters. + * @return accuracy + */ + + @JsonProperty(value = JSON_PROPERTY_ACCURACY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Float getAccuracy() { + return accuracy; + } + + + @JsonProperty(value = JSON_PROPERTY_ACCURACY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccuracy(@Nullable Float accuracy) { + this.accuracy = accuracy; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Location location = (Location) o; + return Objects.equals(this.lat, location.lat) && + Objects.equals(this.lon, location.lon) && + equalsNullable(this.timestamp, location.timestamp) && + equalsNullable(this.formattedAddress, location.formattedAddress) && + Objects.equals(this.accuracy, location.accuracy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lat, lon, hashCodeNullable(timestamp), hashCodeNullable(formattedAddress), accuracy); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Location {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/LocationCreate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/LocationCreate.java new file mode 100644 index 0000000..5ae4e10 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/LocationCreate.java @@ -0,0 +1,244 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * LocationCreate + */ +@JsonPropertyOrder({ + LocationCreate.JSON_PROPERTY_LAT, + LocationCreate.JSON_PROPERTY_LON, + LocationCreate.JSON_PROPERTY_TIMESTAMP, + LocationCreate.JSON_PROPERTY_FORMATTED_ADDRESS, + LocationCreate.JSON_PROPERTY_ACCURACY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class LocationCreate { + public static final String JSON_PROPERTY_LAT = "lat"; + + private Float lat; + + public static final String JSON_PROPERTY_LON = "lon"; + + private Float lon; + + public static final String JSON_PROPERTY_TIMESTAMP = "timestamp"; + + private JsonNullable<@Nullable OffsetDateTime> timestamp = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_FORMATTED_ADDRESS = "formatted_address"; + + private JsonNullable<@Nullable String> formattedAddress = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACCURACY = "accuracy"; + + private JsonNullable<@Nullable Float> accuracy = JsonNullable.undefined(); + + public LocationCreate() { + } + + public LocationCreate lat(Float lat) { + + this.lat = lat; + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + + @JsonProperty(value = JSON_PROPERTY_LAT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Float getLat() { + return lat; + } + + + @JsonProperty(value = JSON_PROPERTY_LAT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLat(Float lat) { + this.lat = lat; + } + + + public LocationCreate lon(Float lon) { + + this.lon = lon; + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + + @JsonProperty(value = JSON_PROPERTY_LON, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Float getLon() { + return lon; + } + + + @JsonProperty(value = JSON_PROPERTY_LON, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLon(Float lon) { + this.lon = lon; + } + + + public LocationCreate timestamp(@Nullable OffsetDateTime timestamp) { + this.timestamp = JsonNullable.of(timestamp); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return timestamp + */ + + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getTimestamp() { + return timestamp; + } + + @JsonProperty(JSON_PROPERTY_TIMESTAMP) + public void setTimestamp(JsonNullable timestamp) { + this.timestamp = timestamp; + } + + + + public LocationCreate formattedAddress(@Nullable String formattedAddress) { + this.formattedAddress = JsonNullable.of(formattedAddress); + + return this; + } + + /** + * Get formattedAddress + * @return formattedAddress + */ + + @JsonProperty(value = JSON_PROPERTY_FORMATTED_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getFormattedAddress() { + return formattedAddress; + } + + @JsonProperty(JSON_PROPERTY_FORMATTED_ADDRESS) + public void setFormattedAddress(JsonNullable formattedAddress) { + this.formattedAddress = formattedAddress; + } + + + + public LocationCreate accuracy(@Nullable Float accuracy) { + this.accuracy = JsonNullable.of(accuracy); + + return this; + } + + /** + * Horizontal GPS accuracy in meters. + * @return accuracy + */ + + @JsonProperty(value = JSON_PROPERTY_ACCURACY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Float> getAccuracy() { + return accuracy; + } + + @JsonProperty(JSON_PROPERTY_ACCURACY) + public void setAccuracy(JsonNullable accuracy) { + this.accuracy = accuracy; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LocationCreate locationCreate = (LocationCreate) o; + return Objects.equals(this.lat, locationCreate.lat) && + Objects.equals(this.lon, locationCreate.lon) && + equalsNullable(this.timestamp, locationCreate.timestamp) && + equalsNullable(this.formattedAddress, locationCreate.formattedAddress) && + equalsNullable(this.accuracy, locationCreate.accuracy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lat, lon, hashCodeNullable(timestamp), hashCodeNullable(formattedAddress), hashCodeNullable(accuracy)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class LocationCreate {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/LocationUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/LocationUpdate.java new file mode 100644 index 0000000..4dc5d1c --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/LocationUpdate.java @@ -0,0 +1,240 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * LocationUpdate + */ +@JsonPropertyOrder({ + LocationUpdate.JSON_PROPERTY_LAT, + LocationUpdate.JSON_PROPERTY_LON, + LocationUpdate.JSON_PROPERTY_TIMESTAMP, + LocationUpdate.JSON_PROPERTY_FORMATTED_ADDRESS, + LocationUpdate.JSON_PROPERTY_ACCURACY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class LocationUpdate { + public static final String JSON_PROPERTY_LAT = "lat"; + + private JsonNullable<@Nullable Float> lat = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LON = "lon"; + + private JsonNullable<@Nullable Float> lon = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TIMESTAMP = "timestamp"; + + private JsonNullable<@Nullable OffsetDateTime> timestamp = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_FORMATTED_ADDRESS = "formatted_address"; + + private JsonNullable<@Nullable String> formattedAddress = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACCURACY = "accuracy"; + + private JsonNullable<@Nullable Float> accuracy = JsonNullable.undefined(); + + public LocationUpdate() { + } + + public LocationUpdate lat(@Nullable Float lat) { + this.lat = JsonNullable.of(lat); + + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Float> getLat() { + return lat; + } + + @JsonProperty(JSON_PROPERTY_LAT) + public void setLat(JsonNullable lat) { + this.lat = lat; + } + + + + public LocationUpdate lon(@Nullable Float lon) { + this.lon = JsonNullable.of(lon); + + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Float> getLon() { + return lon; + } + + @JsonProperty(JSON_PROPERTY_LON) + public void setLon(JsonNullable lon) { + this.lon = lon; + } + + + + public LocationUpdate timestamp(@Nullable OffsetDateTime timestamp) { + this.timestamp = JsonNullable.of(timestamp); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return timestamp + */ + + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getTimestamp() { + return timestamp; + } + + @JsonProperty(JSON_PROPERTY_TIMESTAMP) + public void setTimestamp(JsonNullable timestamp) { + this.timestamp = timestamp; + } + + + + public LocationUpdate formattedAddress(@Nullable String formattedAddress) { + this.formattedAddress = JsonNullable.of(formattedAddress); + + return this; + } + + /** + * Get formattedAddress + * @return formattedAddress + */ + + @JsonProperty(value = JSON_PROPERTY_FORMATTED_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getFormattedAddress() { + return formattedAddress; + } + + @JsonProperty(JSON_PROPERTY_FORMATTED_ADDRESS) + public void setFormattedAddress(JsonNullable formattedAddress) { + this.formattedAddress = formattedAddress; + } + + + + public LocationUpdate accuracy(@Nullable Float accuracy) { + this.accuracy = JsonNullable.of(accuracy); + + return this; + } + + /** + * Horizontal GPS accuracy in meters. + * @return accuracy + */ + + @JsonProperty(value = JSON_PROPERTY_ACCURACY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Float> getAccuracy() { + return accuracy; + } + + @JsonProperty(JSON_PROPERTY_ACCURACY) + public void setAccuracy(JsonNullable accuracy) { + this.accuracy = accuracy; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LocationUpdate locationUpdate = (LocationUpdate) o; + return equalsNullable(this.lat, locationUpdate.lat) && + equalsNullable(this.lon, locationUpdate.lon) && + equalsNullable(this.timestamp, locationUpdate.timestamp) && + equalsNullable(this.formattedAddress, locationUpdate.formattedAddress) && + equalsNullable(this.accuracy, locationUpdate.accuracy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(lat), hashCodeNullable(lon), hashCodeNullable(timestamp), hashCodeNullable(formattedAddress), hashCodeNullable(accuracy)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class LocationUpdate {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/NormalWorkingTimes.java b/sdk/java-restclient/src/main/java/com/timr/api/models/NormalWorkingTimes.java new file mode 100644 index 0000000..e08972c --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/NormalWorkingTimes.java @@ -0,0 +1,151 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * NormalWorkingTimes + */ +@JsonPropertyOrder({ + NormalWorkingTimes.JSON_PROPERTY_START, + NormalWorkingTimes.JSON_PROPERTY_END +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class NormalWorkingTimes { + public static final String JSON_PROPERTY_START = "start"; + + private JsonNullable<@Nullable String> start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable String> end = JsonNullable.undefined(); + + public NormalWorkingTimes() { + } + + public NormalWorkingTimes start(@Nullable String start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * Get start + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public NormalWorkingTimes end(@Nullable String end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * Get end + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NormalWorkingTimes normalWorkingTimes = (NormalWorkingTimes) o; + return equalsNullable(this.start, normalWorkingTimes.start) && + equalsNullable(this.end, normalWorkingTimes.end); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NormalWorkingTimes {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/OvertimeSurchargeAccount.java b/sdk/java-restclient/src/main/java/com/timr/api/models/OvertimeSurchargeAccount.java new file mode 100644 index 0000000..7b41474 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/OvertimeSurchargeAccount.java @@ -0,0 +1,181 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * OvertimeSurchargeAccount + */ +@JsonPropertyOrder({ + OvertimeSurchargeAccount.JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, + OvertimeSurchargeAccount.JSON_PROPERTY_NEW_MINUTES, + OvertimeSurchargeAccount.JSON_PROPERTY_BALANCE_TOTAL_MINUTES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class OvertimeSurchargeAccount { + public static final String JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES = "balance_last_period_minutes"; + + private @Nullable Integer balanceLastPeriodMinutes; + + public static final String JSON_PROPERTY_NEW_MINUTES = "new_minutes"; + + private @Nullable Integer newMinutes; + + public static final String JSON_PROPERTY_BALANCE_TOTAL_MINUTES = "balance_total_minutes"; + + private @Nullable Integer balanceTotalMinutes; + + public OvertimeSurchargeAccount() { + } + + public OvertimeSurchargeAccount balanceLastPeriodMinutes(@Nullable Integer balanceLastPeriodMinutes) { + + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + return this; + } + + /** + * Get balanceLastPeriodMinutes + * @return balanceLastPeriodMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getBalanceLastPeriodMinutes() { + return balanceLastPeriodMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceLastPeriodMinutes(@Nullable Integer balanceLastPeriodMinutes) { + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + } + + + public OvertimeSurchargeAccount newMinutes(@Nullable Integer newMinutes) { + + this.newMinutes = newMinutes; + return this; + } + + /** + * Get newMinutes + * @return newMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_NEW_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getNewMinutes() { + return newMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_NEW_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNewMinutes(@Nullable Integer newMinutes) { + this.newMinutes = newMinutes; + } + + + public OvertimeSurchargeAccount balanceTotalMinutes(@Nullable Integer balanceTotalMinutes) { + + this.balanceTotalMinutes = balanceTotalMinutes; + return this; + } + + /** + * Get balanceTotalMinutes + * @return balanceTotalMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getBalanceTotalMinutes() { + return balanceTotalMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceTotalMinutes(@Nullable Integer balanceTotalMinutes) { + this.balanceTotalMinutes = balanceTotalMinutes; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OvertimeSurchargeAccount overtimeSurchargeAccount = (OvertimeSurchargeAccount) o; + return Objects.equals(this.balanceLastPeriodMinutes, overtimeSurchargeAccount.balanceLastPeriodMinutes) && + Objects.equals(this.newMinutes, overtimeSurchargeAccount.newMinutes) && + Objects.equals(this.balanceTotalMinutes, overtimeSurchargeAccount.balanceTotalMinutes); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(balanceLastPeriodMinutes, newMinutes, balanceTotalMinutes); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OvertimeSurchargeAccount {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/OvertimeSurchargeAccounts.java b/sdk/java-restclient/src/main/java/com/timr/api/models/OvertimeSurchargeAccounts.java new file mode 100644 index 0000000..f5b9d3b --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/OvertimeSurchargeAccounts.java @@ -0,0 +1,216 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.OvertimeSurchargeAccount; +import com.timr.api.models.OvertimeSurchargeRule; +import java.math.BigDecimal; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * OvertimeSurchargeAccounts + */ +@JsonPropertyOrder({ + OvertimeSurchargeAccounts.JSON_PROPERTY_RULE, + OvertimeSurchargeAccounts.JSON_PROPERTY_PERCENTAGE, + OvertimeSurchargeAccounts.JSON_PROPERTY_OVERTIME, + OvertimeSurchargeAccounts.JSON_PROPERTY_SURCHARGE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class OvertimeSurchargeAccounts { + public static final String JSON_PROPERTY_RULE = "rule"; + + private OvertimeSurchargeRule rule; + + public static final String JSON_PROPERTY_PERCENTAGE = "percentage"; + + private @Nullable BigDecimal percentage; + + public static final String JSON_PROPERTY_OVERTIME = "overtime"; + + private OvertimeSurchargeAccount overtime; + + public static final String JSON_PROPERTY_SURCHARGE = "surcharge"; + + private OvertimeSurchargeAccount surcharge; + + public OvertimeSurchargeAccounts() { + } + + public OvertimeSurchargeAccounts rule(OvertimeSurchargeRule rule) { + + this.rule = rule; + return this; + } + + /** + * Get rule + * @return rule + */ + + @JsonProperty(value = JSON_PROPERTY_RULE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OvertimeSurchargeRule getRule() { + return rule; + } + + + @JsonProperty(value = JSON_PROPERTY_RULE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRule(OvertimeSurchargeRule rule) { + this.rule = rule; + } + + + public OvertimeSurchargeAccounts percentage(@Nullable BigDecimal percentage) { + + this.percentage = percentage; + return this; + } + + /** + * Get percentage + * @return percentage + */ + + @JsonProperty(value = JSON_PROPERTY_PERCENTAGE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable BigDecimal getPercentage() { + return percentage; + } + + + @JsonProperty(value = JSON_PROPERTY_PERCENTAGE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPercentage(@Nullable BigDecimal percentage) { + this.percentage = percentage; + } + + + public OvertimeSurchargeAccounts overtime(OvertimeSurchargeAccount overtime) { + + this.overtime = overtime; + return this; + } + + /** + * Get overtime + * @return overtime + */ + + @JsonProperty(value = JSON_PROPERTY_OVERTIME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OvertimeSurchargeAccount getOvertime() { + return overtime; + } + + + @JsonProperty(value = JSON_PROPERTY_OVERTIME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setOvertime(OvertimeSurchargeAccount overtime) { + this.overtime = overtime; + } + + + public OvertimeSurchargeAccounts surcharge(OvertimeSurchargeAccount surcharge) { + + this.surcharge = surcharge; + return this; + } + + /** + * Get surcharge + * @return surcharge + */ + + @JsonProperty(value = JSON_PROPERTY_SURCHARGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OvertimeSurchargeAccount getSurcharge() { + return surcharge; + } + + + @JsonProperty(value = JSON_PROPERTY_SURCHARGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSurcharge(OvertimeSurchargeAccount surcharge) { + this.surcharge = surcharge; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OvertimeSurchargeAccounts overtimeSurchargeAccounts = (OvertimeSurchargeAccounts) o; + return Objects.equals(this.rule, overtimeSurchargeAccounts.rule) && + Objects.equals(this.percentage, overtimeSurchargeAccounts.percentage) && + Objects.equals(this.overtime, overtimeSurchargeAccounts.overtime) && + Objects.equals(this.surcharge, overtimeSurchargeAccounts.surcharge); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(rule, percentage, overtime, surcharge); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OvertimeSurchargeAccounts {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/OvertimeSurchargeRule.java b/sdk/java-restclient/src/main/java/com/timr/api/models/OvertimeSurchargeRule.java new file mode 100644 index 0000000..3a87bf8 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/OvertimeSurchargeRule.java @@ -0,0 +1,182 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.UUID; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * OvertimeSurchargeRule + */ +@JsonPropertyOrder({ + OvertimeSurchargeRule.JSON_PROPERTY_ID, + OvertimeSurchargeRule.JSON_PROPERTY_NAME, + OvertimeSurchargeRule.JSON_PROPERTY_SHORT_NAME +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class OvertimeSurchargeRule { + public static final String JSON_PROPERTY_ID = "id"; + + private UUID id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_SHORT_NAME = "short_name"; + + private String shortName; + + public OvertimeSurchargeRule() { + } + + public OvertimeSurchargeRule id(UUID id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UUID getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(UUID id) { + this.id = id; + } + + + public OvertimeSurchargeRule name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public OvertimeSurchargeRule shortName(String shortName) { + + this.shortName = shortName; + return this; + } + + /** + * Get shortName + * @return shortName + */ + + @JsonProperty(value = JSON_PROPERTY_SHORT_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getShortName() { + return shortName; + } + + + @JsonProperty(value = JSON_PROPERTY_SHORT_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setShortName(String shortName) { + this.shortName = shortName; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OvertimeSurchargeRule overtimeSurchargeRule = (OvertimeSurchargeRule) o; + return Objects.equals(this.id, overtimeSurchargeRule.id) && + Objects.equals(this.name, overtimeSurchargeRule.name) && + Objects.equals(this.shortName, overtimeSurchargeRule.shortName); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, shortName); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OvertimeSurchargeRule {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/PagingInformation.java b/sdk/java-restclient/src/main/java/com/timr/api/models/PagingInformation.java new file mode 100644 index 0000000..e1a4a33 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/PagingInformation.java @@ -0,0 +1,117 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * PagingInformation + */ +@JsonPropertyOrder({ + PagingInformation.JSON_PROPERTY_NEXT_PAGE_TOKEN +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class PagingInformation { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public PagingInformation() { + } + + public PagingInformation nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PagingInformation pagingInformation = (PagingInformation) o; + return Objects.equals(this.nextPageToken, pagingInformation.nextPageToken); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PagingInformation {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Platform.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Platform.java new file mode 100644 index 0000000..be586f7 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Platform.java @@ -0,0 +1,69 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Platform the entry was recorded on. + */ +public enum Platform { + + TIMR_WEB("timr_web"), + + TIMR_MOBILE("timr_mobile"), + + TOUR_MOBILE("tour_mobile"), + + TIMR_TERMINAL("timr_terminal"), + + SYNC_API("sync_api"), + + TIMR_API("timr_api"); + + private String value; + + Platform(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static Platform fromValue(String value) { + for (Platform b : Platform.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/ProblemDetail.java b/sdk/java-restclient/src/main/java/com/timr/api/models/ProblemDetail.java new file mode 100644 index 0000000..066e583 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/ProblemDetail.java @@ -0,0 +1,242 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.net.URI; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * RFC 9457 Problem Details base members (`type`, `title`, `status`, `detail`, `instance`) — the common shape of all error response bodies. + */ +@JsonPropertyOrder({ + ProblemDetail.JSON_PROPERTY_TYPE, + ProblemDetail.JSON_PROPERTY_TITLE, + ProblemDetail.JSON_PROPERTY_STATUS, + ProblemDetail.JSON_PROPERTY_DETAIL, + ProblemDetail.JSON_PROPERTY_INSTANCE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProblemDetail { + public static final String JSON_PROPERTY_TYPE = "type"; + + private URI type; + + public static final String JSON_PROPERTY_TITLE = "title"; + + private String title; + + public static final String JSON_PROPERTY_STATUS = "status"; + + private Integer status; + + public static final String JSON_PROPERTY_DETAIL = "detail"; + + private JsonNullable<@Nullable String> detail = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_INSTANCE = "instance"; + + private JsonNullable<@Nullable String> instance = JsonNullable.undefined(); + + public ProblemDetail() { + } + + public ProblemDetail type(URI type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public URI getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(URI type) { + this.type = type; + } + + + public ProblemDetail title(String title) { + + this.title = title; + return this; + } + + /** + * Get title + * @return title + */ + + @JsonProperty(value = JSON_PROPERTY_TITLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getTitle() { + return title; + } + + + @JsonProperty(value = JSON_PROPERTY_TITLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTitle(String title) { + this.title = title; + } + + + public ProblemDetail status(Integer status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(Integer status) { + this.status = status; + } + + + public ProblemDetail detail(@Nullable String detail) { + this.detail = JsonNullable.of(detail); + + return this; + } + + /** + * Get detail + * @return detail + */ + + @JsonProperty(value = JSON_PROPERTY_DETAIL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDetail() { + return detail; + } + + @JsonProperty(JSON_PROPERTY_DETAIL) + public void setDetail(JsonNullable detail) { + this.detail = detail; + } + + + + public ProblemDetail instance(@Nullable String instance) { + this.instance = JsonNullable.of(instance); + + return this; + } + + /** + * Get instance + * @return instance + */ + + @JsonProperty(value = JSON_PROPERTY_INSTANCE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getInstance() { + return instance; + } + + @JsonProperty(JSON_PROPERTY_INSTANCE) + public void setInstance(JsonNullable instance) { + this.instance = instance; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProblemDetail problemDetail = (ProblemDetail) o; + return Objects.equals(this.type, problemDetail.type) && + Objects.equals(this.title, problemDetail.title) && + Objects.equals(this.status, problemDetail.status) && + equalsNullable(this.detail, problemDetail.detail) && + equalsNullable(this.instance, problemDetail.instance); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type, title, status, hashCodeNullable(detail), hashCodeNullable(instance)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProblemDetail {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTime.java b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTime.java new file mode 100644 index 0000000..d198a71 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTime.java @@ -0,0 +1,735 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTime; +import com.timr.api.models.Duration; +import com.timr.api.models.Location; +import com.timr.api.models.Platform; +import com.timr.api.models.ProjectTimeStatus; +import com.timr.api.models.TaskPartial; +import com.timr.api.models.UserPartial; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * One booking on a `task`, from `start` to `end`, optionally `billable`, with `break_times`, notes and locations. + */ +@JsonPropertyOrder({ + ProjectTime.JSON_PROPERTY_ID, + ProjectTime.JSON_PROPERTY_START, + ProjectTime.JSON_PROPERTY_END, + ProjectTime.JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, + ProjectTime.JSON_PROPERTY_BREAK_TIMES, + ProjectTime.JSON_PROPERTY_DURATION, + ProjectTime.JSON_PROPERTY_CHANGED, + ProjectTime.JSON_PROPERTY_NOTES, + ProjectTime.JSON_PROPERTY_USER, + ProjectTime.JSON_PROPERTY_TASK, + ProjectTime.JSON_PROPERTY_BILLABLE, + ProjectTime.JSON_PROPERTY_START_LOCATION, + ProjectTime.JSON_PROPERTY_END_LOCATION, + ProjectTime.JSON_PROPERTY_START_PLATFORM, + ProjectTime.JSON_PROPERTY_END_PLATFORM, + ProjectTime.JSON_PROPERTY_LAST_MODIFIED, + ProjectTime.JSON_PROPERTY_LAST_MODIFIED_BY, + ProjectTime.JSON_PROPERTY_STATUS, + ProjectTime.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTime { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_START = "start"; + + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + + private @Nullable OffsetDateTime end; + + public static final String JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES = "break_time_total_minutes"; + + private Integer breakTimeTotalMinutes; + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + + private List breakTimes; + + public static final String JSON_PROPERTY_DURATION = "duration"; + + private @Nullable Duration duration; + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private Boolean changed; + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private @Nullable String notes; + + public static final String JSON_PROPERTY_USER = "user"; + + private UserPartial user; + + public static final String JSON_PROPERTY_TASK = "task"; + + private TaskPartial task; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + + private Boolean billable; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + + private @Nullable Location startLocation; + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + + private @Nullable Location endLocation; + + public static final String JSON_PROPERTY_START_PLATFORM = "start_platform"; + + private @Nullable Platform startPlatform; + + public static final String JSON_PROPERTY_END_PLATFORM = "end_platform"; + + private @Nullable Platform endPlatform; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + + private @Nullable UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_STATUS = "status"; + + private ProjectTimeStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public ProjectTime() { + } + + public ProjectTime id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public ProjectTime start(OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(OffsetDateTime start) { + this.start = start; + } + + + public ProjectTime end(@Nullable OffsetDateTime end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable OffsetDateTime getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@Nullable OffsetDateTime end) { + this.end = end; + } + + + public ProjectTime breakTimeTotalMinutes(Integer breakTimeTotalMinutes) { + + this.breakTimeTotalMinutes = breakTimeTotalMinutes; + return this; + } + + /** + * Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + * @return breakTimeTotalMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getBreakTimeTotalMinutes() { + return breakTimeTotalMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreakTimeTotalMinutes(Integer breakTimeTotalMinutes) { + this.breakTimeTotalMinutes = breakTimeTotalMinutes; + } + + + public ProjectTime breakTimes(List breakTimes) { + + this.breakTimes = breakTimes; + return this; + } + + public ProjectTime addBreakTimesItem(BreakTime breakTimesItem) { + if (this.breakTimes == null) { + this.breakTimes = new ArrayList<>(); + } + this.breakTimes.add(breakTimesItem); + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getBreakTimes() { + return breakTimes; + } + + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreakTimes(List breakTimes) { + this.breakTimes = breakTimes; + } + + + public ProjectTime duration(@Nullable Duration duration) { + + this.duration = duration; + return this; + } + + /** + * Get duration + * @return duration + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Duration getDuration() { + return duration; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDuration(@Nullable Duration duration) { + this.duration = duration; + } + + + public ProjectTime changed(Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(Boolean changed) { + this.changed = changed; + } + + + public ProjectTime notes(@Nullable String notes) { + + this.notes = notes; + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNotes() { + return notes; + } + + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNotes(@Nullable String notes) { + this.notes = notes; + } + + + public ProjectTime user(UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(UserPartial user) { + this.user = user; + } + + + public ProjectTime task(TaskPartial task) { + + this.task = task; + return this; + } + + /** + * Get task + * @return task + */ + + @JsonProperty(value = JSON_PROPERTY_TASK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public TaskPartial getTask() { + return task; + } + + + @JsonProperty(value = JSON_PROPERTY_TASK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTask(TaskPartial task) { + this.task = task; + } + + + public ProjectTime billable(Boolean billable) { + + this.billable = billable; + return this; + } + + /** + * Get billable + * @return billable + */ + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBillable() { + return billable; + } + + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBillable(Boolean billable) { + this.billable = billable; + } + + + public ProjectTime startLocation(@Nullable Location startLocation) { + + this.startLocation = startLocation; + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Location getStartLocation() { + return startLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartLocation(@Nullable Location startLocation) { + this.startLocation = startLocation; + } + + + public ProjectTime endLocation(@Nullable Location endLocation) { + + this.endLocation = endLocation; + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Location getEndLocation() { + return endLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndLocation(@Nullable Location endLocation) { + this.endLocation = endLocation; + } + + + public ProjectTime startPlatform(@Nullable Platform startPlatform) { + + this.startPlatform = startPlatform; + return this; + } + + /** + * Get startPlatform + * @return startPlatform + */ + + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Platform getStartPlatform() { + return startPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartPlatform(@Nullable Platform startPlatform) { + this.startPlatform = startPlatform; + } + + + public ProjectTime endPlatform(@Nullable Platform endPlatform) { + + this.endPlatform = endPlatform; + return this; + } + + /** + * Get endPlatform + * @return endPlatform + */ + + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Platform getEndPlatform() { + return endPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndPlatform(@Nullable Platform endPlatform) { + this.endPlatform = endPlatform; + } + + + public ProjectTime lastModified(OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public ProjectTime lastModifiedBy(@Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public ProjectTime status(ProjectTimeStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public ProjectTimeStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(ProjectTimeStatus status) { + this.status = status; + } + + + public ProjectTime metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public ProjectTime putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTime projectTime = (ProjectTime) o; + return Objects.equals(this.id, projectTime.id) && + Objects.equals(this.start, projectTime.start) && + Objects.equals(this.end, projectTime.end) && + Objects.equals(this.breakTimeTotalMinutes, projectTime.breakTimeTotalMinutes) && + Objects.equals(this.breakTimes, projectTime.breakTimes) && + Objects.equals(this.duration, projectTime.duration) && + Objects.equals(this.changed, projectTime.changed) && + Objects.equals(this.notes, projectTime.notes) && + Objects.equals(this.user, projectTime.user) && + Objects.equals(this.task, projectTime.task) && + Objects.equals(this.billable, projectTime.billable) && + Objects.equals(this.startLocation, projectTime.startLocation) && + Objects.equals(this.endLocation, projectTime.endLocation) && + Objects.equals(this.startPlatform, projectTime.startPlatform) && + Objects.equals(this.endPlatform, projectTime.endPlatform) && + Objects.equals(this.lastModified, projectTime.lastModified) && + Objects.equals(this.lastModifiedBy, projectTime.lastModifiedBy) && + Objects.equals(this.status, projectTime.status) && + equalsNullable(this.metadata, projectTime.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, start, end, breakTimeTotalMinutes, breakTimes, duration, changed, notes, user, task, billable, startLocation, endLocation, startPlatform, endPlatform, lastModified, lastModifiedBy, status, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTime {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" task: ").append(toIndentedString(task)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeCreate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeCreate.java new file mode 100644 index 0000000..ca461b6 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeCreate.java @@ -0,0 +1,498 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.LocationCreate; +import com.timr.api.models.ProjectTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * ProjectTimeCreate + */ +@JsonPropertyOrder({ + ProjectTimeCreate.JSON_PROPERTY_START, + ProjectTimeCreate.JSON_PROPERTY_END, + ProjectTimeCreate.JSON_PROPERTY_BREAK_TIMES, + ProjectTimeCreate.JSON_PROPERTY_CHANGED, + ProjectTimeCreate.JSON_PROPERTY_NOTES, + ProjectTimeCreate.JSON_PROPERTY_TASK_ID, + ProjectTimeCreate.JSON_PROPERTY_BILLABLE, + ProjectTimeCreate.JSON_PROPERTY_STATUS, + ProjectTimeCreate.JSON_PROPERTY_METADATA, + ProjectTimeCreate.JSON_PROPERTY_USER_ID, + ProjectTimeCreate.JSON_PROPERTY_START_LOCATION, + ProjectTimeCreate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTimeCreate { + public static final String JSON_PROPERTY_START = "start"; + + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + + private JsonNullable<@Nullable List> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private Boolean changed; + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private JsonNullable<@Nullable String> notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TASK_ID = "task_id"; + + private String taskId; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + + private JsonNullable<@Nullable Boolean> billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + + private ProjectTimeStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_USER_ID = "user_id"; + + private String userId; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + + private JsonNullable<@Nullable LocationCreate> startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + + private JsonNullable<@Nullable LocationCreate> endLocation = JsonNullable.undefined(); + + public ProjectTimeCreate() { + } + + public ProjectTimeCreate start(OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(OffsetDateTime start) { + this.start = start; + } + + + public ProjectTimeCreate end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public ProjectTimeCreate breakTimes(@Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public ProjectTimeCreate addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable List> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public ProjectTimeCreate changed(Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(Boolean changed) { + this.changed = changed; + } + + + public ProjectTimeCreate notes(@Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public ProjectTimeCreate taskId(String taskId) { + + this.taskId = taskId; + return this; + } + + /** + * Get taskId + * @return taskId + */ + + @JsonProperty(value = JSON_PROPERTY_TASK_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getTaskId() { + return taskId; + } + + + @JsonProperty(value = JSON_PROPERTY_TASK_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + + public ProjectTimeCreate billable(@Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public ProjectTimeCreate status(ProjectTimeStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public ProjectTimeStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(ProjectTimeStatus status) { + this.status = status; + } + + + public ProjectTimeCreate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public ProjectTimeCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public ProjectTimeCreate userId(String userId) { + + this.userId = userId; + return this; + } + + /** + * Get userId + * @return userId + */ + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getUserId() { + return userId; + } + + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUserId(String userId) { + this.userId = userId; + } + + + public ProjectTimeCreate startLocation(@Nullable LocationCreate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationCreate> getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public ProjectTimeCreate endLocation(@Nullable LocationCreate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationCreate> getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTimeCreate projectTimeCreate = (ProjectTimeCreate) o; + return Objects.equals(this.start, projectTimeCreate.start) && + equalsNullable(this.end, projectTimeCreate.end) && + equalsNullable(this.breakTimes, projectTimeCreate.breakTimes) && + Objects.equals(this.changed, projectTimeCreate.changed) && + equalsNullable(this.notes, projectTimeCreate.notes) && + Objects.equals(this.taskId, projectTimeCreate.taskId) && + equalsNullable(this.billable, projectTimeCreate.billable) && + Objects.equals(this.status, projectTimeCreate.status) && + equalsNullable(this.metadata, projectTimeCreate.metadata) && + Objects.equals(this.userId, projectTimeCreate.userId) && + equalsNullable(this.startLocation, projectTimeCreate.startLocation) && + equalsNullable(this.endLocation, projectTimeCreate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, hashCodeNullable(end), hashCodeNullable(breakTimes), changed, hashCodeNullable(notes), taskId, hashCodeNullable(billable), status, hashCodeNullable(metadata), userId, hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTimeCreate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" taskId: ").append(toIndentedString(taskId)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeStatus.java b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeStatus.java new file mode 100644 index 0000000..4c3ea68 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeStatus.java @@ -0,0 +1,73 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Processing state of a Project Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + */ +public enum ProjectTimeStatus { + + RUNNING("running"), + + PAUSED("paused"), + + CHANGEABLE("changeable"), + + LOCKED("locked"), + + APPROVED("approved"), + + CLEARED("cleared"), + + CLOSED("closed"), + + ARCHIVED("archived"); + + private String value; + + ProjectTimeStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ProjectTimeStatus fromValue(String value) { + for (ProjectTimeStatus b : ProjectTimeStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeUpdate.java new file mode 100644 index 0000000..5f854a0 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeUpdate.java @@ -0,0 +1,457 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.LocationUpdate; +import com.timr.api.models.ProjectTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * ProjectTimeUpdate + */ +@JsonPropertyOrder({ + ProjectTimeUpdate.JSON_PROPERTY_START, + ProjectTimeUpdate.JSON_PROPERTY_END, + ProjectTimeUpdate.JSON_PROPERTY_BREAK_TIMES, + ProjectTimeUpdate.JSON_PROPERTY_CHANGED, + ProjectTimeUpdate.JSON_PROPERTY_NOTES, + ProjectTimeUpdate.JSON_PROPERTY_TASK_ID, + ProjectTimeUpdate.JSON_PROPERTY_BILLABLE, + ProjectTimeUpdate.JSON_PROPERTY_STATUS, + ProjectTimeUpdate.JSON_PROPERTY_METADATA, + ProjectTimeUpdate.JSON_PROPERTY_START_LOCATION, + ProjectTimeUpdate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTimeUpdate { + public static final String JSON_PROPERTY_START = "start"; + + private JsonNullable<@Nullable OffsetDateTime> start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + + private JsonNullable<@Nullable List> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private JsonNullable<@Nullable Boolean> changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private JsonNullable<@Nullable String> notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TASK_ID = "task_id"; + + private JsonNullable<@Nullable String> taskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + + private JsonNullable<@Nullable Boolean> billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + + private JsonNullable<@Nullable ProjectTimeStatus> status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + + private JsonNullable<@Nullable LocationUpdate> startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + + private JsonNullable<@Nullable LocationUpdate> endLocation = JsonNullable.undefined(); + + public ProjectTimeUpdate() { + } + + public ProjectTimeUpdate start(@Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public ProjectTimeUpdate end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public ProjectTimeUpdate breakTimes(@Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public ProjectTimeUpdate addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable List> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public ProjectTimeUpdate changed(@Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public ProjectTimeUpdate notes(@Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public ProjectTimeUpdate taskId(@Nullable String taskId) { + this.taskId = JsonNullable.of(taskId); + + return this; + } + + /** + * Get taskId + * @return taskId + */ + + @JsonProperty(value = JSON_PROPERTY_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getTaskId() { + return taskId; + } + + @JsonProperty(JSON_PROPERTY_TASK_ID) + public void setTaskId(JsonNullable taskId) { + this.taskId = taskId; + } + + + + public ProjectTimeUpdate billable(@Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public ProjectTimeUpdate status(@Nullable ProjectTimeStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable ProjectTimeStatus> getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public ProjectTimeUpdate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public ProjectTimeUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public ProjectTimeUpdate startLocation(@Nullable LocationUpdate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationUpdate> getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public ProjectTimeUpdate endLocation(@Nullable LocationUpdate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationUpdate> getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTimeUpdate projectTimeUpdate = (ProjectTimeUpdate) o; + return equalsNullable(this.start, projectTimeUpdate.start) && + equalsNullable(this.end, projectTimeUpdate.end) && + equalsNullable(this.breakTimes, projectTimeUpdate.breakTimes) && + equalsNullable(this.changed, projectTimeUpdate.changed) && + equalsNullable(this.notes, projectTimeUpdate.notes) && + equalsNullable(this.taskId, projectTimeUpdate.taskId) && + equalsNullable(this.billable, projectTimeUpdate.billable) && + equalsNullable(this.status, projectTimeUpdate.status) && + equalsNullable(this.metadata, projectTimeUpdate.metadata) && + equalsNullable(this.startLocation, projectTimeUpdate.startLocation) && + equalsNullable(this.endLocation, projectTimeUpdate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(changed), hashCodeNullable(notes), hashCodeNullable(taskId), hashCodeNullable(billable), hashCodeNullable(status), hashCodeNullable(metadata), hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTimeUpdate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" taskId: ").append(toIndentedString(taskId)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeUpsert.java b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeUpsert.java new file mode 100644 index 0000000..a20d8c6 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimeUpsert.java @@ -0,0 +1,396 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.ProjectTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * ProjectTimeUpsert + */ +@JsonPropertyOrder({ + ProjectTimeUpsert.JSON_PROPERTY_START, + ProjectTimeUpsert.JSON_PROPERTY_END, + ProjectTimeUpsert.JSON_PROPERTY_BREAK_TIMES, + ProjectTimeUpsert.JSON_PROPERTY_CHANGED, + ProjectTimeUpsert.JSON_PROPERTY_NOTES, + ProjectTimeUpsert.JSON_PROPERTY_TASK_ID, + ProjectTimeUpsert.JSON_PROPERTY_BILLABLE, + ProjectTimeUpsert.JSON_PROPERTY_STATUS, + ProjectTimeUpsert.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTimeUpsert { + public static final String JSON_PROPERTY_START = "start"; + + private JsonNullable<@Nullable OffsetDateTime> start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + + private JsonNullable<@Nullable List> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private JsonNullable<@Nullable Boolean> changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private JsonNullable<@Nullable String> notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TASK_ID = "task_id"; + + private JsonNullable<@Nullable String> taskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + + private JsonNullable<@Nullable Boolean> billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + + private JsonNullable<@Nullable ProjectTimeStatus> status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public ProjectTimeUpsert() { + } + + public ProjectTimeUpsert start(@Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public ProjectTimeUpsert end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public ProjectTimeUpsert breakTimes(@Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public ProjectTimeUpsert addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable List> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public ProjectTimeUpsert changed(@Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public ProjectTimeUpsert notes(@Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public ProjectTimeUpsert taskId(@Nullable String taskId) { + this.taskId = JsonNullable.of(taskId); + + return this; + } + + /** + * Get taskId + * @return taskId + */ + + @JsonProperty(value = JSON_PROPERTY_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getTaskId() { + return taskId; + } + + @JsonProperty(JSON_PROPERTY_TASK_ID) + public void setTaskId(JsonNullable taskId) { + this.taskId = taskId; + } + + + + public ProjectTimeUpsert billable(@Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public ProjectTimeUpsert status(@Nullable ProjectTimeStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable ProjectTimeStatus> getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public ProjectTimeUpsert metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public ProjectTimeUpsert putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTimeUpsert projectTimeUpsert = (ProjectTimeUpsert) o; + return equalsNullable(this.start, projectTimeUpsert.start) && + equalsNullable(this.end, projectTimeUpsert.end) && + equalsNullable(this.breakTimes, projectTimeUpsert.breakTimes) && + equalsNullable(this.changed, projectTimeUpsert.changed) && + equalsNullable(this.notes, projectTimeUpsert.notes) && + equalsNullable(this.taskId, projectTimeUpsert.taskId) && + equalsNullable(this.billable, projectTimeUpsert.billable) && + equalsNullable(this.status, projectTimeUpsert.status) && + equalsNullable(this.metadata, projectTimeUpsert.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(changed), hashCodeNullable(notes), hashCodeNullable(taskId), hashCodeNullable(billable), hashCodeNullable(status), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTimeUpsert {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" taskId: ").append(toIndentedString(taskId)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimesPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimesPage.java new file mode 100644 index 0000000..73b7059 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimesPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.ProjectTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * ProjectTimesPage + */ +@JsonPropertyOrder({ + ProjectTimesPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + ProjectTimesPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTimesPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public ProjectTimesPage() { + } + + public ProjectTimesPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public ProjectTimesPage data(List data) { + + this.data = data; + return this; + } + + public ProjectTimesPage addDataItem(ProjectTime dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTimesPage projectTimesPage = (ProjectTimesPage) o; + return Objects.equals(this.nextPageToken, projectTimesPage.nextPageToken) && + Objects.equals(this.data, projectTimesPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTimesPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimesSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimesSortColumn.java new file mode 100644 index 0000000..36ce6c2 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/ProjectTimesSortColumn.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Project Times. + */ +public enum ProjectTimesSortColumn { + + START("start"), + + LAST_MODIFIED("last_modified"); + + private String value; + + ProjectTimesSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ProjectTimesSortColumn fromValue(String value) { + for (ProjectTimesSortColumn b : ProjectTimesSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/RecordingLockType.java b/sdk/java-restclient/src/main/java/com/timr/api/models/RecordingLockType.java new file mode 100644 index 0000000..9e7a594 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/RecordingLockType.java @@ -0,0 +1,65 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Whether the assigned User may record on the Task, and where the lock comes from. `recordable` allows recording; `locked_automatically` follows the Task's lock date; `locked_manually` and `unlocked_manually` are explicit overrides for this assignment. + */ +public enum RecordingLockType { + + RECORDABLE("recordable"), + + LOCKED_AUTOMATICALLY("locked_automatically"), + + LOCKED_MANUALLY("locked_manually"), + + UNLOCKED_MANUALLY("unlocked_manually"); + + private String value; + + RecordingLockType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static RecordingLockType fromValue(String value) { + for (RecordingLockType b : RecordingLockType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/RecordingModeUser.java b/sdk/java-restclient/src/main/java/com/timr/api/models/RecordingModeUser.java new file mode 100644 index 0000000..d5cc567 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/RecordingModeUser.java @@ -0,0 +1,63 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Whether a User may record this Working Time Type themselves. Only meaningful for day-based types. + */ +public enum RecordingModeUser { + + NOT_ALLOWED("not_allowed"), + + ALLOWED("allowed"), + + BY_REQUEST("by_request"); + + private String value; + + RecordingModeUser(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static RecordingModeUser fromValue(String value) { + for (RecordingModeUser b : RecordingModeUser.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/SortDirection.java b/sdk/java-restclient/src/main/java/com/timr/api/models/SortDirection.java new file mode 100644 index 0000000..ed7c864 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/SortDirection.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort direction — `asc` for ascending, `dsc` for descending. + */ +public enum SortDirection { + + ASC("asc"), + + DSC("dsc"); + + private String value; + + SortDirection(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static SortDirection fromValue(String value) { + for (SortDirection b : SortDirection.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Task.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Task.java new file mode 100644 index 0000000..fa32e84 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Task.java @@ -0,0 +1,1050 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningType; +import com.timr.api.models.TaskLocation; +import com.timr.api.models.TaskPartial; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A task, placed in the tree by `parent_task`, with the full path from the root in `breadcrumbs`. `bookable` and `billable` control recording and invoicing; `lock_date`, time windows and location constrain what may be recorded. + */ +@JsonPropertyOrder({ + Task.JSON_PROPERTY_ID, + Task.JSON_PROPERTY_NAME, + Task.JSON_PROPERTY_BREADCRUMBS, + Task.JSON_PROPERTY_EXTERNAL_ID, + Task.JSON_PROPERTY_PARENT_TASK, + Task.JSON_PROPERTY_DESCRIPTION, + Task.JSON_PROPERTY_DESCRIPTION_EXTERNAL, + Task.JSON_PROPERTY_BOOKABLE, + Task.JSON_PROPERTY_BILLABLE, + Task.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + Task.JSON_PROPERTY_START_DATE, + Task.JSON_PROPERTY_END_DATE, + Task.JSON_PROPERTY_LOCK_DATE, + Task.JSON_PROPERTY_EARLIEST_START_TIME, + Task.JSON_PROPERTY_LATEST_END_TIME, + Task.JSON_PROPERTY_ACTIVE_FROM, + Task.JSON_PROPERTY_ACTIVE_TO, + Task.JSON_PROPERTY_BUDGET_INHERITED, + Task.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + Task.JSON_PROPERTY_BUDGET_HOURS_PLANNED, + Task.JSON_PROPERTY_BUDGET_HOURLY_RATE, + Task.JSON_PROPERTY_BUDGET_PLANNED, + Task.JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, + Task.JSON_PROPERTY_LOCATION_INHERITED, + Task.JSON_PROPERTY_LOCATION, + Task.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + Task.JSON_PROPERTY_CUSTOM_FIELD1, + Task.JSON_PROPERTY_CUSTOM_FIELD2, + Task.JSON_PROPERTY_CUSTOM_FIELD3, + Task.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Task { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public static final String JSON_PROPERTY_PARENT_TASK = "parent_task"; + + private @Nullable TaskPartial parentTask; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private @Nullable String description; + + public static final String JSON_PROPERTY_DESCRIPTION_EXTERNAL = "description_external"; + + private @Nullable String descriptionExternal; + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + + private Boolean bookable; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + + private Boolean billable; + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + + private Boolean projectTimeNotesRequired; + + public static final String JSON_PROPERTY_START_DATE = "start_date"; + + private @Nullable LocalDate startDate; + + public static final String JSON_PROPERTY_END_DATE = "end_date"; + + private @Nullable LocalDate endDate; + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + + private JsonNullable<@Nullable LocalDate> lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + + private JsonNullable<@Nullable String> earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + + private JsonNullable<@Nullable String> latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACTIVE_FROM = "active_from"; + + private @Nullable LocalDate activeFrom; + + public static final String JSON_PROPERTY_ACTIVE_TO = "active_to"; + + private @Nullable LocalDate activeTo; + + public static final String JSON_PROPERTY_BUDGET_INHERITED = "budget_inherited"; + + private JsonNullable<@Nullable Boolean> budgetInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + + private JsonNullable<@Nullable BudgetPlanningType> budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURS_PLANNED = "budget_hours_planned"; + + private JsonNullable<@Nullable BigDecimal> budgetHoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURLY_RATE = "budget_hourly_rate"; + + private JsonNullable<@Nullable BigDecimal> budgetHourlyRate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNED = "budget_planned"; + + private JsonNullable<@Nullable BigDecimal> budgetPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES = "budget_include_non_billable_project_times"; + + private JsonNullable<@Nullable Boolean> budgetIncludeNonBillableProjectTimes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + + private JsonNullable<@Nullable Boolean> locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + + private JsonNullable<@Nullable TaskLocation> location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + + private JsonNullable<@Nullable Integer> locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + + private @Nullable String customField1; + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + + private @Nullable String customField2; + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + + private @Nullable String customField3; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public Task() { + } + + public Task id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public Task name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public Task breadcrumbs(String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public Task externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + public Task parentTask(@Nullable TaskPartial parentTask) { + + this.parentTask = parentTask; + return this; + } + + /** + * Get parentTask + * @return parentTask + */ + + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable TaskPartial getParentTask() { + return parentTask; + } + + + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setParentTask(@Nullable TaskPartial parentTask) { + this.parentTask = parentTask; + } + + + public Task description(@Nullable String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@Nullable String description) { + this.description = description; + } + + + public Task descriptionExternal(@Nullable String descriptionExternal) { + + this.descriptionExternal = descriptionExternal; + return this; + } + + /** + * Get descriptionExternal + * @return descriptionExternal + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getDescriptionExternal() { + return descriptionExternal; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescriptionExternal(@Nullable String descriptionExternal) { + this.descriptionExternal = descriptionExternal; + } + + + public Task bookable(Boolean bookable) { + + this.bookable = bookable; + return this; + } + + /** + * Get bookable + * @return bookable + */ + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBookable() { + return bookable; + } + + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBookable(Boolean bookable) { + this.bookable = bookable; + } + + + public Task billable(Boolean billable) { + + this.billable = billable; + return this; + } + + /** + * Get billable + * @return billable + */ + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBillable() { + return billable; + } + + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBillable(Boolean billable) { + this.billable = billable; + } + + + public Task projectTimeNotesRequired(Boolean projectTimeNotesRequired) { + + this.projectTimeNotesRequired = projectTimeNotesRequired; + return this; + } + + /** + * Get projectTimeNotesRequired + * @return projectTimeNotesRequired + */ + + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setProjectTimeNotesRequired(Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + public Task startDate(@Nullable LocalDate startDate) { + + this.startDate = startDate; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return startDate + */ + + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable LocalDate getStartDate() { + return startDate; + } + + + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartDate(@Nullable LocalDate startDate) { + this.startDate = startDate; + } + + + public Task endDate(@Nullable LocalDate endDate) { + + this.endDate = endDate; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return endDate + */ + + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable LocalDate getEndDate() { + return endDate; + } + + + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndDate(@Nullable LocalDate endDate) { + this.endDate = endDate; + } + + + public Task lockDate(@Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return lockDate + */ + + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public Task earliestStartTime(@Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * time of day (ISO-8601) + * @return earliestStartTime + */ + + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public Task latestEndTime(@Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * time of day (ISO-8601) + * @return latestEndTime + */ + + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public Task activeFrom(@Nullable LocalDate activeFrom) { + + this.activeFrom = activeFrom; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return activeFrom + */ + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_FROM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable LocalDate getActiveFrom() { + return activeFrom; + } + + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_FROM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActiveFrom(@Nullable LocalDate activeFrom) { + this.activeFrom = activeFrom; + } + + + public Task activeTo(@Nullable LocalDate activeTo) { + + this.activeTo = activeTo; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return activeTo + */ + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_TO, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable LocalDate getActiveTo() { + return activeTo; + } + + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_TO, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActiveTo(@Nullable LocalDate activeTo) { + this.activeTo = activeTo; + } + + + public Task budgetInherited(@Nullable Boolean budgetInherited) { + this.budgetInherited = JsonNullable.of(budgetInherited); + + return this; + } + + /** + * Get budgetInherited + * @return budgetInherited + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBudgetInherited() { + return budgetInherited; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INHERITED) + public void setBudgetInherited(JsonNullable budgetInherited) { + this.budgetInherited = budgetInherited; + } + + + + public Task budgetPlanningType(@Nullable BudgetPlanningType budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * Get budgetPlanningType + * @return budgetPlanningType + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BudgetPlanningType> getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public Task budgetHoursPlanned(@Nullable BigDecimal budgetHoursPlanned) { + this.budgetHoursPlanned = JsonNullable.of(budgetHoursPlanned); + + return this; + } + + /** + * Get budgetHoursPlanned + * @return budgetHoursPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetHoursPlanned() { + return budgetHoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURS_PLANNED) + public void setBudgetHoursPlanned(JsonNullable budgetHoursPlanned) { + this.budgetHoursPlanned = budgetHoursPlanned; + } + + + + public Task budgetHourlyRate(@Nullable BigDecimal budgetHourlyRate) { + this.budgetHourlyRate = JsonNullable.of(budgetHourlyRate); + + return this; + } + + /** + * Get budgetHourlyRate + * @return budgetHourlyRate + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURLY_RATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetHourlyRate() { + return budgetHourlyRate; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURLY_RATE) + public void setBudgetHourlyRate(JsonNullable budgetHourlyRate) { + this.budgetHourlyRate = budgetHourlyRate; + } + + + + public Task budgetPlanned(@Nullable BigDecimal budgetPlanned) { + this.budgetPlanned = JsonNullable.of(budgetPlanned); + + return this; + } + + /** + * Get budgetPlanned + * @return budgetPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetPlanned() { + return budgetPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNED) + public void setBudgetPlanned(JsonNullable budgetPlanned) { + this.budgetPlanned = budgetPlanned; + } + + + + public Task budgetIncludeNonBillableProjectTimes(@Nullable Boolean budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = JsonNullable.of(budgetIncludeNonBillableProjectTimes); + + return this; + } + + /** + * Get budgetIncludeNonBillableProjectTimes + * @return budgetIncludeNonBillableProjectTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBudgetIncludeNonBillableProjectTimes() { + return budgetIncludeNonBillableProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES) + public void setBudgetIncludeNonBillableProjectTimes(JsonNullable budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes; + } + + + + public Task locationInherited(@Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * Get locationInherited + * @return locationInherited + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public Task location(@Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable TaskLocation> getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public Task locationRestrictionRadiusMeters(@Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * Get locationRestrictionRadiusMeters + * @return locationRestrictionRadiusMeters + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Integer> getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public Task customField1(@Nullable String customField1) { + + this.customField1 = customField1; + return this; + } + + /** + * Get customField1 + * @return customField1 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getCustomField1() { + return customField1; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField1(@Nullable String customField1) { + this.customField1 = customField1; + } + + + public Task customField2(@Nullable String customField2) { + + this.customField2 = customField2; + return this; + } + + /** + * Get customField2 + * @return customField2 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getCustomField2() { + return customField2; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField2(@Nullable String customField2) { + this.customField2 = customField2; + } + + + public Task customField3(@Nullable String customField3) { + + this.customField3 = customField3; + return this; + } + + /** + * Get customField3 + * @return customField3 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getCustomField3() { + return customField3; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField3(@Nullable String customField3) { + this.customField3 = customField3; + } + + + public Task metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public Task putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Task task = (Task) o; + return Objects.equals(this.id, task.id) && + Objects.equals(this.name, task.name) && + Objects.equals(this.breadcrumbs, task.breadcrumbs) && + Objects.equals(this.externalId, task.externalId) && + Objects.equals(this.parentTask, task.parentTask) && + Objects.equals(this.description, task.description) && + Objects.equals(this.descriptionExternal, task.descriptionExternal) && + Objects.equals(this.bookable, task.bookable) && + Objects.equals(this.billable, task.billable) && + Objects.equals(this.projectTimeNotesRequired, task.projectTimeNotesRequired) && + Objects.equals(this.startDate, task.startDate) && + Objects.equals(this.endDate, task.endDate) && + equalsNullable(this.lockDate, task.lockDate) && + equalsNullable(this.earliestStartTime, task.earliestStartTime) && + equalsNullable(this.latestEndTime, task.latestEndTime) && + Objects.equals(this.activeFrom, task.activeFrom) && + Objects.equals(this.activeTo, task.activeTo) && + equalsNullable(this.budgetInherited, task.budgetInherited) && + equalsNullable(this.budgetPlanningType, task.budgetPlanningType) && + equalsNullable(this.budgetHoursPlanned, task.budgetHoursPlanned) && + equalsNullable(this.budgetHourlyRate, task.budgetHourlyRate) && + equalsNullable(this.budgetPlanned, task.budgetPlanned) && + equalsNullable(this.budgetIncludeNonBillableProjectTimes, task.budgetIncludeNonBillableProjectTimes) && + equalsNullable(this.locationInherited, task.locationInherited) && + equalsNullable(this.location, task.location) && + equalsNullable(this.locationRestrictionRadiusMeters, task.locationRestrictionRadiusMeters) && + Objects.equals(this.customField1, task.customField1) && + Objects.equals(this.customField2, task.customField2) && + Objects.equals(this.customField3, task.customField3) && + equalsNullable(this.metadata, task.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId, parentTask, description, descriptionExternal, bookable, billable, projectTimeNotesRequired, startDate, endDate, hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), activeFrom, activeTo, hashCodeNullable(budgetInherited), hashCodeNullable(budgetPlanningType), hashCodeNullable(budgetHoursPlanned), hashCodeNullable(budgetHourlyRate), hashCodeNullable(budgetPlanned), hashCodeNullable(budgetIncludeNonBillableProjectTimes), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), customField1, customField2, customField3, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Task {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" parentTask: ").append(toIndentedString(parentTask)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" activeFrom: ").append(toIndentedString(activeFrom)).append("\n"); + sb.append(" activeTo: ").append(toIndentedString(activeTo)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskBase.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskBase.java new file mode 100644 index 0000000..a1727e3 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskBase.java @@ -0,0 +1,864 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningTypeRequest; +import com.timr.api.models.TaskLocation; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskBase + */ +@JsonPropertyOrder({ + TaskBase.JSON_PROPERTY_NAME, + TaskBase.JSON_PROPERTY_PARENT_TASK_ID, + TaskBase.JSON_PROPERTY_EXTERNAL_ID, + TaskBase.JSON_PROPERTY_DESCRIPTION, + TaskBase.JSON_PROPERTY_DESCRIPTION_EXTERNAL, + TaskBase.JSON_PROPERTY_BOOKABLE, + TaskBase.JSON_PROPERTY_BILLABLE, + TaskBase.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + TaskBase.JSON_PROPERTY_START_DATE, + TaskBase.JSON_PROPERTY_END_DATE, + TaskBase.JSON_PROPERTY_LOCK_DATE, + TaskBase.JSON_PROPERTY_EARLIEST_START_TIME, + TaskBase.JSON_PROPERTY_LATEST_END_TIME, + TaskBase.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + TaskBase.JSON_PROPERTY_BUDGET_HOURS_PLANNED, + TaskBase.JSON_PROPERTY_BUDGET_HOURLY_RATE, + TaskBase.JSON_PROPERTY_BUDGET_PLANNED, + TaskBase.JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, + TaskBase.JSON_PROPERTY_LOCATION_INHERITED, + TaskBase.JSON_PROPERTY_LOCATION, + TaskBase.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + TaskBase.JSON_PROPERTY_CUSTOM_FIELD1, + TaskBase.JSON_PROPERTY_CUSTOM_FIELD2, + TaskBase.JSON_PROPERTY_CUSTOM_FIELD3, + TaskBase.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskBase { + public static final String JSON_PROPERTY_NAME = "name"; + + private JsonNullable<@Nullable String> name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PARENT_TASK_ID = "parent_task_id"; + + private JsonNullable<@Nullable String> parentTaskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private JsonNullable<@Nullable String> externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private JsonNullable<@Nullable String> description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION_EXTERNAL = "description_external"; + + private JsonNullable<@Nullable String> descriptionExternal = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + + private JsonNullable<@Nullable Boolean> bookable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + + private JsonNullable<@Nullable Boolean> billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + + private JsonNullable<@Nullable Boolean> projectTimeNotesRequired = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_DATE = "start_date"; + + private JsonNullable<@Nullable LocalDate> startDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_DATE = "end_date"; + + private JsonNullable<@Nullable LocalDate> endDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + + private JsonNullable<@Nullable LocalDate> lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + + private JsonNullable<@Nullable String> earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + + private JsonNullable<@Nullable String> latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + + private JsonNullable<@Nullable BudgetPlanningTypeRequest> budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURS_PLANNED = "budget_hours_planned"; + + private JsonNullable<@Nullable BigDecimal> budgetHoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURLY_RATE = "budget_hourly_rate"; + + private JsonNullable<@Nullable BigDecimal> budgetHourlyRate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNED = "budget_planned"; + + private JsonNullable<@Nullable BigDecimal> budgetPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES = "budget_include_non_billable_project_times"; + + private JsonNullable<@Nullable Boolean> budgetIncludeNonBillableProjectTimes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + + private JsonNullable<@Nullable Boolean> locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + + private JsonNullable<@Nullable TaskLocation> location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + + private JsonNullable<@Nullable Integer> locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + + private JsonNullable<@Nullable String> customField1 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + + private JsonNullable<@Nullable String> customField2 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + + private JsonNullable<@Nullable String> customField3 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public TaskBase() { + } + + public TaskBase name(@Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public TaskBase parentTaskId(@Nullable String parentTaskId) { + this.parentTaskId = JsonNullable.of(parentTaskId); + + return this; + } + + /** + * returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @return parentTaskId + */ + + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getParentTaskId() { + return parentTaskId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TASK_ID) + public void setParentTaskId(JsonNullable parentTaskId) { + this.parentTaskId = parentTaskId; + } + + + + public TaskBase externalId(@Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public TaskBase description(@Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TaskBase descriptionExternal(@Nullable String descriptionExternal) { + this.descriptionExternal = JsonNullable.of(descriptionExternal); + + return this; + } + + /** + * Get descriptionExternal + * @return descriptionExternal + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDescriptionExternal() { + return descriptionExternal; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION_EXTERNAL) + public void setDescriptionExternal(JsonNullable descriptionExternal) { + this.descriptionExternal = descriptionExternal; + } + + + + public TaskBase bookable(@Nullable Boolean bookable) { + this.bookable = JsonNullable.of(bookable); + + return this; + } + + /** + * when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @return bookable + */ + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBookable() { + return bookable; + } + + @JsonProperty(JSON_PROPERTY_BOOKABLE) + public void setBookable(JsonNullable bookable) { + this.bookable = bookable; + } + + + + public TaskBase billable(@Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public TaskBase projectTimeNotesRequired(@Nullable Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = JsonNullable.of(projectTimeNotesRequired); + + return this; + } + + /** + * depending on this property project times booked on this task have to include notes or not + * @return projectTimeNotesRequired + */ + + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + @JsonProperty(JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED) + public void setProjectTimeNotesRequired(JsonNullable projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + + public TaskBase startDate(@Nullable LocalDate startDate) { + this.startDate = JsonNullable.of(startDate); + + return this; + } + + /** + * the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return startDate + */ + + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getStartDate() { + return startDate; + } + + @JsonProperty(JSON_PROPERTY_START_DATE) + public void setStartDate(JsonNullable startDate) { + this.startDate = startDate; + } + + + + public TaskBase endDate(@Nullable LocalDate endDate) { + this.endDate = JsonNullable.of(endDate); + + return this; + } + + /** + * the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return endDate + */ + + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getEndDate() { + return endDate; + } + + @JsonProperty(JSON_PROPERTY_END_DATE) + public void setEndDate(JsonNullable endDate) { + this.endDate = endDate; + } + + + + public TaskBase lockDate(@Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + * @return lockDate + */ + + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public TaskBase earliestStartTime(@Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked before this time + * @return earliestStartTime + */ + + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public TaskBase latestEndTime(@Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked after this time + * @return latestEndTime + */ + + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public TaskBase budgetPlanningType(@Nullable BudgetPlanningTypeRequest budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * @return budgetPlanningType + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BudgetPlanningTypeRequest> getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public TaskBase budgetHoursPlanned(@Nullable BigDecimal budgetHoursPlanned) { + this.budgetHoursPlanned = JsonNullable.of(budgetHoursPlanned); + + return this; + } + + /** + * how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetHoursPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetHoursPlanned() { + return budgetHoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURS_PLANNED) + public void setBudgetHoursPlanned(JsonNullable budgetHoursPlanned) { + this.budgetHoursPlanned = budgetHoursPlanned; + } + + + + public TaskBase budgetHourlyRate(@Nullable BigDecimal budgetHourlyRate) { + this.budgetHourlyRate = JsonNullable.of(budgetHourlyRate); + + return this; + } + + /** + * depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * @return budgetHourlyRate + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURLY_RATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetHourlyRate() { + return budgetHourlyRate; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURLY_RATE) + public void setBudgetHourlyRate(JsonNullable budgetHourlyRate) { + this.budgetHourlyRate = budgetHourlyRate; + } + + + + public TaskBase budgetPlanned(@Nullable BigDecimal budgetPlanned) { + this.budgetPlanned = JsonNullable.of(budgetPlanned); + + return this; + } + + /** + * the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetPlanned() { + return budgetPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNED) + public void setBudgetPlanned(JsonNullable budgetPlanned) { + this.budgetPlanned = budgetPlanned; + } + + + + public TaskBase budgetIncludeNonBillableProjectTimes(@Nullable Boolean budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = JsonNullable.of(budgetIncludeNonBillableProjectTimes); + + return this; + } + + /** + * set this property to true, if you want to include not billable hours for all project times booked on this task + * @return budgetIncludeNonBillableProjectTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBudgetIncludeNonBillableProjectTimes() { + return budgetIncludeNonBillableProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES) + public void setBudgetIncludeNonBillableProjectTimes(JsonNullable budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes; + } + + + + public TaskBase locationInherited(@Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @return locationInherited + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public TaskBase location(@Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable TaskLocation> getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public TaskBase locationRestrictionRadiusMeters(@Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @return locationRestrictionRadiusMeters + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Integer> getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public TaskBase customField1(@Nullable String customField1) { + this.customField1 = JsonNullable.of(customField1); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField1 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getCustomField1() { + return customField1; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD1) + public void setCustomField1(JsonNullable customField1) { + this.customField1 = customField1; + } + + + + public TaskBase customField2(@Nullable String customField2) { + this.customField2 = JsonNullable.of(customField2); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField2 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getCustomField2() { + return customField2; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD2) + public void setCustomField2(JsonNullable customField2) { + this.customField2 = customField2; + } + + + + public TaskBase customField3(@Nullable String customField3) { + this.customField3 = JsonNullable.of(customField3); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField3 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getCustomField3() { + return customField3; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD3) + public void setCustomField3(JsonNullable customField3) { + this.customField3 = customField3; + } + + + + public TaskBase metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public TaskBase putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskBase taskBase = (TaskBase) o; + return equalsNullable(this.name, taskBase.name) && + equalsNullable(this.parentTaskId, taskBase.parentTaskId) && + equalsNullable(this.externalId, taskBase.externalId) && + equalsNullable(this.description, taskBase.description) && + equalsNullable(this.descriptionExternal, taskBase.descriptionExternal) && + equalsNullable(this.bookable, taskBase.bookable) && + equalsNullable(this.billable, taskBase.billable) && + equalsNullable(this.projectTimeNotesRequired, taskBase.projectTimeNotesRequired) && + equalsNullable(this.startDate, taskBase.startDate) && + equalsNullable(this.endDate, taskBase.endDate) && + equalsNullable(this.lockDate, taskBase.lockDate) && + equalsNullable(this.earliestStartTime, taskBase.earliestStartTime) && + equalsNullable(this.latestEndTime, taskBase.latestEndTime) && + equalsNullable(this.budgetPlanningType, taskBase.budgetPlanningType) && + equalsNullable(this.budgetHoursPlanned, taskBase.budgetHoursPlanned) && + equalsNullable(this.budgetHourlyRate, taskBase.budgetHourlyRate) && + equalsNullable(this.budgetPlanned, taskBase.budgetPlanned) && + equalsNullable(this.budgetIncludeNonBillableProjectTimes, taskBase.budgetIncludeNonBillableProjectTimes) && + equalsNullable(this.locationInherited, taskBase.locationInherited) && + equalsNullable(this.location, taskBase.location) && + equalsNullable(this.locationRestrictionRadiusMeters, taskBase.locationRestrictionRadiusMeters) && + equalsNullable(this.customField1, taskBase.customField1) && + equalsNullable(this.customField2, taskBase.customField2) && + equalsNullable(this.customField3, taskBase.customField3) && + equalsNullable(this.metadata, taskBase.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(name), hashCodeNullable(parentTaskId), hashCodeNullable(externalId), hashCodeNullable(description), hashCodeNullable(descriptionExternal), hashCodeNullable(bookable), hashCodeNullable(billable), hashCodeNullable(projectTimeNotesRequired), hashCodeNullable(startDate), hashCodeNullable(endDate), hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), hashCodeNullable(budgetPlanningType), hashCodeNullable(budgetHoursPlanned), hashCodeNullable(budgetHourlyRate), hashCodeNullable(budgetPlanned), hashCodeNullable(budgetIncludeNonBillableProjectTimes), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), hashCodeNullable(customField1), hashCodeNullable(customField2), hashCodeNullable(customField3), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskBase {\n"); + sb.append(" parentTaskId: ").append(toIndentedString(parentTaskId)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n"); + sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskCreate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskCreate.java new file mode 100644 index 0000000..02079fc --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskCreate.java @@ -0,0 +1,870 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningTypeRequest; +import com.timr.api.models.TaskLocation; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskCreate + */ +@JsonPropertyOrder({ + TaskCreate.JSON_PROPERTY_NAME, + TaskCreate.JSON_PROPERTY_PARENT_TASK_ID, + TaskCreate.JSON_PROPERTY_EXTERNAL_ID, + TaskCreate.JSON_PROPERTY_DESCRIPTION, + TaskCreate.JSON_PROPERTY_DESCRIPTION_EXTERNAL, + TaskCreate.JSON_PROPERTY_BOOKABLE, + TaskCreate.JSON_PROPERTY_BILLABLE, + TaskCreate.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + TaskCreate.JSON_PROPERTY_START_DATE, + TaskCreate.JSON_PROPERTY_END_DATE, + TaskCreate.JSON_PROPERTY_LOCK_DATE, + TaskCreate.JSON_PROPERTY_EARLIEST_START_TIME, + TaskCreate.JSON_PROPERTY_LATEST_END_TIME, + TaskCreate.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + TaskCreate.JSON_PROPERTY_BUDGET_HOURS_PLANNED, + TaskCreate.JSON_PROPERTY_BUDGET_HOURLY_RATE, + TaskCreate.JSON_PROPERTY_BUDGET_PLANNED, + TaskCreate.JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, + TaskCreate.JSON_PROPERTY_LOCATION_INHERITED, + TaskCreate.JSON_PROPERTY_LOCATION, + TaskCreate.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + TaskCreate.JSON_PROPERTY_CUSTOM_FIELD1, + TaskCreate.JSON_PROPERTY_CUSTOM_FIELD2, + TaskCreate.JSON_PROPERTY_CUSTOM_FIELD3, + TaskCreate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskCreate { + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_PARENT_TASK_ID = "parent_task_id"; + + private JsonNullable<@Nullable String> parentTaskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private JsonNullable<@Nullable String> externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private JsonNullable<@Nullable String> description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION_EXTERNAL = "description_external"; + + private JsonNullable<@Nullable String> descriptionExternal = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + + private Boolean bookable; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + + private Boolean billable; + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + + private JsonNullable<@Nullable Boolean> projectTimeNotesRequired = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_DATE = "start_date"; + + private JsonNullable<@Nullable LocalDate> startDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_DATE = "end_date"; + + private JsonNullable<@Nullable LocalDate> endDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + + private JsonNullable<@Nullable LocalDate> lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + + private JsonNullable<@Nullable String> earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + + private JsonNullable<@Nullable String> latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + + private JsonNullable<@Nullable BudgetPlanningTypeRequest> budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURS_PLANNED = "budget_hours_planned"; + + private JsonNullable<@Nullable BigDecimal> budgetHoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURLY_RATE = "budget_hourly_rate"; + + private JsonNullable<@Nullable BigDecimal> budgetHourlyRate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNED = "budget_planned"; + + private JsonNullable<@Nullable BigDecimal> budgetPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES = "budget_include_non_billable_project_times"; + + private JsonNullable<@Nullable Boolean> budgetIncludeNonBillableProjectTimes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + + private JsonNullable<@Nullable Boolean> locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + + private JsonNullable<@Nullable TaskLocation> location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + + private JsonNullable<@Nullable Integer> locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + + private JsonNullable<@Nullable String> customField1 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + + private JsonNullable<@Nullable String> customField2 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + + private JsonNullable<@Nullable String> customField3 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public TaskCreate() { + } + + public TaskCreate name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public TaskCreate parentTaskId(@Nullable String parentTaskId) { + this.parentTaskId = JsonNullable.of(parentTaskId); + + return this; + } + + /** + * returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @return parentTaskId + */ + + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getParentTaskId() { + return parentTaskId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TASK_ID) + public void setParentTaskId(JsonNullable parentTaskId) { + this.parentTaskId = parentTaskId; + } + + + + public TaskCreate externalId(@Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public TaskCreate description(@Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TaskCreate descriptionExternal(@Nullable String descriptionExternal) { + this.descriptionExternal = JsonNullable.of(descriptionExternal); + + return this; + } + + /** + * Get descriptionExternal + * @return descriptionExternal + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDescriptionExternal() { + return descriptionExternal; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION_EXTERNAL) + public void setDescriptionExternal(JsonNullable descriptionExternal) { + this.descriptionExternal = descriptionExternal; + } + + + + public TaskCreate bookable(Boolean bookable) { + + this.bookable = bookable; + return this; + } + + /** + * when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @return bookable + */ + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBookable() { + return bookable; + } + + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBookable(Boolean bookable) { + this.bookable = bookable; + } + + + public TaskCreate billable(Boolean billable) { + + this.billable = billable; + return this; + } + + /** + * Get billable + * @return billable + */ + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBillable() { + return billable; + } + + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBillable(Boolean billable) { + this.billable = billable; + } + + + public TaskCreate projectTimeNotesRequired(@Nullable Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = JsonNullable.of(projectTimeNotesRequired); + + return this; + } + + /** + * depending on this property project times booked on this task have to include notes or not + * @return projectTimeNotesRequired + */ + + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + @JsonProperty(JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED) + public void setProjectTimeNotesRequired(JsonNullable projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + + public TaskCreate startDate(@Nullable LocalDate startDate) { + this.startDate = JsonNullable.of(startDate); + + return this; + } + + /** + * the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return startDate + */ + + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getStartDate() { + return startDate; + } + + @JsonProperty(JSON_PROPERTY_START_DATE) + public void setStartDate(JsonNullable startDate) { + this.startDate = startDate; + } + + + + public TaskCreate endDate(@Nullable LocalDate endDate) { + this.endDate = JsonNullable.of(endDate); + + return this; + } + + /** + * the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return endDate + */ + + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getEndDate() { + return endDate; + } + + @JsonProperty(JSON_PROPERTY_END_DATE) + public void setEndDate(JsonNullable endDate) { + this.endDate = endDate; + } + + + + public TaskCreate lockDate(@Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + * @return lockDate + */ + + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public TaskCreate earliestStartTime(@Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked before this time + * @return earliestStartTime + */ + + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public TaskCreate latestEndTime(@Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked after this time + * @return latestEndTime + */ + + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public TaskCreate budgetPlanningType(@Nullable BudgetPlanningTypeRequest budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * @return budgetPlanningType + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BudgetPlanningTypeRequest> getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public TaskCreate budgetHoursPlanned(@Nullable BigDecimal budgetHoursPlanned) { + this.budgetHoursPlanned = JsonNullable.of(budgetHoursPlanned); + + return this; + } + + /** + * how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetHoursPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetHoursPlanned() { + return budgetHoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURS_PLANNED) + public void setBudgetHoursPlanned(JsonNullable budgetHoursPlanned) { + this.budgetHoursPlanned = budgetHoursPlanned; + } + + + + public TaskCreate budgetHourlyRate(@Nullable BigDecimal budgetHourlyRate) { + this.budgetHourlyRate = JsonNullable.of(budgetHourlyRate); + + return this; + } + + /** + * depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * @return budgetHourlyRate + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURLY_RATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetHourlyRate() { + return budgetHourlyRate; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURLY_RATE) + public void setBudgetHourlyRate(JsonNullable budgetHourlyRate) { + this.budgetHourlyRate = budgetHourlyRate; + } + + + + public TaskCreate budgetPlanned(@Nullable BigDecimal budgetPlanned) { + this.budgetPlanned = JsonNullable.of(budgetPlanned); + + return this; + } + + /** + * the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetPlanned() { + return budgetPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNED) + public void setBudgetPlanned(JsonNullable budgetPlanned) { + this.budgetPlanned = budgetPlanned; + } + + + + public TaskCreate budgetIncludeNonBillableProjectTimes(@Nullable Boolean budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = JsonNullable.of(budgetIncludeNonBillableProjectTimes); + + return this; + } + + /** + * set this property to true, if you want to include not billable hours for all project times booked on this task + * @return budgetIncludeNonBillableProjectTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBudgetIncludeNonBillableProjectTimes() { + return budgetIncludeNonBillableProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES) + public void setBudgetIncludeNonBillableProjectTimes(JsonNullable budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes; + } + + + + public TaskCreate locationInherited(@Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @return locationInherited + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public TaskCreate location(@Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable TaskLocation> getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public TaskCreate locationRestrictionRadiusMeters(@Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @return locationRestrictionRadiusMeters + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Integer> getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public TaskCreate customField1(@Nullable String customField1) { + this.customField1 = JsonNullable.of(customField1); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField1 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getCustomField1() { + return customField1; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD1) + public void setCustomField1(JsonNullable customField1) { + this.customField1 = customField1; + } + + + + public TaskCreate customField2(@Nullable String customField2) { + this.customField2 = JsonNullable.of(customField2); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField2 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getCustomField2() { + return customField2; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD2) + public void setCustomField2(JsonNullable customField2) { + this.customField2 = customField2; + } + + + + public TaskCreate customField3(@Nullable String customField3) { + this.customField3 = JsonNullable.of(customField3); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField3 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getCustomField3() { + return customField3; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD3) + public void setCustomField3(JsonNullable customField3) { + this.customField3 = customField3; + } + + + + public TaskCreate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public TaskCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskCreate taskCreate = (TaskCreate) o; + return Objects.equals(this.name, taskCreate.name) && + equalsNullable(this.parentTaskId, taskCreate.parentTaskId) && + equalsNullable(this.externalId, taskCreate.externalId) && + equalsNullable(this.description, taskCreate.description) && + equalsNullable(this.descriptionExternal, taskCreate.descriptionExternal) && + Objects.equals(this.bookable, taskCreate.bookable) && + Objects.equals(this.billable, taskCreate.billable) && + equalsNullable(this.projectTimeNotesRequired, taskCreate.projectTimeNotesRequired) && + equalsNullable(this.startDate, taskCreate.startDate) && + equalsNullable(this.endDate, taskCreate.endDate) && + equalsNullable(this.lockDate, taskCreate.lockDate) && + equalsNullable(this.earliestStartTime, taskCreate.earliestStartTime) && + equalsNullable(this.latestEndTime, taskCreate.latestEndTime) && + equalsNullable(this.budgetPlanningType, taskCreate.budgetPlanningType) && + equalsNullable(this.budgetHoursPlanned, taskCreate.budgetHoursPlanned) && + equalsNullable(this.budgetHourlyRate, taskCreate.budgetHourlyRate) && + equalsNullable(this.budgetPlanned, taskCreate.budgetPlanned) && + equalsNullable(this.budgetIncludeNonBillableProjectTimes, taskCreate.budgetIncludeNonBillableProjectTimes) && + equalsNullable(this.locationInherited, taskCreate.locationInherited) && + equalsNullable(this.location, taskCreate.location) && + equalsNullable(this.locationRestrictionRadiusMeters, taskCreate.locationRestrictionRadiusMeters) && + equalsNullable(this.customField1, taskCreate.customField1) && + equalsNullable(this.customField2, taskCreate.customField2) && + equalsNullable(this.customField3, taskCreate.customField3) && + equalsNullable(this.metadata, taskCreate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(name, hashCodeNullable(parentTaskId), hashCodeNullable(externalId), hashCodeNullable(description), hashCodeNullable(descriptionExternal), bookable, billable, hashCodeNullable(projectTimeNotesRequired), hashCodeNullable(startDate), hashCodeNullable(endDate), hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), hashCodeNullable(budgetPlanningType), hashCodeNullable(budgetHoursPlanned), hashCodeNullable(budgetHourlyRate), hashCodeNullable(budgetPlanned), hashCodeNullable(budgetIncludeNonBillableProjectTimes), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), hashCodeNullable(customField1), hashCodeNullable(customField2), hashCodeNullable(customField3), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskCreate {\n"); + sb.append(" parentTaskId: ").append(toIndentedString(parentTaskId)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n"); + sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskLocation.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskLocation.java new file mode 100644 index 0000000..32ddf31 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskLocation.java @@ -0,0 +1,309 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * You can define the location of a task by setting this property. If the task has a parent task, the location is inherited if nothing else is explicitly defined. If you set this property to null, the location will be deleted. + */ +@JsonPropertyOrder({ + TaskLocation.JSON_PROPERTY_LAT, + TaskLocation.JSON_PROPERTY_LON, + TaskLocation.JSON_PROPERTY_ADDRESS, + TaskLocation.JSON_PROPERTY_CITY, + TaskLocation.JSON_PROPERTY_ZIP_CODE, + TaskLocation.JSON_PROPERTY_STATE, + TaskLocation.JSON_PROPERTY_COUNTRY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskLocation { + public static final String JSON_PROPERTY_LAT = "lat"; + + private @Nullable Float lat; + + public static final String JSON_PROPERTY_LON = "lon"; + + private @Nullable Float lon; + + public static final String JSON_PROPERTY_ADDRESS = "address"; + + private @Nullable String address; + + public static final String JSON_PROPERTY_CITY = "city"; + + private @Nullable String city; + + public static final String JSON_PROPERTY_ZIP_CODE = "zip_code"; + + private @Nullable String zipCode; + + public static final String JSON_PROPERTY_STATE = "state"; + + private @Nullable String state; + + public static final String JSON_PROPERTY_COUNTRY = "country"; + + private @Nullable String country; + + public TaskLocation() { + } + + public TaskLocation lat(@Nullable Float lat) { + + this.lat = lat; + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Float getLat() { + return lat; + } + + + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLat(@Nullable Float lat) { + this.lat = lat; + } + + + public TaskLocation lon(@Nullable Float lon) { + + this.lon = lon; + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Float getLon() { + return lon; + } + + + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLon(@Nullable Float lon) { + this.lon = lon; + } + + + public TaskLocation address(@Nullable String address) { + + this.address = address; + return this; + } + + /** + * Get address + * @return address + */ + + @JsonProperty(value = JSON_PROPERTY_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getAddress() { + return address; + } + + + @JsonProperty(value = JSON_PROPERTY_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAddress(@Nullable String address) { + this.address = address; + } + + + public TaskLocation city(@Nullable String city) { + + this.city = city; + return this; + } + + /** + * Get city + * @return city + */ + + @JsonProperty(value = JSON_PROPERTY_CITY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getCity() { + return city; + } + + + @JsonProperty(value = JSON_PROPERTY_CITY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCity(@Nullable String city) { + this.city = city; + } + + + public TaskLocation zipCode(@Nullable String zipCode) { + + this.zipCode = zipCode; + return this; + } + + /** + * Get zipCode + * @return zipCode + */ + + @JsonProperty(value = JSON_PROPERTY_ZIP_CODE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getZipCode() { + return zipCode; + } + + + @JsonProperty(value = JSON_PROPERTY_ZIP_CODE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setZipCode(@Nullable String zipCode) { + this.zipCode = zipCode; + } + + + public TaskLocation state(@Nullable String state) { + + this.state = state; + return this; + } + + /** + * Get state + * @return state + */ + + @JsonProperty(value = JSON_PROPERTY_STATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getState() { + return state; + } + + + @JsonProperty(value = JSON_PROPERTY_STATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setState(@Nullable String state) { + this.state = state; + } + + + public TaskLocation country(@Nullable String country) { + + this.country = country; + return this; + } + + /** + * the country's international country code + * @return country + */ + + @JsonProperty(value = JSON_PROPERTY_COUNTRY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getCountry() { + return country; + } + + + @JsonProperty(value = JSON_PROPERTY_COUNTRY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCountry(@Nullable String country) { + this.country = country; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskLocation taskLocation = (TaskLocation) o; + return Objects.equals(this.lat, taskLocation.lat) && + Objects.equals(this.lon, taskLocation.lon) && + Objects.equals(this.address, taskLocation.address) && + Objects.equals(this.city, taskLocation.city) && + Objects.equals(this.zipCode, taskLocation.zipCode) && + Objects.equals(this.state, taskLocation.state) && + Objects.equals(this.country, taskLocation.country); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lat, lon, address, city, zipCode, state, country); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskLocation {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskPartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskPartial.java new file mode 100644 index 0000000..7d746b7 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskPartial.java @@ -0,0 +1,214 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskPartial + */ +@JsonPropertyOrder({ + TaskPartial.JSON_PROPERTY_ID, + TaskPartial.JSON_PROPERTY_NAME, + TaskPartial.JSON_PROPERTY_BREADCRUMBS, + TaskPartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskPartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public TaskPartial() { + } + + public TaskPartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public TaskPartial name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public TaskPartial breadcrumbs(String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public TaskPartial externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskPartial taskPartial = (TaskPartial) o; + return Objects.equals(this.id, taskPartial.id) && + Objects.equals(this.name, taskPartial.name) && + Objects.equals(this.breadcrumbs, taskPartial.breadcrumbs) && + Objects.equals(this.externalId, taskPartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskReduced.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskReduced.java new file mode 100644 index 0000000..91d24c3 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskReduced.java @@ -0,0 +1,759 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningType; +import com.timr.api.models.TaskLocation; +import com.timr.api.models.TaskPartial; +import java.time.LocalDate; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskReduced + */ +@JsonPropertyOrder({ + TaskReduced.JSON_PROPERTY_ID, + TaskReduced.JSON_PROPERTY_NAME, + TaskReduced.JSON_PROPERTY_BREADCRUMBS, + TaskReduced.JSON_PROPERTY_EXTERNAL_ID, + TaskReduced.JSON_PROPERTY_PARENT_TASK, + TaskReduced.JSON_PROPERTY_DESCRIPTION, + TaskReduced.JSON_PROPERTY_BOOKABLE, + TaskReduced.JSON_PROPERTY_BILLABLE, + TaskReduced.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + TaskReduced.JSON_PROPERTY_LOCK_DATE, + TaskReduced.JSON_PROPERTY_EARLIEST_START_TIME, + TaskReduced.JSON_PROPERTY_LATEST_END_TIME, + TaskReduced.JSON_PROPERTY_ACTIVE_FROM, + TaskReduced.JSON_PROPERTY_ACTIVE_TO, + TaskReduced.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + TaskReduced.JSON_PROPERTY_LOCATION_INHERITED, + TaskReduced.JSON_PROPERTY_LOCATION, + TaskReduced.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + TaskReduced.JSON_PROPERTY_CUSTOM_FIELD1, + TaskReduced.JSON_PROPERTY_CUSTOM_FIELD2, + TaskReduced.JSON_PROPERTY_CUSTOM_FIELD3 +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskReduced { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public static final String JSON_PROPERTY_PARENT_TASK = "parent_task"; + + private @Nullable TaskPartial parentTask; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private @Nullable String description; + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + + private Boolean bookable; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + + private Boolean billable; + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + + private Boolean projectTimeNotesRequired; + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + + private JsonNullable<@Nullable LocalDate> lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + + private JsonNullable<@Nullable String> earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + + private JsonNullable<@Nullable String> latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACTIVE_FROM = "active_from"; + + private @Nullable LocalDate activeFrom; + + public static final String JSON_PROPERTY_ACTIVE_TO = "active_to"; + + private @Nullable LocalDate activeTo; + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + + private JsonNullable<@Nullable BudgetPlanningType> budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + + private JsonNullable<@Nullable Boolean> locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + + private JsonNullable<@Nullable TaskLocation> location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + + private JsonNullable<@Nullable Integer> locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + + private @Nullable String customField1; + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + + private @Nullable String customField2; + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + + private @Nullable String customField3; + + public TaskReduced() { + } + + public TaskReduced id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public TaskReduced name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public TaskReduced breadcrumbs(String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public TaskReduced externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + public TaskReduced parentTask(@Nullable TaskPartial parentTask) { + + this.parentTask = parentTask; + return this; + } + + /** + * Get parentTask + * @return parentTask + */ + + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable TaskPartial getParentTask() { + return parentTask; + } + + + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setParentTask(@Nullable TaskPartial parentTask) { + this.parentTask = parentTask; + } + + + public TaskReduced description(@Nullable String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@Nullable String description) { + this.description = description; + } + + + public TaskReduced bookable(Boolean bookable) { + + this.bookable = bookable; + return this; + } + + /** + * Get bookable + * @return bookable + */ + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBookable() { + return bookable; + } + + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBookable(Boolean bookable) { + this.bookable = bookable; + } + + + public TaskReduced billable(Boolean billable) { + + this.billable = billable; + return this; + } + + /** + * Get billable + * @return billable + */ + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBillable() { + return billable; + } + + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBillable(Boolean billable) { + this.billable = billable; + } + + + public TaskReduced projectTimeNotesRequired(Boolean projectTimeNotesRequired) { + + this.projectTimeNotesRequired = projectTimeNotesRequired; + return this; + } + + /** + * Get projectTimeNotesRequired + * @return projectTimeNotesRequired + */ + + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setProjectTimeNotesRequired(Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + public TaskReduced lockDate(@Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return lockDate + */ + + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public TaskReduced earliestStartTime(@Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * time of day (ISO-8601) + * @return earliestStartTime + */ + + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public TaskReduced latestEndTime(@Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * time of day (ISO-8601) + * @return latestEndTime + */ + + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public TaskReduced activeFrom(@Nullable LocalDate activeFrom) { + + this.activeFrom = activeFrom; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return activeFrom + */ + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_FROM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable LocalDate getActiveFrom() { + return activeFrom; + } + + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_FROM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActiveFrom(@Nullable LocalDate activeFrom) { + this.activeFrom = activeFrom; + } + + + public TaskReduced activeTo(@Nullable LocalDate activeTo) { + + this.activeTo = activeTo; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return activeTo + */ + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_TO, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable LocalDate getActiveTo() { + return activeTo; + } + + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_TO, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActiveTo(@Nullable LocalDate activeTo) { + this.activeTo = activeTo; + } + + + public TaskReduced budgetPlanningType(@Nullable BudgetPlanningType budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * Get budgetPlanningType + * @return budgetPlanningType + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BudgetPlanningType> getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public TaskReduced locationInherited(@Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * Get locationInherited + * @return locationInherited + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public TaskReduced location(@Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable TaskLocation> getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public TaskReduced locationRestrictionRadiusMeters(@Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * Get locationRestrictionRadiusMeters + * @return locationRestrictionRadiusMeters + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Integer> getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public TaskReduced customField1(@Nullable String customField1) { + + this.customField1 = customField1; + return this; + } + + /** + * Get customField1 + * @return customField1 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getCustomField1() { + return customField1; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField1(@Nullable String customField1) { + this.customField1 = customField1; + } + + + public TaskReduced customField2(@Nullable String customField2) { + + this.customField2 = customField2; + return this; + } + + /** + * Get customField2 + * @return customField2 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getCustomField2() { + return customField2; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField2(@Nullable String customField2) { + this.customField2 = customField2; + } + + + public TaskReduced customField3(@Nullable String customField3) { + + this.customField3 = customField3; + return this; + } + + /** + * Get customField3 + * @return customField3 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getCustomField3() { + return customField3; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField3(@Nullable String customField3) { + this.customField3 = customField3; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskReduced taskReduced = (TaskReduced) o; + return Objects.equals(this.id, taskReduced.id) && + Objects.equals(this.name, taskReduced.name) && + Objects.equals(this.breadcrumbs, taskReduced.breadcrumbs) && + Objects.equals(this.externalId, taskReduced.externalId) && + Objects.equals(this.parentTask, taskReduced.parentTask) && + Objects.equals(this.description, taskReduced.description) && + Objects.equals(this.bookable, taskReduced.bookable) && + Objects.equals(this.billable, taskReduced.billable) && + Objects.equals(this.projectTimeNotesRequired, taskReduced.projectTimeNotesRequired) && + equalsNullable(this.lockDate, taskReduced.lockDate) && + equalsNullable(this.earliestStartTime, taskReduced.earliestStartTime) && + equalsNullable(this.latestEndTime, taskReduced.latestEndTime) && + Objects.equals(this.activeFrom, taskReduced.activeFrom) && + Objects.equals(this.activeTo, taskReduced.activeTo) && + equalsNullable(this.budgetPlanningType, taskReduced.budgetPlanningType) && + equalsNullable(this.locationInherited, taskReduced.locationInherited) && + equalsNullable(this.location, taskReduced.location) && + equalsNullable(this.locationRestrictionRadiusMeters, taskReduced.locationRestrictionRadiusMeters) && + Objects.equals(this.customField1, taskReduced.customField1) && + Objects.equals(this.customField2, taskReduced.customField2) && + Objects.equals(this.customField3, taskReduced.customField3); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId, parentTask, description, bookable, billable, projectTimeNotesRequired, hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), activeFrom, activeTo, hashCodeNullable(budgetPlanningType), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), customField1, customField2, customField3); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskReduced {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" parentTask: ").append(toIndentedString(parentTask)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" activeFrom: ").append(toIndentedString(activeFrom)).append("\n"); + sb.append(" activeTo: ").append(toIndentedString(activeTo)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToLeaderAssignment.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToLeaderAssignment.java new file mode 100644 index 0000000..3f71972 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToLeaderAssignment.java @@ -0,0 +1,152 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToLeaderAssignment + */ +@JsonPropertyOrder({ + TaskToLeaderAssignment.JSON_PROPERTY_USER, + TaskToLeaderAssignment.JSON_PROPERTY_AUTOMATICALLY_ASSIGNED +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToLeaderAssignment { + public static final String JSON_PROPERTY_USER = "user"; + + private UserPartial user; + + public static final String JSON_PROPERTY_AUTOMATICALLY_ASSIGNED = "automatically_assigned"; + + private Boolean automaticallyAssigned; + + public TaskToLeaderAssignment() { + } + + public TaskToLeaderAssignment user(UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(UserPartial user) { + this.user = user; + } + + + public TaskToLeaderAssignment automaticallyAssigned(Boolean automaticallyAssigned) { + + this.automaticallyAssigned = automaticallyAssigned; + return this; + } + + /** + * Get automaticallyAssigned + * @return automaticallyAssigned + */ + + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getAutomaticallyAssigned() { + return automaticallyAssigned; + } + + + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAutomaticallyAssigned(Boolean automaticallyAssigned) { + this.automaticallyAssigned = automaticallyAssigned; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToLeaderAssignment taskToLeaderAssignment = (TaskToLeaderAssignment) o; + return Objects.equals(this.user, taskToLeaderAssignment.user) && + Objects.equals(this.automaticallyAssigned, taskToLeaderAssignment.automaticallyAssigned); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(user, automaticallyAssigned); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToLeaderAssignment {\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" automaticallyAssigned: ").append(toIndentedString(automaticallyAssigned)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsPage.java new file mode 100644 index 0000000..2185afc --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TaskToLeaderAssignment; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToLeaderAssignmentsPage + */ +@JsonPropertyOrder({ + TaskToLeaderAssignmentsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TaskToLeaderAssignmentsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToLeaderAssignmentsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public TaskToLeaderAssignmentsPage() { + } + + public TaskToLeaderAssignmentsPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TaskToLeaderAssignmentsPage data(List data) { + + this.data = data; + return this; + } + + public TaskToLeaderAssignmentsPage addDataItem(TaskToLeaderAssignment dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToLeaderAssignmentsPage taskToLeaderAssignmentsPage = (TaskToLeaderAssignmentsPage) o; + return Objects.equals(this.nextPageToken, taskToLeaderAssignmentsPage.nextPageToken) && + Objects.equals(this.data, taskToLeaderAssignmentsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToLeaderAssignmentsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsSortColumn.java new file mode 100644 index 0000000..3fdfdac --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Task to Leader Assignments. `user_name` orders by the assigned User's last name, then first name. + */ +public enum TaskToLeaderAssignmentsSortColumn { + + USER_NAME("user_name"); + + private String value; + + TaskToLeaderAssignmentsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TaskToLeaderAssignmentsSortColumn fromValue(String value) { + for (TaskToLeaderAssignmentsSortColumn b : TaskToLeaderAssignmentsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToTeamAssignment.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToTeamAssignment.java new file mode 100644 index 0000000..ee7042d --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToTeamAssignment.java @@ -0,0 +1,152 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TeamPartial; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToTeamAssignment + */ +@JsonPropertyOrder({ + TaskToTeamAssignment.JSON_PROPERTY_TEAM, + TaskToTeamAssignment.JSON_PROPERTY_AUTOMATICALLY_ASSIGNED +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToTeamAssignment { + public static final String JSON_PROPERTY_TEAM = "team"; + + private TeamPartial team; + + public static final String JSON_PROPERTY_AUTOMATICALLY_ASSIGNED = "automatically_assigned"; + + private Boolean automaticallyAssigned; + + public TaskToTeamAssignment() { + } + + public TaskToTeamAssignment team(TeamPartial team) { + + this.team = team; + return this; + } + + /** + * Get team + * @return team + */ + + @JsonProperty(value = JSON_PROPERTY_TEAM, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public TeamPartial getTeam() { + return team; + } + + + @JsonProperty(value = JSON_PROPERTY_TEAM, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTeam(TeamPartial team) { + this.team = team; + } + + + public TaskToTeamAssignment automaticallyAssigned(Boolean automaticallyAssigned) { + + this.automaticallyAssigned = automaticallyAssigned; + return this; + } + + /** + * Get automaticallyAssigned + * @return automaticallyAssigned + */ + + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getAutomaticallyAssigned() { + return automaticallyAssigned; + } + + + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAutomaticallyAssigned(Boolean automaticallyAssigned) { + this.automaticallyAssigned = automaticallyAssigned; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToTeamAssignment taskToTeamAssignment = (TaskToTeamAssignment) o; + return Objects.equals(this.team, taskToTeamAssignment.team) && + Objects.equals(this.automaticallyAssigned, taskToTeamAssignment.automaticallyAssigned); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(team, automaticallyAssigned); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToTeamAssignment {\n"); + sb.append(" team: ").append(toIndentedString(team)).append("\n"); + sb.append(" automaticallyAssigned: ").append(toIndentedString(automaticallyAssigned)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToTeamAssignmentsPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToTeamAssignmentsPage.java new file mode 100644 index 0000000..ac12227 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToTeamAssignmentsPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TaskToTeamAssignment; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToTeamAssignmentsPage + */ +@JsonPropertyOrder({ + TaskToTeamAssignmentsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TaskToTeamAssignmentsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToTeamAssignmentsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public TaskToTeamAssignmentsPage() { + } + + public TaskToTeamAssignmentsPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TaskToTeamAssignmentsPage data(List data) { + + this.data = data; + return this; + } + + public TaskToTeamAssignmentsPage addDataItem(TaskToTeamAssignment dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToTeamAssignmentsPage taskToTeamAssignmentsPage = (TaskToTeamAssignmentsPage) o; + return Objects.equals(this.nextPageToken, taskToTeamAssignmentsPage.nextPageToken) && + Objects.equals(this.data, taskToTeamAssignmentsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToTeamAssignmentsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToTeamAssignmentsSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToTeamAssignmentsSortColumn.java new file mode 100644 index 0000000..7550b77 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToTeamAssignmentsSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Task to Team Assignments. `team_name` orders by the assigned Team's name. + */ +public enum TaskToTeamAssignmentsSortColumn { + + TEAM_NAME("team_name"); + + private String value; + + TaskToTeamAssignmentsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TaskToTeamAssignmentsSortColumn fromValue(String value) { + for (TaskToTeamAssignmentsSortColumn b : TaskToTeamAssignmentsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignment.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignment.java new file mode 100644 index 0000000..82f94d5 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignment.java @@ -0,0 +1,221 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.RecordingLockType; +import com.timr.api.models.UserPartial; +import java.math.BigDecimal; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToUserAssignment + */ +@JsonPropertyOrder({ + TaskToUserAssignment.JSON_PROPERTY_USER, + TaskToUserAssignment.JSON_PROPERTY_HOURS_PLANNED, + TaskToUserAssignment.JSON_PROPERTY_RECORDING_LOCK, + TaskToUserAssignment.JSON_PROPERTY_AUTOMATICALLY_ASSIGNED +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToUserAssignment { + public static final String JSON_PROPERTY_USER = "user"; + + private UserPartial user; + + public static final String JSON_PROPERTY_HOURS_PLANNED = "hours_planned"; + + private JsonNullable<@Nullable BigDecimal> hoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RECORDING_LOCK = "recording_lock"; + + private RecordingLockType recordingLock; + + public static final String JSON_PROPERTY_AUTOMATICALLY_ASSIGNED = "automatically_assigned"; + + private Boolean automaticallyAssigned; + + public TaskToUserAssignment() { + } + + public TaskToUserAssignment user(UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(UserPartial user) { + this.user = user; + } + + + public TaskToUserAssignment hoursPlanned(@Nullable BigDecimal hoursPlanned) { + this.hoursPlanned = JsonNullable.of(hoursPlanned); + + return this; + } + + /** + * Get hoursPlanned + * @return hoursPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getHoursPlanned() { + return hoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_HOURS_PLANNED) + public void setHoursPlanned(JsonNullable hoursPlanned) { + this.hoursPlanned = hoursPlanned; + } + + + + public TaskToUserAssignment recordingLock(RecordingLockType recordingLock) { + + this.recordingLock = recordingLock; + return this; + } + + /** + * Get recordingLock + * @return recordingLock + */ + + @JsonProperty(value = JSON_PROPERTY_RECORDING_LOCK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public RecordingLockType getRecordingLock() { + return recordingLock; + } + + + @JsonProperty(value = JSON_PROPERTY_RECORDING_LOCK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRecordingLock(RecordingLockType recordingLock) { + this.recordingLock = recordingLock; + } + + + public TaskToUserAssignment automaticallyAssigned(Boolean automaticallyAssigned) { + + this.automaticallyAssigned = automaticallyAssigned; + return this; + } + + /** + * Get automaticallyAssigned + * @return automaticallyAssigned + */ + + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getAutomaticallyAssigned() { + return automaticallyAssigned; + } + + + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAutomaticallyAssigned(Boolean automaticallyAssigned) { + this.automaticallyAssigned = automaticallyAssigned; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToUserAssignment taskToUserAssignment = (TaskToUserAssignment) o; + return Objects.equals(this.user, taskToUserAssignment.user) && + equalsNullable(this.hoursPlanned, taskToUserAssignment.hoursPlanned) && + Objects.equals(this.recordingLock, taskToUserAssignment.recordingLock) && + Objects.equals(this.automaticallyAssigned, taskToUserAssignment.automaticallyAssigned); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(user, hashCodeNullable(hoursPlanned), recordingLock, automaticallyAssigned); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToUserAssignment {\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" recordingLock: ").append(toIndentedString(recordingLock)).append("\n"); + sb.append(" automaticallyAssigned: ").append(toIndentedString(automaticallyAssigned)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignmentUpsert.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignmentUpsert.java new file mode 100644 index 0000000..998b930 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignmentUpsert.java @@ -0,0 +1,152 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.RecordingLockType; +import java.math.BigDecimal; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToUserAssignmentUpsert + */ +@JsonPropertyOrder({ + TaskToUserAssignmentUpsert.JSON_PROPERTY_HOURS_PLANNED, + TaskToUserAssignmentUpsert.JSON_PROPERTY_RECORDING_LOCK +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToUserAssignmentUpsert { + public static final String JSON_PROPERTY_HOURS_PLANNED = "hours_planned"; + + private JsonNullable<@Nullable BigDecimal> hoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RECORDING_LOCK = "recording_lock"; + + private JsonNullable<@Nullable RecordingLockType> recordingLock = JsonNullable.undefined(); + + public TaskToUserAssignmentUpsert() { + } + + public TaskToUserAssignmentUpsert hoursPlanned(@Nullable BigDecimal hoursPlanned) { + this.hoursPlanned = JsonNullable.of(hoursPlanned); + + return this; + } + + /** + * Get hoursPlanned + * @return hoursPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getHoursPlanned() { + return hoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_HOURS_PLANNED) + public void setHoursPlanned(JsonNullable hoursPlanned) { + this.hoursPlanned = hoursPlanned; + } + + + + public TaskToUserAssignmentUpsert recordingLock(@Nullable RecordingLockType recordingLock) { + this.recordingLock = JsonNullable.of(recordingLock); + + return this; + } + + /** + * Get recordingLock + * @return recordingLock + */ + + @JsonProperty(value = JSON_PROPERTY_RECORDING_LOCK, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable RecordingLockType> getRecordingLock() { + return recordingLock; + } + + @JsonProperty(JSON_PROPERTY_RECORDING_LOCK) + public void setRecordingLock(JsonNullable recordingLock) { + this.recordingLock = recordingLock; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToUserAssignmentUpsert taskToUserAssignmentUpsert = (TaskToUserAssignmentUpsert) o; + return equalsNullable(this.hoursPlanned, taskToUserAssignmentUpsert.hoursPlanned) && + equalsNullable(this.recordingLock, taskToUserAssignmentUpsert.recordingLock); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(hoursPlanned), hashCodeNullable(recordingLock)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToUserAssignmentUpsert {\n"); + sb.append(" recordingLock: ").append(toIndentedString(recordingLock)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignmentsPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignmentsPage.java new file mode 100644 index 0000000..b1609b6 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignmentsPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TaskToUserAssignment; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToUserAssignmentsPage + */ +@JsonPropertyOrder({ + TaskToUserAssignmentsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TaskToUserAssignmentsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToUserAssignmentsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public TaskToUserAssignmentsPage() { + } + + public TaskToUserAssignmentsPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TaskToUserAssignmentsPage data(List data) { + + this.data = data; + return this; + } + + public TaskToUserAssignmentsPage addDataItem(TaskToUserAssignment dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToUserAssignmentsPage taskToUserAssignmentsPage = (TaskToUserAssignmentsPage) o; + return Objects.equals(this.nextPageToken, taskToUserAssignmentsPage.nextPageToken) && + Objects.equals(this.data, taskToUserAssignmentsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToUserAssignmentsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignmentsSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignmentsSortColumn.java new file mode 100644 index 0000000..9e1ee76 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskToUserAssignmentsSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Task to User Assignments. `user_name` orders by the assigned User's last name, then first name. + */ +public enum TaskToUserAssignmentsSortColumn { + + USER_NAME("user_name"); + + private String value; + + TaskToUserAssignmentsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TaskToUserAssignmentsSortColumn fromValue(String value) { + for (TaskToUserAssignmentsSortColumn b : TaskToUserAssignmentsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TaskUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskUpdate.java new file mode 100644 index 0000000..9f7aca2 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TaskUpdate.java @@ -0,0 +1,894 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningTypeRequest; +import com.timr.api.models.TaskLocation; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskUpdate + */ +@JsonPropertyOrder({ + TaskUpdate.JSON_PROPERTY_NAME, + TaskUpdate.JSON_PROPERTY_PARENT_TASK_ID, + TaskUpdate.JSON_PROPERTY_EXTERNAL_ID, + TaskUpdate.JSON_PROPERTY_DESCRIPTION, + TaskUpdate.JSON_PROPERTY_DESCRIPTION_EXTERNAL, + TaskUpdate.JSON_PROPERTY_BOOKABLE, + TaskUpdate.JSON_PROPERTY_BILLABLE, + TaskUpdate.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + TaskUpdate.JSON_PROPERTY_START_DATE, + TaskUpdate.JSON_PROPERTY_END_DATE, + TaskUpdate.JSON_PROPERTY_LOCK_DATE, + TaskUpdate.JSON_PROPERTY_EARLIEST_START_TIME, + TaskUpdate.JSON_PROPERTY_LATEST_END_TIME, + TaskUpdate.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + TaskUpdate.JSON_PROPERTY_BUDGET_HOURS_PLANNED, + TaskUpdate.JSON_PROPERTY_BUDGET_HOURLY_RATE, + TaskUpdate.JSON_PROPERTY_BUDGET_PLANNED, + TaskUpdate.JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, + TaskUpdate.JSON_PROPERTY_LOCATION_INHERITED, + TaskUpdate.JSON_PROPERTY_LOCATION, + TaskUpdate.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + TaskUpdate.JSON_PROPERTY_CUSTOM_FIELD1, + TaskUpdate.JSON_PROPERTY_CUSTOM_FIELD2, + TaskUpdate.JSON_PROPERTY_CUSTOM_FIELD3, + TaskUpdate.JSON_PROPERTY_METADATA, + TaskUpdate.JSON_PROPERTY_BUDGET_UPDATE_PROJECT_TIMES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskUpdate { + public static final String JSON_PROPERTY_NAME = "name"; + + private JsonNullable<@Nullable String> name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PARENT_TASK_ID = "parent_task_id"; + + private JsonNullable<@Nullable String> parentTaskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private JsonNullable<@Nullable String> externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private JsonNullable<@Nullable String> description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION_EXTERNAL = "description_external"; + + private JsonNullable<@Nullable String> descriptionExternal = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + + private JsonNullable<@Nullable Boolean> bookable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + + private JsonNullable<@Nullable Boolean> billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + + private JsonNullable<@Nullable Boolean> projectTimeNotesRequired = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_DATE = "start_date"; + + private JsonNullable<@Nullable LocalDate> startDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_DATE = "end_date"; + + private JsonNullable<@Nullable LocalDate> endDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + + private JsonNullable<@Nullable LocalDate> lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + + private JsonNullable<@Nullable String> earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + + private JsonNullable<@Nullable String> latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + + private JsonNullable<@Nullable BudgetPlanningTypeRequest> budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURS_PLANNED = "budget_hours_planned"; + + private JsonNullable<@Nullable BigDecimal> budgetHoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURLY_RATE = "budget_hourly_rate"; + + private JsonNullable<@Nullable BigDecimal> budgetHourlyRate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNED = "budget_planned"; + + private JsonNullable<@Nullable BigDecimal> budgetPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES = "budget_include_non_billable_project_times"; + + private JsonNullable<@Nullable Boolean> budgetIncludeNonBillableProjectTimes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + + private JsonNullable<@Nullable Boolean> locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + + private JsonNullable<@Nullable TaskLocation> location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + + private JsonNullable<@Nullable Integer> locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + + private JsonNullable<@Nullable String> customField1 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + + private JsonNullable<@Nullable String> customField2 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + + private JsonNullable<@Nullable String> customField3 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_BUDGET_UPDATE_PROJECT_TIMES = "budget_update_project_times"; + + private JsonNullable<@Nullable Boolean> budgetUpdateProjectTimes = JsonNullable.undefined(); + + public TaskUpdate() { + } + + public TaskUpdate name(@Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public TaskUpdate parentTaskId(@Nullable String parentTaskId) { + this.parentTaskId = JsonNullable.of(parentTaskId); + + return this; + } + + /** + * returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @return parentTaskId + */ + + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getParentTaskId() { + return parentTaskId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TASK_ID) + public void setParentTaskId(JsonNullable parentTaskId) { + this.parentTaskId = parentTaskId; + } + + + + public TaskUpdate externalId(@Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public TaskUpdate description(@Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TaskUpdate descriptionExternal(@Nullable String descriptionExternal) { + this.descriptionExternal = JsonNullable.of(descriptionExternal); + + return this; + } + + /** + * Get descriptionExternal + * @return descriptionExternal + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDescriptionExternal() { + return descriptionExternal; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION_EXTERNAL) + public void setDescriptionExternal(JsonNullable descriptionExternal) { + this.descriptionExternal = descriptionExternal; + } + + + + public TaskUpdate bookable(@Nullable Boolean bookable) { + this.bookable = JsonNullable.of(bookable); + + return this; + } + + /** + * when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @return bookable + */ + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBookable() { + return bookable; + } + + @JsonProperty(JSON_PROPERTY_BOOKABLE) + public void setBookable(JsonNullable bookable) { + this.bookable = bookable; + } + + + + public TaskUpdate billable(@Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public TaskUpdate projectTimeNotesRequired(@Nullable Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = JsonNullable.of(projectTimeNotesRequired); + + return this; + } + + /** + * depending on this property project times booked on this task have to include notes or not + * @return projectTimeNotesRequired + */ + + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + @JsonProperty(JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED) + public void setProjectTimeNotesRequired(JsonNullable projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + + public TaskUpdate startDate(@Nullable LocalDate startDate) { + this.startDate = JsonNullable.of(startDate); + + return this; + } + + /** + * the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return startDate + */ + + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getStartDate() { + return startDate; + } + + @JsonProperty(JSON_PROPERTY_START_DATE) + public void setStartDate(JsonNullable startDate) { + this.startDate = startDate; + } + + + + public TaskUpdate endDate(@Nullable LocalDate endDate) { + this.endDate = JsonNullable.of(endDate); + + return this; + } + + /** + * the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return endDate + */ + + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getEndDate() { + return endDate; + } + + @JsonProperty(JSON_PROPERTY_END_DATE) + public void setEndDate(JsonNullable endDate) { + this.endDate = endDate; + } + + + + public TaskUpdate lockDate(@Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + * @return lockDate + */ + + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public TaskUpdate earliestStartTime(@Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked before this time + * @return earliestStartTime + */ + + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public TaskUpdate latestEndTime(@Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked after this time + * @return latestEndTime + */ + + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public TaskUpdate budgetPlanningType(@Nullable BudgetPlanningTypeRequest budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * @return budgetPlanningType + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BudgetPlanningTypeRequest> getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public TaskUpdate budgetHoursPlanned(@Nullable BigDecimal budgetHoursPlanned) { + this.budgetHoursPlanned = JsonNullable.of(budgetHoursPlanned); + + return this; + } + + /** + * how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetHoursPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetHoursPlanned() { + return budgetHoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURS_PLANNED) + public void setBudgetHoursPlanned(JsonNullable budgetHoursPlanned) { + this.budgetHoursPlanned = budgetHoursPlanned; + } + + + + public TaskUpdate budgetHourlyRate(@Nullable BigDecimal budgetHourlyRate) { + this.budgetHourlyRate = JsonNullable.of(budgetHourlyRate); + + return this; + } + + /** + * depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * @return budgetHourlyRate + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURLY_RATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetHourlyRate() { + return budgetHourlyRate; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURLY_RATE) + public void setBudgetHourlyRate(JsonNullable budgetHourlyRate) { + this.budgetHourlyRate = budgetHourlyRate; + } + + + + public TaskUpdate budgetPlanned(@Nullable BigDecimal budgetPlanned) { + this.budgetPlanned = JsonNullable.of(budgetPlanned); + + return this; + } + + /** + * the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetPlanned + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBudgetPlanned() { + return budgetPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNED) + public void setBudgetPlanned(JsonNullable budgetPlanned) { + this.budgetPlanned = budgetPlanned; + } + + + + public TaskUpdate budgetIncludeNonBillableProjectTimes(@Nullable Boolean budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = JsonNullable.of(budgetIncludeNonBillableProjectTimes); + + return this; + } + + /** + * set this property to true, if you want to include not billable hours for all project times booked on this task + * @return budgetIncludeNonBillableProjectTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBudgetIncludeNonBillableProjectTimes() { + return budgetIncludeNonBillableProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES) + public void setBudgetIncludeNonBillableProjectTimes(JsonNullable budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes; + } + + + + public TaskUpdate locationInherited(@Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @return locationInherited + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public TaskUpdate location(@Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable TaskLocation> getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public TaskUpdate locationRestrictionRadiusMeters(@Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @return locationRestrictionRadiusMeters + */ + + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Integer> getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public TaskUpdate customField1(@Nullable String customField1) { + this.customField1 = JsonNullable.of(customField1); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField1 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getCustomField1() { + return customField1; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD1) + public void setCustomField1(JsonNullable customField1) { + this.customField1 = customField1; + } + + + + public TaskUpdate customField2(@Nullable String customField2) { + this.customField2 = JsonNullable.of(customField2); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField2 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getCustomField2() { + return customField2; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD2) + public void setCustomField2(JsonNullable customField2) { + this.customField2 = customField2; + } + + + + public TaskUpdate customField3(@Nullable String customField3) { + this.customField3 = JsonNullable.of(customField3); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField3 + */ + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getCustomField3() { + return customField3; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD3) + public void setCustomField3(JsonNullable customField3) { + this.customField3 = customField3; + } + + + + public TaskUpdate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public TaskUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public TaskUpdate budgetUpdateProjectTimes(@Nullable Boolean budgetUpdateProjectTimes) { + this.budgetUpdateProjectTimes = JsonNullable.of(budgetUpdateProjectTimes); + + return this; + } + + /** + * this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. + * @return budgetUpdateProjectTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BUDGET_UPDATE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getBudgetUpdateProjectTimes() { + return budgetUpdateProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_UPDATE_PROJECT_TIMES) + public void setBudgetUpdateProjectTimes(JsonNullable budgetUpdateProjectTimes) { + this.budgetUpdateProjectTimes = budgetUpdateProjectTimes; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskUpdate taskUpdate = (TaskUpdate) o; + return equalsNullable(this.name, taskUpdate.name) && + equalsNullable(this.parentTaskId, taskUpdate.parentTaskId) && + equalsNullable(this.externalId, taskUpdate.externalId) && + equalsNullable(this.description, taskUpdate.description) && + equalsNullable(this.descriptionExternal, taskUpdate.descriptionExternal) && + equalsNullable(this.bookable, taskUpdate.bookable) && + equalsNullable(this.billable, taskUpdate.billable) && + equalsNullable(this.projectTimeNotesRequired, taskUpdate.projectTimeNotesRequired) && + equalsNullable(this.startDate, taskUpdate.startDate) && + equalsNullable(this.endDate, taskUpdate.endDate) && + equalsNullable(this.lockDate, taskUpdate.lockDate) && + equalsNullable(this.earliestStartTime, taskUpdate.earliestStartTime) && + equalsNullable(this.latestEndTime, taskUpdate.latestEndTime) && + equalsNullable(this.budgetPlanningType, taskUpdate.budgetPlanningType) && + equalsNullable(this.budgetHoursPlanned, taskUpdate.budgetHoursPlanned) && + equalsNullable(this.budgetHourlyRate, taskUpdate.budgetHourlyRate) && + equalsNullable(this.budgetPlanned, taskUpdate.budgetPlanned) && + equalsNullable(this.budgetIncludeNonBillableProjectTimes, taskUpdate.budgetIncludeNonBillableProjectTimes) && + equalsNullable(this.locationInherited, taskUpdate.locationInherited) && + equalsNullable(this.location, taskUpdate.location) && + equalsNullable(this.locationRestrictionRadiusMeters, taskUpdate.locationRestrictionRadiusMeters) && + equalsNullable(this.customField1, taskUpdate.customField1) && + equalsNullable(this.customField2, taskUpdate.customField2) && + equalsNullable(this.customField3, taskUpdate.customField3) && + equalsNullable(this.metadata, taskUpdate.metadata) && + equalsNullable(this.budgetUpdateProjectTimes, taskUpdate.budgetUpdateProjectTimes); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(name), hashCodeNullable(parentTaskId), hashCodeNullable(externalId), hashCodeNullable(description), hashCodeNullable(descriptionExternal), hashCodeNullable(bookable), hashCodeNullable(billable), hashCodeNullable(projectTimeNotesRequired), hashCodeNullable(startDate), hashCodeNullable(endDate), hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), hashCodeNullable(budgetPlanningType), hashCodeNullable(budgetHoursPlanned), hashCodeNullable(budgetHourlyRate), hashCodeNullable(budgetPlanned), hashCodeNullable(budgetIncludeNonBillableProjectTimes), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), hashCodeNullable(customField1), hashCodeNullable(customField2), hashCodeNullable(customField3), hashCodeNullable(metadata), hashCodeNullable(budgetUpdateProjectTimes)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskUpdate {\n"); + sb.append(" parentTaskId: ").append(toIndentedString(parentTaskId)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n"); + sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TasksPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TasksPage.java new file mode 100644 index 0000000..a4dc888 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TasksPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.Task; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TasksPage + */ +@JsonPropertyOrder({ + TasksPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TasksPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TasksPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public TasksPage() { + } + + public TasksPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TasksPage data(List data) { + + this.data = data; + return this; + } + + public TasksPage addDataItem(Task dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TasksPage tasksPage = (TasksPage) o; + return Objects.equals(this.nextPageToken, tasksPage.nextPageToken) && + Objects.equals(this.data, tasksPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TasksPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TasksReducedPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TasksReducedPage.java new file mode 100644 index 0000000..c24ff3c --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TasksReducedPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TaskReduced; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TasksReducedPage + */ +@JsonPropertyOrder({ + TasksReducedPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TasksReducedPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TasksReducedPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public TasksReducedPage() { + } + + public TasksReducedPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TasksReducedPage data(List data) { + + this.data = data; + return this; + } + + public TasksReducedPage addDataItem(TaskReduced dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TasksReducedPage tasksReducedPage = (TasksReducedPage) o; + return Objects.equals(this.nextPageToken, tasksReducedPage.nextPageToken) && + Objects.equals(this.data, tasksReducedPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TasksReducedPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TasksSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TasksSortColumn.java new file mode 100644 index 0000000..e089bf3 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TasksSortColumn.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Tasks. `breadcrumbs` orders by the Task's full path, `name` by its own name only. + */ +public enum TasksSortColumn { + + BREADCRUMBS("breadcrumbs"), + + NAME("name"); + + private String value; + + TasksSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TasksSortColumn fromValue(String value) { + for (TasksSortColumn b : TasksSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Team.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Team.java new file mode 100644 index 0000000..44e51f9 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Team.java @@ -0,0 +1,280 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TeamPartial; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A team, placed in the hierarchy by `parent_team`, with the full path from the root in `breadcrumbs`. + */ +@JsonPropertyOrder({ + Team.JSON_PROPERTY_ID, + Team.JSON_PROPERTY_NAME, + Team.JSON_PROPERTY_BREADCRUMBS, + Team.JSON_PROPERTY_EXTERNAL_ID, + Team.JSON_PROPERTY_DESCRIPTION, + Team.JSON_PROPERTY_PARENT_TEAM +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Team { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private @Nullable String description; + + public static final String JSON_PROPERTY_PARENT_TEAM = "parent_team"; + + private @Nullable TeamPartial parentTeam; + + public Team() { + } + + public Team id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public Team name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public Team breadcrumbs(String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public Team externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + public Team description(@Nullable String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@Nullable String description) { + this.description = description; + } + + + public Team parentTeam(@Nullable TeamPartial parentTeam) { + + this.parentTeam = parentTeam; + return this; + } + + /** + * Get parentTeam + * @return parentTeam + */ + + @JsonProperty(value = JSON_PROPERTY_PARENT_TEAM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable TeamPartial getParentTeam() { + return parentTeam; + } + + + @JsonProperty(value = JSON_PROPERTY_PARENT_TEAM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setParentTeam(@Nullable TeamPartial parentTeam) { + this.parentTeam = parentTeam; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Team team = (Team) o; + return Objects.equals(this.id, team.id) && + Objects.equals(this.name, team.name) && + Objects.equals(this.breadcrumbs, team.breadcrumbs) && + Objects.equals(this.externalId, team.externalId) && + Objects.equals(this.description, team.description) && + Objects.equals(this.parentTeam, team.parentTeam); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId, description, parentTeam); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Team {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" parentTeam: ").append(toIndentedString(parentTeam)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TeamCreate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamCreate.java new file mode 100644 index 0000000..acf4159 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamCreate.java @@ -0,0 +1,212 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamCreate + */ +@JsonPropertyOrder({ + TeamCreate.JSON_PROPERTY_NAME, + TeamCreate.JSON_PROPERTY_DESCRIPTION, + TeamCreate.JSON_PROPERTY_PARENT_TEAM_ID, + TeamCreate.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamCreate { + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private JsonNullable<@Nullable String> description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PARENT_TEAM_ID = "parent_team_id"; + + private JsonNullable<@Nullable String> parentTeamId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private JsonNullable<@Nullable String> externalId = JsonNullable.undefined(); + + public TeamCreate() { + } + + public TeamCreate name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public TeamCreate description(@Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TeamCreate parentTeamId(@Nullable String parentTeamId) { + this.parentTeamId = JsonNullable.of(parentTeamId); + + return this; + } + + /** + * Get parentTeamId + * @return parentTeamId + */ + + @JsonProperty(value = JSON_PROPERTY_PARENT_TEAM_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getParentTeamId() { + return parentTeamId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TEAM_ID) + public void setParentTeamId(JsonNullable parentTeamId) { + this.parentTeamId = parentTeamId; + } + + + + public TeamCreate externalId(@Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamCreate teamCreate = (TeamCreate) o; + return Objects.equals(this.name, teamCreate.name) && + equalsNullable(this.description, teamCreate.description) && + equalsNullable(this.parentTeamId, teamCreate.parentTeamId) && + equalsNullable(this.externalId, teamCreate.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(name, hashCodeNullable(description), hashCodeNullable(parentTeamId), hashCodeNullable(externalId)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamCreate {\n"); + sb.append(" parentTeamId: ").append(toIndentedString(parentTeamId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TeamPartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamPartial.java new file mode 100644 index 0000000..bc7d68c --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamPartial.java @@ -0,0 +1,214 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamPartial + */ +@JsonPropertyOrder({ + TeamPartial.JSON_PROPERTY_ID, + TeamPartial.JSON_PROPERTY_NAME, + TeamPartial.JSON_PROPERTY_BREADCRUMBS, + TeamPartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamPartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public TeamPartial() { + } + + public TeamPartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public TeamPartial name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public TeamPartial breadcrumbs(String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public TeamPartial externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamPartial teamPartial = (TeamPartial) o; + return Objects.equals(this.id, teamPartial.id) && + Objects.equals(this.name, teamPartial.name) && + Objects.equals(this.breadcrumbs, teamPartial.breadcrumbs) && + Objects.equals(this.externalId, teamPartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TeamUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamUpdate.java new file mode 100644 index 0000000..6853d21 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamUpdate.java @@ -0,0 +1,210 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamUpdate + */ +@JsonPropertyOrder({ + TeamUpdate.JSON_PROPERTY_NAME, + TeamUpdate.JSON_PROPERTY_DESCRIPTION, + TeamUpdate.JSON_PROPERTY_PARENT_TEAM_ID, + TeamUpdate.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamUpdate { + public static final String JSON_PROPERTY_NAME = "name"; + + private JsonNullable<@Nullable String> name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private JsonNullable<@Nullable String> description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PARENT_TEAM_ID = "parent_team_id"; + + private JsonNullable<@Nullable String> parentTeamId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private JsonNullable<@Nullable String> externalId = JsonNullable.undefined(); + + public TeamUpdate() { + } + + public TeamUpdate name(@Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public TeamUpdate description(@Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TeamUpdate parentTeamId(@Nullable String parentTeamId) { + this.parentTeamId = JsonNullable.of(parentTeamId); + + return this; + } + + /** + * Get parentTeamId + * @return parentTeamId + */ + + @JsonProperty(value = JSON_PROPERTY_PARENT_TEAM_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getParentTeamId() { + return parentTeamId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TEAM_ID) + public void setParentTeamId(JsonNullable parentTeamId) { + this.parentTeamId = parentTeamId; + } + + + + public TeamUpdate externalId(@Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamUpdate teamUpdate = (TeamUpdate) o; + return equalsNullable(this.name, teamUpdate.name) && + equalsNullable(this.description, teamUpdate.description) && + equalsNullable(this.parentTeamId, teamUpdate.parentTeamId) && + equalsNullable(this.externalId, teamUpdate.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(name), hashCodeNullable(description), hashCodeNullable(parentTeamId), hashCodeNullable(externalId)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamUpdate {\n"); + sb.append(" parentTeamId: ").append(toIndentedString(parentTeamId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TeamsPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamsPage.java new file mode 100644 index 0000000..19e5b68 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamsPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.Team; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamsPage + */ +@JsonPropertyOrder({ + TeamsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TeamsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public TeamsPage() { + } + + public TeamsPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TeamsPage data(List data) { + + this.data = data; + return this; + } + + public TeamsPage addDataItem(Team dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamsPage teamsPage = (TeamsPage) o; + return Objects.equals(this.nextPageToken, teamsPage.nextPageToken) && + Objects.equals(this.data, teamsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TeamsPartialPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamsPartialPage.java new file mode 100644 index 0000000..0ae7449 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamsPartialPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TeamPartial; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamsPartialPage + */ +@JsonPropertyOrder({ + TeamsPartialPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TeamsPartialPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamsPartialPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public TeamsPartialPage() { + } + + public TeamsPartialPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TeamsPartialPage data(List data) { + + this.data = data; + return this; + } + + public TeamsPartialPage addDataItem(TeamPartial dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamsPartialPage teamsPartialPage = (TeamsPartialPage) o; + return Objects.equals(this.nextPageToken, teamsPartialPage.nextPageToken) && + Objects.equals(this.data, teamsPartialPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamsPartialPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TeamsSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamsSortColumn.java new file mode 100644 index 0000000..ec51be5 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TeamsSortColumn.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Teams. `breadcrumbs` orders by the Team's full path, `name` by its own name only. + */ +public enum TeamsSortColumn { + + BREADCRUMBS("breadcrumbs"), + + NAME("name"); + + private String value; + + TeamsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TeamsSortColumn fromValue(String value) { + for (TeamsSortColumn b : TeamsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/TimeAccount.java b/sdk/java-restclient/src/main/java/com/timr/api/models/TimeAccount.java new file mode 100644 index 0000000..0723eb5 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/TimeAccount.java @@ -0,0 +1,344 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.FlexTimeIndicator; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TimeAccount + */ +@JsonPropertyOrder({ + TimeAccount.JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, + TimeAccount.JSON_PROPERTY_DURATION_ACTUAL_MINUTES, + TimeAccount.JSON_PROPERTY_DURATION_TARGET_MINUTES, + TimeAccount.JSON_PROPERTY_BALANCE_CURRENT_PERIOD_MINUTES, + TimeAccount.JSON_PROPERTY_BALANCE_TOTAL_MINUTES, + TimeAccount.JSON_PROPERTY_WORK_FROM_HOME_DAYS_FULL, + TimeAccount.JSON_PROPERTY_WORK_FROM_HOME_DAYS_PARTIAL, + TimeAccount.JSON_PROPERTY_FLEX_TIME_INDICATOR +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TimeAccount { + public static final String JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES = "balance_last_period_minutes"; + + private @Nullable Integer balanceLastPeriodMinutes; + + public static final String JSON_PROPERTY_DURATION_ACTUAL_MINUTES = "duration_actual_minutes"; + + private @Nullable Integer durationActualMinutes; + + public static final String JSON_PROPERTY_DURATION_TARGET_MINUTES = "duration_target_minutes"; + + private @Nullable Integer durationTargetMinutes; + + public static final String JSON_PROPERTY_BALANCE_CURRENT_PERIOD_MINUTES = "balance_current_period_minutes"; + + private @Nullable Integer balanceCurrentPeriodMinutes; + + public static final String JSON_PROPERTY_BALANCE_TOTAL_MINUTES = "balance_total_minutes"; + + private @Nullable Integer balanceTotalMinutes; + + public static final String JSON_PROPERTY_WORK_FROM_HOME_DAYS_FULL = "work_from_home_days_full"; + + private @Nullable Integer workFromHomeDaysFull; + + public static final String JSON_PROPERTY_WORK_FROM_HOME_DAYS_PARTIAL = "work_from_home_days_partial"; + + private @Nullable Integer workFromHomeDaysPartial; + + public static final String JSON_PROPERTY_FLEX_TIME_INDICATOR = "flex_time_indicator"; + + private JsonNullable<@Nullable FlexTimeIndicator> flexTimeIndicator = JsonNullable.undefined(); + + public TimeAccount() { + } + + public TimeAccount balanceLastPeriodMinutes(@Nullable Integer balanceLastPeriodMinutes) { + + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + return this; + } + + /** + * Get balanceLastPeriodMinutes + * @return balanceLastPeriodMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getBalanceLastPeriodMinutes() { + return balanceLastPeriodMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceLastPeriodMinutes(@Nullable Integer balanceLastPeriodMinutes) { + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + } + + + public TimeAccount durationActualMinutes(@Nullable Integer durationActualMinutes) { + + this.durationActualMinutes = durationActualMinutes; + return this; + } + + /** + * sum of durations in current period + * @return durationActualMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION_ACTUAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getDurationActualMinutes() { + return durationActualMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION_ACTUAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDurationActualMinutes(@Nullable Integer durationActualMinutes) { + this.durationActualMinutes = durationActualMinutes; + } + + + public TimeAccount durationTargetMinutes(@Nullable Integer durationTargetMinutes) { + + this.durationTargetMinutes = durationTargetMinutes; + return this; + } + + /** + * target duration in current period + * @return durationTargetMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION_TARGET_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getDurationTargetMinutes() { + return durationTargetMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION_TARGET_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDurationTargetMinutes(@Nullable Integer durationTargetMinutes) { + this.durationTargetMinutes = durationTargetMinutes; + } + + + public TimeAccount balanceCurrentPeriodMinutes(@Nullable Integer balanceCurrentPeriodMinutes) { + + this.balanceCurrentPeriodMinutes = balanceCurrentPeriodMinutes; + return this; + } + + /** + * difference between target duration and actual duration + * @return balanceCurrentPeriodMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_BALANCE_CURRENT_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getBalanceCurrentPeriodMinutes() { + return balanceCurrentPeriodMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_CURRENT_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceCurrentPeriodMinutes(@Nullable Integer balanceCurrentPeriodMinutes) { + this.balanceCurrentPeriodMinutes = balanceCurrentPeriodMinutes; + } + + + public TimeAccount balanceTotalMinutes(@Nullable Integer balanceTotalMinutes) { + + this.balanceTotalMinutes = balanceTotalMinutes; + return this; + } + + /** + * total duration until balancing date + * @return balanceTotalMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getBalanceTotalMinutes() { + return balanceTotalMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceTotalMinutes(@Nullable Integer balanceTotalMinutes) { + this.balanceTotalMinutes = balanceTotalMinutes; + } + + + public TimeAccount workFromHomeDaysFull(@Nullable Integer workFromHomeDaysFull) { + + this.workFromHomeDaysFull = workFromHomeDaysFull; + return this; + } + + /** + * complete days worked from home in current period + * @return workFromHomeDaysFull + */ + + @JsonProperty(value = JSON_PROPERTY_WORK_FROM_HOME_DAYS_FULL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getWorkFromHomeDaysFull() { + return workFromHomeDaysFull; + } + + + @JsonProperty(value = JSON_PROPERTY_WORK_FROM_HOME_DAYS_FULL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkFromHomeDaysFull(@Nullable Integer workFromHomeDaysFull) { + this.workFromHomeDaysFull = workFromHomeDaysFull; + } + + + public TimeAccount workFromHomeDaysPartial(@Nullable Integer workFromHomeDaysPartial) { + + this.workFromHomeDaysPartial = workFromHomeDaysPartial; + return this; + } + + /** + * partial days worked from home in current period + * @return workFromHomeDaysPartial + */ + + @JsonProperty(value = JSON_PROPERTY_WORK_FROM_HOME_DAYS_PARTIAL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Integer getWorkFromHomeDaysPartial() { + return workFromHomeDaysPartial; + } + + + @JsonProperty(value = JSON_PROPERTY_WORK_FROM_HOME_DAYS_PARTIAL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkFromHomeDaysPartial(@Nullable Integer workFromHomeDaysPartial) { + this.workFromHomeDaysPartial = workFromHomeDaysPartial; + } + + + public TimeAccount flexTimeIndicator(@Nullable FlexTimeIndicator flexTimeIndicator) { + this.flexTimeIndicator = JsonNullable.of(flexTimeIndicator); + + return this; + } + + /** + * Get flexTimeIndicator + * @return flexTimeIndicator + */ + + @JsonProperty(value = JSON_PROPERTY_FLEX_TIME_INDICATOR, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable FlexTimeIndicator> getFlexTimeIndicator() { + return flexTimeIndicator; + } + + @JsonProperty(JSON_PROPERTY_FLEX_TIME_INDICATOR) + public void setFlexTimeIndicator(JsonNullable flexTimeIndicator) { + this.flexTimeIndicator = flexTimeIndicator; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TimeAccount timeAccount = (TimeAccount) o; + return Objects.equals(this.balanceLastPeriodMinutes, timeAccount.balanceLastPeriodMinutes) && + Objects.equals(this.durationActualMinutes, timeAccount.durationActualMinutes) && + Objects.equals(this.durationTargetMinutes, timeAccount.durationTargetMinutes) && + Objects.equals(this.balanceCurrentPeriodMinutes, timeAccount.balanceCurrentPeriodMinutes) && + Objects.equals(this.balanceTotalMinutes, timeAccount.balanceTotalMinutes) && + Objects.equals(this.workFromHomeDaysFull, timeAccount.workFromHomeDaysFull) && + Objects.equals(this.workFromHomeDaysPartial, timeAccount.workFromHomeDaysPartial) && + equalsNullable(this.flexTimeIndicator, timeAccount.flexTimeIndicator); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(balanceLastPeriodMinutes, durationActualMinutes, durationTargetMinutes, balanceCurrentPeriodMinutes, balanceTotalMinutes, workFromHomeDaysFull, workFromHomeDaysPartial, hashCodeNullable(flexTimeIndicator)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TimeAccount {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/User.java b/sdk/java-restclient/src/main/java/com/timr/api/models/User.java new file mode 100644 index 0000000..fcd1427 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/User.java @@ -0,0 +1,541 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.HolidayCalendarPartial; +import com.timr.api.models.WorkScheduleModelPartial; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A user's identity (`firstname`, `lastname`, `email`), employment dates (`entry_date`, `resign_date`), and the assigned `work_schedule_model` and `holiday_calendar`. + */ +@JsonPropertyOrder({ + User.JSON_PROPERTY_ID, + User.JSON_PROPERTY_FIRSTNAME, + User.JSON_PROPERTY_LASTNAME, + User.JSON_PROPERTY_FULLNAME, + User.JSON_PROPERTY_EMAIL, + User.JSON_PROPERTY_EMPLOYEE_NUMBER, + User.JSON_PROPERTY_EXTERNAL_ID, + User.JSON_PROPERTY_LOGIN, + User.JSON_PROPERTY_ENTRY_DATE, + User.JSON_PROPERTY_RESIGN_DATE, + User.JSON_PROPERTY_WORK_SCHEDULE_MODEL, + User.JSON_PROPERTY_HOLIDAY_CALENDAR, + User.JSON_PROPERTY_VACATION_YEAR_START, + User.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class User { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_FIRSTNAME = "firstname"; + + private @Nullable String firstname; + + public static final String JSON_PROPERTY_LASTNAME = "lastname"; + + private @Nullable String lastname; + + public static final String JSON_PROPERTY_FULLNAME = "fullname"; + + private @Nullable String fullname; + + public static final String JSON_PROPERTY_EMAIL = "email"; + + private @Nullable String email; + + public static final String JSON_PROPERTY_EMPLOYEE_NUMBER = "employee_number"; + + private @Nullable String employeeNumber; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public static final String JSON_PROPERTY_LOGIN = "login"; + + private JsonNullable<@Nullable String> login = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ENTRY_DATE = "entry_date"; + + private JsonNullable<@Nullable LocalDate> entryDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RESIGN_DATE = "resign_date"; + + private JsonNullable<@Nullable LocalDate> resignDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORK_SCHEDULE_MODEL = "work_schedule_model"; + + private JsonNullable<@Nullable WorkScheduleModelPartial> workScheduleModel = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_HOLIDAY_CALENDAR = "holiday_calendar"; + + private JsonNullable<@Nullable HolidayCalendarPartial> holidayCalendar = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_VACATION_YEAR_START = "vacation_year_start"; + + private JsonNullable<@Nullable String> vacationYearStart = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public User() { + } + + public User id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public User firstname(@Nullable String firstname) { + + this.firstname = firstname; + return this; + } + + /** + * Get firstname + * @return firstname + */ + + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getFirstname() { + return firstname; + } + + + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFirstname(@Nullable String firstname) { + this.firstname = firstname; + } + + + public User lastname(@Nullable String lastname) { + + this.lastname = lastname; + return this; + } + + /** + * Get lastname + * @return lastname + */ + + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getLastname() { + return lastname; + } + + + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastname(@Nullable String lastname) { + this.lastname = lastname; + } + + + public User fullname(@Nullable String fullname) { + + this.fullname = fullname; + return this; + } + + /** + * Get fullname + * @return fullname + */ + + @JsonProperty(value = JSON_PROPERTY_FULLNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getFullname() { + return fullname; + } + + + @JsonProperty(value = JSON_PROPERTY_FULLNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFullname(@Nullable String fullname) { + this.fullname = fullname; + } + + + public User email(@Nullable String email) { + + this.email = email; + return this; + } + + /** + * Email address must be either valid or null. + * @return email + */ + + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getEmail() { + return email; + } + + + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmail(@Nullable String email) { + this.email = email; + } + + + public User employeeNumber(@Nullable String employeeNumber) { + + this.employeeNumber = employeeNumber; + return this; + } + + /** + * Get employeeNumber + * @return employeeNumber + */ + + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getEmployeeNumber() { + return employeeNumber; + } + + + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmployeeNumber(@Nullable String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + + public User externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + public User login(@Nullable String login) { + this.login = JsonNullable.of(login); + + return this; + } + + /** + * Get login + * @return login + */ + + @JsonProperty(value = JSON_PROPERTY_LOGIN, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getLogin() { + return login; + } + + @JsonProperty(JSON_PROPERTY_LOGIN) + public void setLogin(JsonNullable login) { + this.login = login; + } + + + + public User entryDate(@Nullable LocalDate entryDate) { + this.entryDate = JsonNullable.of(entryDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return entryDate + */ + + @JsonProperty(value = JSON_PROPERTY_ENTRY_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getEntryDate() { + return entryDate; + } + + @JsonProperty(JSON_PROPERTY_ENTRY_DATE) + public void setEntryDate(JsonNullable entryDate) { + this.entryDate = entryDate; + } + + + + public User resignDate(@Nullable LocalDate resignDate) { + this.resignDate = JsonNullable.of(resignDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return resignDate + */ + + @JsonProperty(value = JSON_PROPERTY_RESIGN_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getResignDate() { + return resignDate; + } + + @JsonProperty(JSON_PROPERTY_RESIGN_DATE) + public void setResignDate(JsonNullable resignDate) { + this.resignDate = resignDate; + } + + + + public User workScheduleModel(@Nullable WorkScheduleModelPartial workScheduleModel) { + this.workScheduleModel = JsonNullable.of(workScheduleModel); + + return this; + } + + /** + * Get workScheduleModel + * @return workScheduleModel + */ + + @JsonProperty(value = JSON_PROPERTY_WORK_SCHEDULE_MODEL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable WorkScheduleModelPartial> getWorkScheduleModel() { + return workScheduleModel; + } + + @JsonProperty(JSON_PROPERTY_WORK_SCHEDULE_MODEL) + public void setWorkScheduleModel(JsonNullable workScheduleModel) { + this.workScheduleModel = workScheduleModel; + } + + + + public User holidayCalendar(@Nullable HolidayCalendarPartial holidayCalendar) { + this.holidayCalendar = JsonNullable.of(holidayCalendar); + + return this; + } + + /** + * Get holidayCalendar + * @return holidayCalendar + */ + + @JsonProperty(value = JSON_PROPERTY_HOLIDAY_CALENDAR, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable HolidayCalendarPartial> getHolidayCalendar() { + return holidayCalendar; + } + + @JsonProperty(JSON_PROPERTY_HOLIDAY_CALENDAR) + public void setHolidayCalendar(JsonNullable holidayCalendar) { + this.holidayCalendar = holidayCalendar; + } + + + + public User vacationYearStart(@Nullable String vacationYearStart) { + this.vacationYearStart = JsonNullable.of(vacationYearStart); + + return this; + } + + /** + * recurring month and day on which the user's vacation year starts + * @return vacationYearStart + */ + + @JsonProperty(value = JSON_PROPERTY_VACATION_YEAR_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getVacationYearStart() { + return vacationYearStart; + } + + @JsonProperty(JSON_PROPERTY_VACATION_YEAR_START) + public void setVacationYearStart(JsonNullable vacationYearStart) { + this.vacationYearStart = vacationYearStart; + } + + + + public User metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public User putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.firstname, user.firstname) && + Objects.equals(this.lastname, user.lastname) && + Objects.equals(this.fullname, user.fullname) && + Objects.equals(this.email, user.email) && + Objects.equals(this.employeeNumber, user.employeeNumber) && + Objects.equals(this.externalId, user.externalId) && + equalsNullable(this.login, user.login) && + equalsNullable(this.entryDate, user.entryDate) && + equalsNullable(this.resignDate, user.resignDate) && + equalsNullable(this.workScheduleModel, user.workScheduleModel) && + equalsNullable(this.holidayCalendar, user.holidayCalendar) && + equalsNullable(this.vacationYearStart, user.vacationYearStart) && + equalsNullable(this.metadata, user.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, firstname, lastname, fullname, email, employeeNumber, externalId, hashCodeNullable(login), hashCodeNullable(entryDate), hashCodeNullable(resignDate), hashCodeNullable(workScheduleModel), hashCodeNullable(holidayCalendar), hashCodeNullable(vacationYearStart), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/UserCreate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/UserCreate.java new file mode 100644 index 0000000..13d74a6 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/UserCreate.java @@ -0,0 +1,436 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UserCreate + */ +@JsonPropertyOrder({ + UserCreate.JSON_PROPERTY_LOGIN, + UserCreate.JSON_PROPERTY_FIRSTNAME, + UserCreate.JSON_PROPERTY_LASTNAME, + UserCreate.JSON_PROPERTY_EMAIL, + UserCreate.JSON_PROPERTY_ENTRY_DATE, + UserCreate.JSON_PROPERTY_RESIGN_DATE, + UserCreate.JSON_PROPERTY_EMPLOYEE_NUMBER, + UserCreate.JSON_PROPERTY_EXTERNAL_ID, + UserCreate.JSON_PROPERTY_METADATA, + UserCreate.JSON_PROPERTY_AUTH_PROVIDER, + UserCreate.JSON_PROPERTY_AUTH_IDENTIFIER +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UserCreate { + public static final String JSON_PROPERTY_LOGIN = "login"; + + private String login; + + public static final String JSON_PROPERTY_FIRSTNAME = "firstname"; + + private JsonNullable<@Nullable String> firstname = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LASTNAME = "lastname"; + + private JsonNullable<@Nullable String> lastname = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EMAIL = "email"; + + private JsonNullable<@Nullable String> email = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ENTRY_DATE = "entry_date"; + + private JsonNullable<@Nullable LocalDate> entryDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RESIGN_DATE = "resign_date"; + + private JsonNullable<@Nullable LocalDate> resignDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EMPLOYEE_NUMBER = "employee_number"; + + private JsonNullable<@Nullable String> employeeNumber = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private JsonNullable<@Nullable String> externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_AUTH_PROVIDER = "auth_provider"; + + private JsonNullable<@Nullable String> authProvider = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_AUTH_IDENTIFIER = "auth_identifier"; + + private JsonNullable<@Nullable String> authIdentifier = JsonNullable.undefined(); + + public UserCreate() { + } + + public UserCreate login(String login) { + + this.login = login; + return this; + } + + /** + * Get login + * @return login + */ + + @JsonProperty(value = JSON_PROPERTY_LOGIN, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getLogin() { + return login; + } + + + @JsonProperty(value = JSON_PROPERTY_LOGIN, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLogin(String login) { + this.login = login; + } + + + public UserCreate firstname(@Nullable String firstname) { + this.firstname = JsonNullable.of(firstname); + + return this; + } + + /** + * Get firstname + * @return firstname + */ + + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getFirstname() { + return firstname; + } + + @JsonProperty(JSON_PROPERTY_FIRSTNAME) + public void setFirstname(JsonNullable firstname) { + this.firstname = firstname; + } + + + + public UserCreate lastname(@Nullable String lastname) { + this.lastname = JsonNullable.of(lastname); + + return this; + } + + /** + * Get lastname + * @return lastname + */ + + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getLastname() { + return lastname; + } + + @JsonProperty(JSON_PROPERTY_LASTNAME) + public void setLastname(JsonNullable lastname) { + this.lastname = lastname; + } + + + + public UserCreate email(@Nullable String email) { + this.email = JsonNullable.of(email); + + return this; + } + + /** + * Get email + * @return email + */ + + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEmail() { + return email; + } + + @JsonProperty(JSON_PROPERTY_EMAIL) + public void setEmail(JsonNullable email) { + this.email = email; + } + + + + public UserCreate entryDate(@Nullable LocalDate entryDate) { + this.entryDate = JsonNullable.of(entryDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return entryDate + */ + + @JsonProperty(value = JSON_PROPERTY_ENTRY_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getEntryDate() { + return entryDate; + } + + @JsonProperty(JSON_PROPERTY_ENTRY_DATE) + public void setEntryDate(JsonNullable entryDate) { + this.entryDate = entryDate; + } + + + + public UserCreate resignDate(@Nullable LocalDate resignDate) { + this.resignDate = JsonNullable.of(resignDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return resignDate + */ + + @JsonProperty(value = JSON_PROPERTY_RESIGN_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getResignDate() { + return resignDate; + } + + @JsonProperty(JSON_PROPERTY_RESIGN_DATE) + public void setResignDate(JsonNullable resignDate) { + this.resignDate = resignDate; + } + + + + public UserCreate employeeNumber(@Nullable String employeeNumber) { + this.employeeNumber = JsonNullable.of(employeeNumber); + + return this; + } + + /** + * Get employeeNumber + * @return employeeNumber + */ + + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEmployeeNumber() { + return employeeNumber; + } + + @JsonProperty(JSON_PROPERTY_EMPLOYEE_NUMBER) + public void setEmployeeNumber(JsonNullable employeeNumber) { + this.employeeNumber = employeeNumber; + } + + + + public UserCreate externalId(@Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Get externalId + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public UserCreate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public UserCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public UserCreate authProvider(@Nullable String authProvider) { + this.authProvider = JsonNullable.of(authProvider); + + return this; + } + + /** + * Get authProvider + * @return authProvider + */ + + @JsonProperty(value = JSON_PROPERTY_AUTH_PROVIDER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getAuthProvider() { + return authProvider; + } + + @JsonProperty(JSON_PROPERTY_AUTH_PROVIDER) + public void setAuthProvider(JsonNullable authProvider) { + this.authProvider = authProvider; + } + + + + public UserCreate authIdentifier(@Nullable String authIdentifier) { + this.authIdentifier = JsonNullable.of(authIdentifier); + + return this; + } + + /** + * Get authIdentifier + * @return authIdentifier + */ + + @JsonProperty(value = JSON_PROPERTY_AUTH_IDENTIFIER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getAuthIdentifier() { + return authIdentifier; + } + + @JsonProperty(JSON_PROPERTY_AUTH_IDENTIFIER) + public void setAuthIdentifier(JsonNullable authIdentifier) { + this.authIdentifier = authIdentifier; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserCreate userCreate = (UserCreate) o; + return Objects.equals(this.login, userCreate.login) && + equalsNullable(this.firstname, userCreate.firstname) && + equalsNullable(this.lastname, userCreate.lastname) && + equalsNullable(this.email, userCreate.email) && + equalsNullable(this.entryDate, userCreate.entryDate) && + equalsNullable(this.resignDate, userCreate.resignDate) && + equalsNullable(this.employeeNumber, userCreate.employeeNumber) && + equalsNullable(this.externalId, userCreate.externalId) && + equalsNullable(this.metadata, userCreate.metadata) && + equalsNullable(this.authProvider, userCreate.authProvider) && + equalsNullable(this.authIdentifier, userCreate.authIdentifier); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(login, hashCodeNullable(firstname), hashCodeNullable(lastname), hashCodeNullable(email), hashCodeNullable(entryDate), hashCodeNullable(resignDate), hashCodeNullable(employeeNumber), hashCodeNullable(externalId), hashCodeNullable(metadata), hashCodeNullable(authProvider), hashCodeNullable(authIdentifier)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UserCreate {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/UserPartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/UserPartial.java new file mode 100644 index 0000000..162a777 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/UserPartial.java @@ -0,0 +1,310 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UserPartial + */ +@JsonPropertyOrder({ + UserPartial.JSON_PROPERTY_ID, + UserPartial.JSON_PROPERTY_FIRSTNAME, + UserPartial.JSON_PROPERTY_LASTNAME, + UserPartial.JSON_PROPERTY_FULLNAME, + UserPartial.JSON_PROPERTY_EMAIL, + UserPartial.JSON_PROPERTY_EMPLOYEE_NUMBER, + UserPartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UserPartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_FIRSTNAME = "firstname"; + + private @Nullable String firstname; + + public static final String JSON_PROPERTY_LASTNAME = "lastname"; + + private @Nullable String lastname; + + public static final String JSON_PROPERTY_FULLNAME = "fullname"; + + private @Nullable String fullname; + + public static final String JSON_PROPERTY_EMAIL = "email"; + + private @Nullable String email; + + public static final String JSON_PROPERTY_EMPLOYEE_NUMBER = "employee_number"; + + private @Nullable String employeeNumber; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public UserPartial() { + } + + public UserPartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public UserPartial firstname(@Nullable String firstname) { + + this.firstname = firstname; + return this; + } + + /** + * Get firstname + * @return firstname + */ + + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getFirstname() { + return firstname; + } + + + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFirstname(@Nullable String firstname) { + this.firstname = firstname; + } + + + public UserPartial lastname(@Nullable String lastname) { + + this.lastname = lastname; + return this; + } + + /** + * Get lastname + * @return lastname + */ + + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getLastname() { + return lastname; + } + + + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastname(@Nullable String lastname) { + this.lastname = lastname; + } + + + public UserPartial fullname(@Nullable String fullname) { + + this.fullname = fullname; + return this; + } + + /** + * Get fullname + * @return fullname + */ + + @JsonProperty(value = JSON_PROPERTY_FULLNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getFullname() { + return fullname; + } + + + @JsonProperty(value = JSON_PROPERTY_FULLNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFullname(@Nullable String fullname) { + this.fullname = fullname; + } + + + public UserPartial email(@Nullable String email) { + + this.email = email; + return this; + } + + /** + * Email address must be either valid or null. + * @return email + */ + + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getEmail() { + return email; + } + + + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmail(@Nullable String email) { + this.email = email; + } + + + public UserPartial employeeNumber(@Nullable String employeeNumber) { + + this.employeeNumber = employeeNumber; + return this; + } + + /** + * Get employeeNumber + * @return employeeNumber + */ + + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getEmployeeNumber() { + return employeeNumber; + } + + + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmployeeNumber(@Nullable String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + + public UserPartial externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserPartial userPartial = (UserPartial) o; + return Objects.equals(this.id, userPartial.id) && + Objects.equals(this.firstname, userPartial.firstname) && + Objects.equals(this.lastname, userPartial.lastname) && + Objects.equals(this.fullname, userPartial.fullname) && + Objects.equals(this.email, userPartial.email) && + Objects.equals(this.employeeNumber, userPartial.employeeNumber) && + Objects.equals(this.externalId, userPartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, firstname, lastname, fullname, email, employeeNumber, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UserPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/UserUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/UserUpdate.java new file mode 100644 index 0000000..a7a0e27 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/UserUpdate.java @@ -0,0 +1,374 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UserUpdate + */ +@JsonPropertyOrder({ + UserUpdate.JSON_PROPERTY_LOGIN, + UserUpdate.JSON_PROPERTY_FIRSTNAME, + UserUpdate.JSON_PROPERTY_LASTNAME, + UserUpdate.JSON_PROPERTY_EMAIL, + UserUpdate.JSON_PROPERTY_ENTRY_DATE, + UserUpdate.JSON_PROPERTY_RESIGN_DATE, + UserUpdate.JSON_PROPERTY_EMPLOYEE_NUMBER, + UserUpdate.JSON_PROPERTY_EXTERNAL_ID, + UserUpdate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UserUpdate { + public static final String JSON_PROPERTY_LOGIN = "login"; + + private JsonNullable<@Nullable String> login = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_FIRSTNAME = "firstname"; + + private JsonNullable<@Nullable String> firstname = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LASTNAME = "lastname"; + + private JsonNullable<@Nullable String> lastname = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EMAIL = "email"; + + private JsonNullable<@Nullable String> email = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ENTRY_DATE = "entry_date"; + + private JsonNullable<@Nullable LocalDate> entryDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RESIGN_DATE = "resign_date"; + + private JsonNullable<@Nullable LocalDate> resignDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EMPLOYEE_NUMBER = "employee_number"; + + private JsonNullable<@Nullable String> employeeNumber = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private JsonNullable<@Nullable String> externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public UserUpdate() { + } + + public UserUpdate login(@Nullable String login) { + this.login = JsonNullable.of(login); + + return this; + } + + /** + * Get login + * @return login + */ + + @JsonProperty(value = JSON_PROPERTY_LOGIN, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getLogin() { + return login; + } + + @JsonProperty(JSON_PROPERTY_LOGIN) + public void setLogin(JsonNullable login) { + this.login = login; + } + + + + public UserUpdate firstname(@Nullable String firstname) { + this.firstname = JsonNullable.of(firstname); + + return this; + } + + /** + * Get firstname + * @return firstname + */ + + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getFirstname() { + return firstname; + } + + @JsonProperty(JSON_PROPERTY_FIRSTNAME) + public void setFirstname(JsonNullable firstname) { + this.firstname = firstname; + } + + + + public UserUpdate lastname(@Nullable String lastname) { + this.lastname = JsonNullable.of(lastname); + + return this; + } + + /** + * Get lastname + * @return lastname + */ + + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getLastname() { + return lastname; + } + + @JsonProperty(JSON_PROPERTY_LASTNAME) + public void setLastname(JsonNullable lastname) { + this.lastname = lastname; + } + + + + public UserUpdate email(@Nullable String email) { + this.email = JsonNullable.of(email); + + return this; + } + + /** + * Get email + * @return email + */ + + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEmail() { + return email; + } + + @JsonProperty(JSON_PROPERTY_EMAIL) + public void setEmail(JsonNullable email) { + this.email = email; + } + + + + public UserUpdate entryDate(@Nullable LocalDate entryDate) { + this.entryDate = JsonNullable.of(entryDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return entryDate + */ + + @JsonProperty(value = JSON_PROPERTY_ENTRY_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getEntryDate() { + return entryDate; + } + + @JsonProperty(JSON_PROPERTY_ENTRY_DATE) + public void setEntryDate(JsonNullable entryDate) { + this.entryDate = entryDate; + } + + + + public UserUpdate resignDate(@Nullable LocalDate resignDate) { + this.resignDate = JsonNullable.of(resignDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return resignDate + */ + + @JsonProperty(value = JSON_PROPERTY_RESIGN_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getResignDate() { + return resignDate; + } + + @JsonProperty(JSON_PROPERTY_RESIGN_DATE) + public void setResignDate(JsonNullable resignDate) { + this.resignDate = resignDate; + } + + + + public UserUpdate employeeNumber(@Nullable String employeeNumber) { + this.employeeNumber = JsonNullable.of(employeeNumber); + + return this; + } + + /** + * Get employeeNumber + * @return employeeNumber + */ + + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getEmployeeNumber() { + return employeeNumber; + } + + @JsonProperty(JSON_PROPERTY_EMPLOYEE_NUMBER) + public void setEmployeeNumber(JsonNullable employeeNumber) { + this.employeeNumber = employeeNumber; + } + + + + public UserUpdate externalId(@Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Get externalId + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public UserUpdate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public UserUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserUpdate userUpdate = (UserUpdate) o; + return equalsNullable(this.login, userUpdate.login) && + equalsNullable(this.firstname, userUpdate.firstname) && + equalsNullable(this.lastname, userUpdate.lastname) && + equalsNullable(this.email, userUpdate.email) && + equalsNullable(this.entryDate, userUpdate.entryDate) && + equalsNullable(this.resignDate, userUpdate.resignDate) && + equalsNullable(this.employeeNumber, userUpdate.employeeNumber) && + equalsNullable(this.externalId, userUpdate.externalId) && + equalsNullable(this.metadata, userUpdate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(login), hashCodeNullable(firstname), hashCodeNullable(lastname), hashCodeNullable(email), hashCodeNullable(entryDate), hashCodeNullable(resignDate), hashCodeNullable(employeeNumber), hashCodeNullable(externalId), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UserUpdate {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/UsersPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/UsersPage.java new file mode 100644 index 0000000..47c8bf2 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/UsersPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.User; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UsersPage + */ +@JsonPropertyOrder({ + UsersPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + UsersPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UsersPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public UsersPage() { + } + + public UsersPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public UsersPage data(List data) { + + this.data = data; + return this; + } + + public UsersPage addDataItem(User dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UsersPage usersPage = (UsersPage) o; + return Objects.equals(this.nextPageToken, usersPage.nextPageToken) && + Objects.equals(this.data, usersPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UsersPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/UsersPartialPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/UsersPartialPage.java new file mode 100644 index 0000000..a01ace2 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/UsersPartialPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UsersPartialPage + */ +@JsonPropertyOrder({ + UsersPartialPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + UsersPartialPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UsersPartialPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public UsersPartialPage() { + } + + public UsersPartialPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public UsersPartialPage data(List data) { + + this.data = data; + return this; + } + + public UsersPartialPage addDataItem(UserPartial dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UsersPartialPage usersPartialPage = (UsersPartialPage) o; + return Objects.equals(this.nextPageToken, usersPartialPage.nextPageToken) && + Objects.equals(this.data, usersPartialPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UsersPartialPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/UsersSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/UsersSortColumn.java new file mode 100644 index 0000000..ad1c4ea --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/UsersSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Users. `name` orders by last name, then first name. + */ +public enum UsersSortColumn { + + NAME("name"); + + private String value; + + UsersSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static UsersSortColumn fromValue(String value) { + for (UsersSortColumn b : UsersSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccount.java b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccount.java new file mode 100644 index 0000000..20058cd --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccount.java @@ -0,0 +1,52 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.VacationAccountDays; +import com.timr.api.models.VacationAccountMinutes; +import com.timr.api.models.VacationUnit; +import java.math.BigDecimal; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@JsonIgnoreProperties( + value = "unit", // ignore manually set unit, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the unit to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "unit", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = VacationAccountDays.class, name = "days"), + @JsonSubTypes.Type(value = VacationAccountMinutes.class, name = "minutes"), +}) + +public interface VacationAccount { + public VacationUnit getUnit(); +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccountBase.java b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccountBase.java new file mode 100644 index 0000000..def1594 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccountBase.java @@ -0,0 +1,118 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.VacationUnit; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Members shared by every kind of vacation account, including the discriminator. + */ +@JsonPropertyOrder({ + VacationAccountBase.JSON_PROPERTY_UNIT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class VacationAccountBase { + public static final String JSON_PROPERTY_UNIT = "unit"; + + protected VacationUnit unit; + + public VacationAccountBase() { + } + + public VacationAccountBase unit(VacationUnit unit) { + + this.unit = unit; + return this; + } + + /** + * Get unit + * @return unit + */ + + @JsonProperty(value = JSON_PROPERTY_UNIT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public VacationUnit getUnit() { + return unit; + } + + + @JsonProperty(value = JSON_PROPERTY_UNIT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUnit(VacationUnit unit) { + this.unit = unit; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VacationAccountBase vacationAccountBase = (VacationAccountBase) o; + return Objects.equals(this.unit, vacationAccountBase.unit); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(unit); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class VacationAccountBase {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccountDays.java b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccountDays.java new file mode 100644 index 0000000..7bbe0a5 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccountDays.java @@ -0,0 +1,215 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.VacationAccountBase; +import com.timr.api.models.VacationUnit; +import java.math.BigDecimal; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * VacationAccountDays + */ +@JsonPropertyOrder({ + VacationAccountDays.JSON_PROPERTY_BALANCE_LAST_PERIOD_DAYS, + VacationAccountDays.JSON_PROPERTY_CONSUMED_DAYS, + VacationAccountDays.JSON_PROPERTY_NEW_DAYS, + VacationAccountDays.JSON_PROPERTY_BALANCE_TOTAL_DAYS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class VacationAccountDays extends VacationAccountBase implements VacationAccount { + public static final String JSON_PROPERTY_BALANCE_LAST_PERIOD_DAYS = "balance_last_period_days"; + + private JsonNullable<@Nullable BigDecimal> balanceLastPeriodDays = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CONSUMED_DAYS = "consumed_days"; + + private JsonNullable<@Nullable BigDecimal> consumedDays = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NEW_DAYS = "new_days"; + + private JsonNullable<@Nullable BigDecimal> newDays = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BALANCE_TOTAL_DAYS = "balance_total_days"; + + private JsonNullable<@Nullable BigDecimal> balanceTotalDays = JsonNullable.undefined(); + + public VacationAccountDays() { + + } + + public VacationAccountDays balanceLastPeriodDays(@Nullable BigDecimal balanceLastPeriodDays) { + this.balanceLastPeriodDays = JsonNullable.of(balanceLastPeriodDays); + + return this; + } + + /** + * vacation balance carried over from the previous vacation period, in days + * @return balanceLastPeriodDays + */ + + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_DAYS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBalanceLastPeriodDays() { + return balanceLastPeriodDays; + } + + @JsonProperty(JSON_PROPERTY_BALANCE_LAST_PERIOD_DAYS) + public void setBalanceLastPeriodDays(JsonNullable balanceLastPeriodDays) { + this.balanceLastPeriodDays = balanceLastPeriodDays; + } + + + + public VacationAccountDays consumedDays(@Nullable BigDecimal consumedDays) { + this.consumedDays = JsonNullable.of(consumedDays); + + return this; + } + + /** + * vacation consumed in the current vacation period, in days + * @return consumedDays + */ + + @JsonProperty(value = JSON_PROPERTY_CONSUMED_DAYS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getConsumedDays() { + return consumedDays; + } + + @JsonProperty(JSON_PROPERTY_CONSUMED_DAYS) + public void setConsumedDays(JsonNullable consumedDays) { + this.consumedDays = consumedDays; + } + + + + public VacationAccountDays newDays(@Nullable BigDecimal newDays) { + this.newDays = JsonNullable.of(newDays); + + return this; + } + + /** + * vacation newly granted in the current vacation period, in days + * @return newDays + */ + + @JsonProperty(value = JSON_PROPERTY_NEW_DAYS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getNewDays() { + return newDays; + } + + @JsonProperty(JSON_PROPERTY_NEW_DAYS) + public void setNewDays(JsonNullable newDays) { + this.newDays = newDays; + } + + + + public VacationAccountDays balanceTotalDays(@Nullable BigDecimal balanceTotalDays) { + this.balanceTotalDays = JsonNullable.of(balanceTotalDays); + + return this; + } + + /** + * total vacation balance for the current vacation period, in days + * @return balanceTotalDays + */ + + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_DAYS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBalanceTotalDays() { + return balanceTotalDays; + } + + @JsonProperty(JSON_PROPERTY_BALANCE_TOTAL_DAYS) + public void setBalanceTotalDays(JsonNullable balanceTotalDays) { + this.balanceTotalDays = balanceTotalDays; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VacationAccountDays vacationAccountDays = (VacationAccountDays) o; + return equalsNullable(this.balanceLastPeriodDays, vacationAccountDays.balanceLastPeriodDays) && + equalsNullable(this.consumedDays, vacationAccountDays.consumedDays) && + equalsNullable(this.newDays, vacationAccountDays.newDays) && + equalsNullable(this.balanceTotalDays, vacationAccountDays.balanceTotalDays) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(balanceLastPeriodDays), hashCodeNullable(consumedDays), hashCodeNullable(newDays), hashCodeNullable(balanceTotalDays), super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class VacationAccountDays {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccountMinutes.java b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccountMinutes.java new file mode 100644 index 0000000..492c8f9 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationAccountMinutes.java @@ -0,0 +1,215 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.VacationAccountBase; +import com.timr.api.models.VacationUnit; +import java.math.BigDecimal; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * VacationAccountMinutes + */ +@JsonPropertyOrder({ + VacationAccountMinutes.JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, + VacationAccountMinutes.JSON_PROPERTY_CONSUMED_MINUTES, + VacationAccountMinutes.JSON_PROPERTY_NEW_MINUTES, + VacationAccountMinutes.JSON_PROPERTY_BALANCE_TOTAL_MINUTES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class VacationAccountMinutes extends VacationAccountBase implements VacationAccount { + public static final String JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES = "balance_last_period_minutes"; + + private JsonNullable<@Nullable BigDecimal> balanceLastPeriodMinutes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CONSUMED_MINUTES = "consumed_minutes"; + + private JsonNullable<@Nullable BigDecimal> consumedMinutes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NEW_MINUTES = "new_minutes"; + + private JsonNullable<@Nullable BigDecimal> newMinutes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BALANCE_TOTAL_MINUTES = "balance_total_minutes"; + + private JsonNullable<@Nullable BigDecimal> balanceTotalMinutes = JsonNullable.undefined(); + + public VacationAccountMinutes() { + + } + + public VacationAccountMinutes balanceLastPeriodMinutes(@Nullable BigDecimal balanceLastPeriodMinutes) { + this.balanceLastPeriodMinutes = JsonNullable.of(balanceLastPeriodMinutes); + + return this; + } + + /** + * vacation balance carried over from the previous vacation period, in minutes + * @return balanceLastPeriodMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBalanceLastPeriodMinutes() { + return balanceLastPeriodMinutes; + } + + @JsonProperty(JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES) + public void setBalanceLastPeriodMinutes(JsonNullable balanceLastPeriodMinutes) { + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + } + + + + public VacationAccountMinutes consumedMinutes(@Nullable BigDecimal consumedMinutes) { + this.consumedMinutes = JsonNullable.of(consumedMinutes); + + return this; + } + + /** + * vacation consumed in the current vacation period, in minutes + * @return consumedMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_CONSUMED_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getConsumedMinutes() { + return consumedMinutes; + } + + @JsonProperty(JSON_PROPERTY_CONSUMED_MINUTES) + public void setConsumedMinutes(JsonNullable consumedMinutes) { + this.consumedMinutes = consumedMinutes; + } + + + + public VacationAccountMinutes newMinutes(@Nullable BigDecimal newMinutes) { + this.newMinutes = JsonNullable.of(newMinutes); + + return this; + } + + /** + * vacation newly granted in the current vacation period, in minutes + * @return newMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_NEW_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getNewMinutes() { + return newMinutes; + } + + @JsonProperty(JSON_PROPERTY_NEW_MINUTES) + public void setNewMinutes(JsonNullable newMinutes) { + this.newMinutes = newMinutes; + } + + + + public VacationAccountMinutes balanceTotalMinutes(@Nullable BigDecimal balanceTotalMinutes) { + this.balanceTotalMinutes = JsonNullable.of(balanceTotalMinutes); + + return this; + } + + /** + * total vacation balance for the current vacation period, in minutes + * @return balanceTotalMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable BigDecimal> getBalanceTotalMinutes() { + return balanceTotalMinutes; + } + + @JsonProperty(JSON_PROPERTY_BALANCE_TOTAL_MINUTES) + public void setBalanceTotalMinutes(JsonNullable balanceTotalMinutes) { + this.balanceTotalMinutes = balanceTotalMinutes; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VacationAccountMinutes vacationAccountMinutes = (VacationAccountMinutes) o; + return equalsNullable(this.balanceLastPeriodMinutes, vacationAccountMinutes.balanceLastPeriodMinutes) && + equalsNullable(this.consumedMinutes, vacationAccountMinutes.consumedMinutes) && + equalsNullable(this.newMinutes, vacationAccountMinutes.newMinutes) && + equalsNullable(this.balanceTotalMinutes, vacationAccountMinutes.balanceTotalMinutes) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(balanceLastPeriodMinutes), hashCodeNullable(consumedMinutes), hashCodeNullable(newMinutes), hashCodeNullable(balanceTotalMinutes), super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class VacationAccountMinutes {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/VacationUnit.java b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationUnit.java new file mode 100644 index 0000000..5d08e68 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/VacationUnit.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Unit a vacation entitlement is expressed in. + */ +public enum VacationUnit { + + DAYS("days"), + + MINUTES("minutes"); + + private String value; + + VacationUnit(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static VacationUnit fromValue(String value) { + for (VacationUnit b : VacationUnit.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/VenuePartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/VenuePartial.java new file mode 100644 index 0000000..64e5da9 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/VenuePartial.java @@ -0,0 +1,370 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * VenuePartial + */ +@JsonPropertyOrder({ + VenuePartial.JSON_PROPERTY_ID, + VenuePartial.JSON_PROPERTY_NAME, + VenuePartial.JSON_PROPERTY_CITY, + VenuePartial.JSON_PROPERTY_ZIP_CODE, + VenuePartial.JSON_PROPERTY_STREET, + VenuePartial.JSON_PROPERTY_STREET_NUMBER, + VenuePartial.JSON_PROPERTY_COUNTRY, + VenuePartial.JSON_PROPERTY_LAT, + VenuePartial.JSON_PROPERTY_LON +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class VenuePartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_CITY = "city"; + + private String city; + + public static final String JSON_PROPERTY_ZIP_CODE = "zip_code"; + + private String zipCode; + + public static final String JSON_PROPERTY_STREET = "street"; + + private String street; + + public static final String JSON_PROPERTY_STREET_NUMBER = "street_number"; + + private String streetNumber; + + public static final String JSON_PROPERTY_COUNTRY = "country"; + + private String country; + + public static final String JSON_PROPERTY_LAT = "lat"; + + private JsonNullable<@Nullable Float> lat = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LON = "lon"; + + private JsonNullable<@Nullable Float> lon = JsonNullable.undefined(); + + public VenuePartial() { + } + + public VenuePartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public VenuePartial name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public VenuePartial city(String city) { + + this.city = city; + return this; + } + + /** + * Get city + * @return city + */ + + @JsonProperty(value = JSON_PROPERTY_CITY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCity() { + return city; + } + + + @JsonProperty(value = JSON_PROPERTY_CITY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCity(String city) { + this.city = city; + } + + + public VenuePartial zipCode(String zipCode) { + + this.zipCode = zipCode; + return this; + } + + /** + * Get zipCode + * @return zipCode + */ + + @JsonProperty(value = JSON_PROPERTY_ZIP_CODE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getZipCode() { + return zipCode; + } + + + @JsonProperty(value = JSON_PROPERTY_ZIP_CODE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } + + + public VenuePartial street(String street) { + + this.street = street; + return this; + } + + /** + * Get street + * @return street + */ + + @JsonProperty(value = JSON_PROPERTY_STREET, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getStreet() { + return street; + } + + + @JsonProperty(value = JSON_PROPERTY_STREET, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStreet(String street) { + this.street = street; + } + + + public VenuePartial streetNumber(String streetNumber) { + + this.streetNumber = streetNumber; + return this; + } + + /** + * Get streetNumber + * @return streetNumber + */ + + @JsonProperty(value = JSON_PROPERTY_STREET_NUMBER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getStreetNumber() { + return streetNumber; + } + + + @JsonProperty(value = JSON_PROPERTY_STREET_NUMBER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStreetNumber(String streetNumber) { + this.streetNumber = streetNumber; + } + + + public VenuePartial country(String country) { + + this.country = country; + return this; + } + + /** + * Get country + * @return country + */ + + @JsonProperty(value = JSON_PROPERTY_COUNTRY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCountry() { + return country; + } + + + @JsonProperty(value = JSON_PROPERTY_COUNTRY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCountry(String country) { + this.country = country; + } + + + public VenuePartial lat(@Nullable Float lat) { + this.lat = JsonNullable.of(lat); + + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Float> getLat() { + return lat; + } + + @JsonProperty(JSON_PROPERTY_LAT) + public void setLat(JsonNullable lat) { + this.lat = lat; + } + + + + public VenuePartial lon(@Nullable Float lon) { + this.lon = JsonNullable.of(lon); + + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Float> getLon() { + return lon; + } + + @JsonProperty(JSON_PROPERTY_LON) + public void setLon(JsonNullable lon) { + this.lon = lon; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VenuePartial venuePartial = (VenuePartial) o; + return Objects.equals(this.id, venuePartial.id) && + Objects.equals(this.name, venuePartial.name) && + Objects.equals(this.city, venuePartial.city) && + Objects.equals(this.zipCode, venuePartial.zipCode) && + Objects.equals(this.street, venuePartial.street) && + Objects.equals(this.streetNumber, venuePartial.streetNumber) && + Objects.equals(this.country, venuePartial.country) && + equalsNullable(this.lat, venuePartial.lat) && + equalsNullable(this.lon, venuePartial.lon); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, city, zipCode, street, streetNumber, country, hashCodeNullable(lat), hashCodeNullable(lon)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class VenuePartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/Waypoint.java b/sdk/java-restclient/src/main/java/com/timr/api/models/Waypoint.java new file mode 100644 index 0000000..227a103 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/Waypoint.java @@ -0,0 +1,149 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Waypoint + */ +@JsonPropertyOrder({ + Waypoint.JSON_PROPERTY_LAT, + Waypoint.JSON_PROPERTY_LON +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Waypoint { + public static final String JSON_PROPERTY_LAT = "lat"; + + private Double lat; + + public static final String JSON_PROPERTY_LON = "lon"; + + private Double lon; + + public Waypoint() { + } + + public Waypoint lat(Double lat) { + + this.lat = lat; + return this; + } + + /** + * Get lat + * @return lat + */ + + @JsonProperty(value = JSON_PROPERTY_LAT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Double getLat() { + return lat; + } + + + @JsonProperty(value = JSON_PROPERTY_LAT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLat(Double lat) { + this.lat = lat; + } + + + public Waypoint lon(Double lon) { + + this.lon = lon; + return this; + } + + /** + * Get lon + * @return lon + */ + + @JsonProperty(value = JSON_PROPERTY_LON, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Double getLon() { + return lon; + } + + + @JsonProperty(value = JSON_PROPERTY_LON, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLon(Double lon) { + this.lon = lon; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Waypoint waypoint = (Waypoint) o; + return Objects.equals(this.lat, waypoint.lat) && + Objects.equals(this.lon, waypoint.lon); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lat, lon); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Waypoint {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModel.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModel.java new file mode 100644 index 0000000..383eb95 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModel.java @@ -0,0 +1,261 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkScheduleModelType; +import com.timr.api.models.WorkScheduleModelWeek; +import com.timr.api.models.WorkingTimeRules; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * The weekday targets a user is measured against: `weeks` holds the layout, `type` selects the calculation mode, and `working_time_rules` the recording constraints. + */ +@JsonPropertyOrder({ + WorkScheduleModel.JSON_PROPERTY_ID, + WorkScheduleModel.JSON_PROPERTY_NAME, + WorkScheduleModel.JSON_PROPERTY_TYPE, + WorkScheduleModel.JSON_PROPERTY_WEEKS, + WorkScheduleModel.JSON_PROPERTY_WORKING_TIME_RULES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkScheduleModel { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_TYPE = "type"; + + private WorkScheduleModelType type; + + public static final String JSON_PROPERTY_WEEKS = "weeks"; + + private List weeks; + + public static final String JSON_PROPERTY_WORKING_TIME_RULES = "working_time_rules"; + + private @Nullable WorkingTimeRules workingTimeRules; + + public WorkScheduleModel() { + } + + public WorkScheduleModel id(String id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public WorkScheduleModel name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public WorkScheduleModel type(WorkScheduleModelType type) { + + this.type = type; + return this; + } + + /** + * working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks) + * @return type + */ + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkScheduleModelType getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(WorkScheduleModelType type) { + this.type = type; + } + + + public WorkScheduleModel weeks(List weeks) { + + this.weeks = weeks; + return this; + } + + public WorkScheduleModel addWeeksItem(WorkScheduleModelWeek weeksItem) { + if (this.weeks == null) { + this.weeks = new ArrayList<>(); + } + this.weeks.add(weeksItem); + return this; + } + + /** + * for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name + * @return weeks + */ + + @JsonProperty(value = JSON_PROPERTY_WEEKS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getWeeks() { + return weeks; + } + + + @JsonProperty(value = JSON_PROPERTY_WEEKS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWeeks(List weeks) { + this.weeks = weeks; + } + + + public WorkScheduleModel workingTimeRules(@Nullable WorkingTimeRules workingTimeRules) { + + this.workingTimeRules = workingTimeRules; + return this; + } + + /** + * Get workingTimeRules + * @return workingTimeRules + */ + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_RULES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable WorkingTimeRules getWorkingTimeRules() { + return workingTimeRules; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_RULES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeRules(@Nullable WorkingTimeRules workingTimeRules) { + this.workingTimeRules = workingTimeRules; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkScheduleModel workScheduleModel = (WorkScheduleModel) o; + return Objects.equals(this.id, workScheduleModel.id) && + Objects.equals(this.name, workScheduleModel.name) && + Objects.equals(this.type, workScheduleModel.type) && + Objects.equals(this.weeks, workScheduleModel.weeks) && + Objects.equals(this.workingTimeRules, workScheduleModel.workingTimeRules); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, type, weeks, workingTimeRules); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkScheduleModel {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelPartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelPartial.java new file mode 100644 index 0000000..c51c252 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelPartial.java @@ -0,0 +1,150 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkScheduleModelPartial + */ +@JsonPropertyOrder({ + WorkScheduleModelPartial.JSON_PROPERTY_ID, + WorkScheduleModelPartial.JSON_PROPERTY_NAME +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkScheduleModelPartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public WorkScheduleModelPartial() { + } + + public WorkScheduleModelPartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public WorkScheduleModelPartial name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkScheduleModelPartial workScheduleModelPartial = (WorkScheduleModelPartial) o; + return Objects.equals(this.id, workScheduleModelPartial.id) && + Objects.equals(this.name, workScheduleModelPartial.name); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkScheduleModelPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelSortColumn.java new file mode 100644 index 0000000..4bddf27 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Work Schedule Models. + */ +public enum WorkScheduleModelSortColumn { + + NAME("name"); + + private String value; + + WorkScheduleModelSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkScheduleModelSortColumn fromValue(String value) { + for (WorkScheduleModelSortColumn b : WorkScheduleModelSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelType.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelType.java new file mode 100644 index 0000000..85b1f9b --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelType.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * How the target working time of the model is defined. + */ +public enum WorkScheduleModelType { + + DAILY_TARGET_HOURS("daily_target_hours"), + + NORMAL_WORKING_TIME("normal_working_time"); + + private String value; + + WorkScheduleModelType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkScheduleModelType fromValue(String value) { + for (WorkScheduleModelType b : WorkScheduleModelType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelWeek.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelWeek.java new file mode 100644 index 0000000..5374113 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelWeek.java @@ -0,0 +1,406 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DailyWorkSchedule; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkScheduleModelWeek + */ +@JsonPropertyOrder({ + WorkScheduleModelWeek.JSON_PROPERTY_WEEK_NUMBER, + WorkScheduleModelWeek.JSON_PROPERTY_NAME, + WorkScheduleModelWeek.JSON_PROPERTY_TARGET_DURATION_WEEKLY_MINUTES, + WorkScheduleModelWeek.JSON_PROPERTY_MONDAY, + WorkScheduleModelWeek.JSON_PROPERTY_TUESDAY, + WorkScheduleModelWeek.JSON_PROPERTY_WEDNESDAY, + WorkScheduleModelWeek.JSON_PROPERTY_THURSDAY, + WorkScheduleModelWeek.JSON_PROPERTY_FRIDAY, + WorkScheduleModelWeek.JSON_PROPERTY_SATURDAY, + WorkScheduleModelWeek.JSON_PROPERTY_SUNDAY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkScheduleModelWeek { + public static final String JSON_PROPERTY_WEEK_NUMBER = "week_number"; + + private JsonNullable<@Nullable Integer> weekNumber = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NAME = "name"; + + private JsonNullable<@Nullable String> name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TARGET_DURATION_WEEKLY_MINUTES = "target_duration_weekly_minutes"; + + private Long targetDurationWeeklyMinutes; + + public static final String JSON_PROPERTY_MONDAY = "monday"; + + private DailyWorkSchedule monday; + + public static final String JSON_PROPERTY_TUESDAY = "tuesday"; + + private DailyWorkSchedule tuesday; + + public static final String JSON_PROPERTY_WEDNESDAY = "wednesday"; + + private DailyWorkSchedule wednesday; + + public static final String JSON_PROPERTY_THURSDAY = "thursday"; + + private DailyWorkSchedule thursday; + + public static final String JSON_PROPERTY_FRIDAY = "friday"; + + private DailyWorkSchedule friday; + + public static final String JSON_PROPERTY_SATURDAY = "saturday"; + + private DailyWorkSchedule saturday; + + public static final String JSON_PROPERTY_SUNDAY = "sunday"; + + private DailyWorkSchedule sunday; + + public WorkScheduleModelWeek() { + } + + public WorkScheduleModelWeek weekNumber(@Nullable Integer weekNumber) { + this.weekNumber = JsonNullable.of(weekNumber); + + return this; + } + + /** + * index of the week in alternating_weeks models (0-based); omitted for fixed_week models + * @return weekNumber + */ + + @JsonProperty(value = JSON_PROPERTY_WEEK_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Integer> getWeekNumber() { + return weekNumber; + } + + @JsonProperty(JSON_PROPERTY_WEEK_NUMBER) + public void setWeekNumber(JsonNullable weekNumber) { + this.weekNumber = weekNumber; + } + + + + public WorkScheduleModelWeek name(@Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * display name of the week in alternating_weeks models; omitted for fixed_week models + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public WorkScheduleModelWeek targetDurationWeeklyMinutes(Long targetDurationWeeklyMinutes) { + + this.targetDurationWeeklyMinutes = targetDurationWeeklyMinutes; + return this; + } + + /** + * value in minutes + * @return targetDurationWeeklyMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_TARGET_DURATION_WEEKLY_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getTargetDurationWeeklyMinutes() { + return targetDurationWeeklyMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_TARGET_DURATION_WEEKLY_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTargetDurationWeeklyMinutes(Long targetDurationWeeklyMinutes) { + this.targetDurationWeeklyMinutes = targetDurationWeeklyMinutes; + } + + + public WorkScheduleModelWeek monday(DailyWorkSchedule monday) { + + this.monday = monday; + return this; + } + + /** + * Get monday + * @return monday + */ + + @JsonProperty(value = JSON_PROPERTY_MONDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getMonday() { + return monday; + } + + + @JsonProperty(value = JSON_PROPERTY_MONDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setMonday(DailyWorkSchedule monday) { + this.monday = monday; + } + + + public WorkScheduleModelWeek tuesday(DailyWorkSchedule tuesday) { + + this.tuesday = tuesday; + return this; + } + + /** + * Get tuesday + * @return tuesday + */ + + @JsonProperty(value = JSON_PROPERTY_TUESDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getTuesday() { + return tuesday; + } + + + @JsonProperty(value = JSON_PROPERTY_TUESDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTuesday(DailyWorkSchedule tuesday) { + this.tuesday = tuesday; + } + + + public WorkScheduleModelWeek wednesday(DailyWorkSchedule wednesday) { + + this.wednesday = wednesday; + return this; + } + + /** + * Get wednesday + * @return wednesday + */ + + @JsonProperty(value = JSON_PROPERTY_WEDNESDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getWednesday() { + return wednesday; + } + + + @JsonProperty(value = JSON_PROPERTY_WEDNESDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWednesday(DailyWorkSchedule wednesday) { + this.wednesday = wednesday; + } + + + public WorkScheduleModelWeek thursday(DailyWorkSchedule thursday) { + + this.thursday = thursday; + return this; + } + + /** + * Get thursday + * @return thursday + */ + + @JsonProperty(value = JSON_PROPERTY_THURSDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getThursday() { + return thursday; + } + + + @JsonProperty(value = JSON_PROPERTY_THURSDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setThursday(DailyWorkSchedule thursday) { + this.thursday = thursday; + } + + + public WorkScheduleModelWeek friday(DailyWorkSchedule friday) { + + this.friday = friday; + return this; + } + + /** + * Get friday + * @return friday + */ + + @JsonProperty(value = JSON_PROPERTY_FRIDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getFriday() { + return friday; + } + + + @JsonProperty(value = JSON_PROPERTY_FRIDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFriday(DailyWorkSchedule friday) { + this.friday = friday; + } + + + public WorkScheduleModelWeek saturday(DailyWorkSchedule saturday) { + + this.saturday = saturday; + return this; + } + + /** + * Get saturday + * @return saturday + */ + + @JsonProperty(value = JSON_PROPERTY_SATURDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getSaturday() { + return saturday; + } + + + @JsonProperty(value = JSON_PROPERTY_SATURDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSaturday(DailyWorkSchedule saturday) { + this.saturday = saturday; + } + + + public WorkScheduleModelWeek sunday(DailyWorkSchedule sunday) { + + this.sunday = sunday; + return this; + } + + /** + * Get sunday + * @return sunday + */ + + @JsonProperty(value = JSON_PROPERTY_SUNDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getSunday() { + return sunday; + } + + + @JsonProperty(value = JSON_PROPERTY_SUNDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSunday(DailyWorkSchedule sunday) { + this.sunday = sunday; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkScheduleModelWeek workScheduleModelWeek = (WorkScheduleModelWeek) o; + return equalsNullable(this.weekNumber, workScheduleModelWeek.weekNumber) && + equalsNullable(this.name, workScheduleModelWeek.name) && + Objects.equals(this.targetDurationWeeklyMinutes, workScheduleModelWeek.targetDurationWeeklyMinutes) && + Objects.equals(this.monday, workScheduleModelWeek.monday) && + Objects.equals(this.tuesday, workScheduleModelWeek.tuesday) && + Objects.equals(this.wednesday, workScheduleModelWeek.wednesday) && + Objects.equals(this.thursday, workScheduleModelWeek.thursday) && + Objects.equals(this.friday, workScheduleModelWeek.friday) && + Objects.equals(this.saturday, workScheduleModelWeek.saturday) && + Objects.equals(this.sunday, workScheduleModelWeek.sunday); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(weekNumber), hashCodeNullable(name), targetDurationWeeklyMinutes, monday, tuesday, wednesday, thursday, friday, saturday, sunday); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkScheduleModelWeek {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelsPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelsPage.java new file mode 100644 index 0000000..fd512c6 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkScheduleModelsPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkScheduleModel; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkScheduleModelsPage + */ +@JsonPropertyOrder({ + WorkScheduleModelsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + WorkScheduleModelsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkScheduleModelsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public WorkScheduleModelsPage() { + } + + public WorkScheduleModelsPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public WorkScheduleModelsPage data(List data) { + + this.data = data; + return this; + } + + public WorkScheduleModelsPage addDataItem(WorkScheduleModel dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkScheduleModelsPage workScheduleModelsPage = (WorkScheduleModelsPage) o; + return Objects.equals(this.nextPageToken, workScheduleModelsPage.nextPageToken) && + Objects.equals(this.data, workScheduleModelsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkScheduleModelsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTime.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTime.java new file mode 100644 index 0000000..46b8fba --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTime.java @@ -0,0 +1,736 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTime; +import com.timr.api.models.Duration; +import com.timr.api.models.Location; +import com.timr.api.models.Platform; +import com.timr.api.models.UserPartial; +import com.timr.api.models.WorkingTimeDateSpanPartial; +import com.timr.api.models.WorkingTimeStatus; +import com.timr.api.models.WorkingTimeTypePartial; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * One continuous stretch from `start` to `end`, classified by its `working_time_type`. Attendance entries carry `break_times`, locations and the platform they were recorded on; an entry derived from a multi-day absence links back to its `working_time_date_span`. + */ +@JsonPropertyOrder({ + WorkingTime.JSON_PROPERTY_ID, + WorkingTime.JSON_PROPERTY_START, + WorkingTime.JSON_PROPERTY_END, + WorkingTime.JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, + WorkingTime.JSON_PROPERTY_BREAK_TIMES, + WorkingTime.JSON_PROPERTY_DURATION, + WorkingTime.JSON_PROPERTY_CHANGED, + WorkingTime.JSON_PROPERTY_NOTES, + WorkingTime.JSON_PROPERTY_USER, + WorkingTime.JSON_PROPERTY_WORKING_TIME_TYPE, + WorkingTime.JSON_PROPERTY_WORKING_TIME_DATE_SPAN, + WorkingTime.JSON_PROPERTY_START_LOCATION, + WorkingTime.JSON_PROPERTY_END_LOCATION, + WorkingTime.JSON_PROPERTY_START_PLATFORM, + WorkingTime.JSON_PROPERTY_END_PLATFORM, + WorkingTime.JSON_PROPERTY_LAST_MODIFIED, + WorkingTime.JSON_PROPERTY_LAST_MODIFIED_BY, + WorkingTime.JSON_PROPERTY_STATUS, + WorkingTime.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTime { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_START = "start"; + + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + + private @Nullable OffsetDateTime end; + + public static final String JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES = "break_time_total_minutes"; + + private Integer breakTimeTotalMinutes; + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + + private List breakTimes; + + public static final String JSON_PROPERTY_DURATION = "duration"; + + private @Nullable Duration duration; + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private Boolean changed; + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private @Nullable String notes; + + public static final String JSON_PROPERTY_USER = "user"; + + private UserPartial user; + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE = "working_time_type"; + + private WorkingTimeTypePartial workingTimeType; + + public static final String JSON_PROPERTY_WORKING_TIME_DATE_SPAN = "working_time_date_span"; + + private @Nullable WorkingTimeDateSpanPartial workingTimeDateSpan; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + + private @Nullable Location startLocation; + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + + private @Nullable Location endLocation; + + public static final String JSON_PROPERTY_START_PLATFORM = "start_platform"; + + private @Nullable Platform startPlatform; + + public static final String JSON_PROPERTY_END_PLATFORM = "end_platform"; + + private @Nullable Platform endPlatform; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + + private @Nullable UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_STATUS = "status"; + + private WorkingTimeStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public WorkingTime() { + } + + public WorkingTime id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public WorkingTime start(OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(OffsetDateTime start) { + this.start = start; + } + + + public WorkingTime end(@Nullable OffsetDateTime end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable OffsetDateTime getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@Nullable OffsetDateTime end) { + this.end = end; + } + + + public WorkingTime breakTimeTotalMinutes(Integer breakTimeTotalMinutes) { + + this.breakTimeTotalMinutes = breakTimeTotalMinutes; + return this; + } + + /** + * Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + * @return breakTimeTotalMinutes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getBreakTimeTotalMinutes() { + return breakTimeTotalMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreakTimeTotalMinutes(Integer breakTimeTotalMinutes) { + this.breakTimeTotalMinutes = breakTimeTotalMinutes; + } + + + public WorkingTime breakTimes(List breakTimes) { + + this.breakTimes = breakTimes; + return this; + } + + public WorkingTime addBreakTimesItem(BreakTime breakTimesItem) { + if (this.breakTimes == null) { + this.breakTimes = new ArrayList<>(); + } + this.breakTimes.add(breakTimesItem); + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getBreakTimes() { + return breakTimes; + } + + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreakTimes(List breakTimes) { + this.breakTimes = breakTimes; + } + + + public WorkingTime duration(@Nullable Duration duration) { + + this.duration = duration; + return this; + } + + /** + * Get duration + * @return duration + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Duration getDuration() { + return duration; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDuration(@Nullable Duration duration) { + this.duration = duration; + } + + + public WorkingTime changed(Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(Boolean changed) { + this.changed = changed; + } + + + public WorkingTime notes(@Nullable String notes) { + + this.notes = notes; + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNotes() { + return notes; + } + + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNotes(@Nullable String notes) { + this.notes = notes; + } + + + public WorkingTime user(UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(UserPartial user) { + this.user = user; + } + + + public WorkingTime workingTimeType(WorkingTimeTypePartial workingTimeType) { + + this.workingTimeType = workingTimeType; + return this; + } + + /** + * Get workingTimeType + * @return workingTimeType + */ + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeTypePartial getWorkingTimeType() { + return workingTimeType; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeType(WorkingTimeTypePartial workingTimeType) { + this.workingTimeType = workingTimeType; + } + + + public WorkingTime workingTimeDateSpan(@Nullable WorkingTimeDateSpanPartial workingTimeDateSpan) { + + this.workingTimeDateSpan = workingTimeDateSpan; + return this; + } + + /** + * Get workingTimeDateSpan + * @return workingTimeDateSpan + */ + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_DATE_SPAN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable WorkingTimeDateSpanPartial getWorkingTimeDateSpan() { + return workingTimeDateSpan; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_DATE_SPAN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeDateSpan(@Nullable WorkingTimeDateSpanPartial workingTimeDateSpan) { + this.workingTimeDateSpan = workingTimeDateSpan; + } + + + public WorkingTime startLocation(@Nullable Location startLocation) { + + this.startLocation = startLocation; + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Location getStartLocation() { + return startLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartLocation(@Nullable Location startLocation) { + this.startLocation = startLocation; + } + + + public WorkingTime endLocation(@Nullable Location endLocation) { + + this.endLocation = endLocation; + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Location getEndLocation() { + return endLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndLocation(@Nullable Location endLocation) { + this.endLocation = endLocation; + } + + + public WorkingTime startPlatform(@Nullable Platform startPlatform) { + + this.startPlatform = startPlatform; + return this; + } + + /** + * Get startPlatform + * @return startPlatform + */ + + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Platform getStartPlatform() { + return startPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartPlatform(@Nullable Platform startPlatform) { + this.startPlatform = startPlatform; + } + + + public WorkingTime endPlatform(@Nullable Platform endPlatform) { + + this.endPlatform = endPlatform; + return this; + } + + /** + * Get endPlatform + * @return endPlatform + */ + + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable Platform getEndPlatform() { + return endPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndPlatform(@Nullable Platform endPlatform) { + this.endPlatform = endPlatform; + } + + + public WorkingTime lastModified(OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public WorkingTime lastModifiedBy(@Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public WorkingTime status(WorkingTimeStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(WorkingTimeStatus status) { + this.status = status; + } + + + public WorkingTime metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTime putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTime workingTime = (WorkingTime) o; + return Objects.equals(this.id, workingTime.id) && + Objects.equals(this.start, workingTime.start) && + Objects.equals(this.end, workingTime.end) && + Objects.equals(this.breakTimeTotalMinutes, workingTime.breakTimeTotalMinutes) && + Objects.equals(this.breakTimes, workingTime.breakTimes) && + Objects.equals(this.duration, workingTime.duration) && + Objects.equals(this.changed, workingTime.changed) && + Objects.equals(this.notes, workingTime.notes) && + Objects.equals(this.user, workingTime.user) && + Objects.equals(this.workingTimeType, workingTime.workingTimeType) && + Objects.equals(this.workingTimeDateSpan, workingTime.workingTimeDateSpan) && + Objects.equals(this.startLocation, workingTime.startLocation) && + Objects.equals(this.endLocation, workingTime.endLocation) && + Objects.equals(this.startPlatform, workingTime.startPlatform) && + Objects.equals(this.endPlatform, workingTime.endPlatform) && + Objects.equals(this.lastModified, workingTime.lastModified) && + Objects.equals(this.lastModifiedBy, workingTime.lastModifiedBy) && + Objects.equals(this.status, workingTime.status) && + equalsNullable(this.metadata, workingTime.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, start, end, breakTimeTotalMinutes, breakTimes, duration, changed, notes, user, workingTimeType, workingTimeDateSpan, startLocation, endLocation, startPlatform, endPlatform, lastModified, lastModifiedBy, status, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTime {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" workingTimeType: ").append(toIndentedString(workingTimeType)).append("\n"); + sb.append(" workingTimeDateSpan: ").append(toIndentedString(workingTimeDateSpan)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeCreate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeCreate.java new file mode 100644 index 0000000..c166aac --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeCreate.java @@ -0,0 +1,499 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.DurationType; +import com.timr.api.models.LocationCreate; +import com.timr.api.models.WorkingTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeCreate + */ +@JsonPropertyOrder({ + WorkingTimeCreate.JSON_PROPERTY_START, + WorkingTimeCreate.JSON_PROPERTY_END, + WorkingTimeCreate.JSON_PROPERTY_BREAK_TIMES, + WorkingTimeCreate.JSON_PROPERTY_DURATION_TYPE, + WorkingTimeCreate.JSON_PROPERTY_CHANGED, + WorkingTimeCreate.JSON_PROPERTY_NOTES, + WorkingTimeCreate.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeCreate.JSON_PROPERTY_STATUS, + WorkingTimeCreate.JSON_PROPERTY_METADATA, + WorkingTimeCreate.JSON_PROPERTY_USER_ID, + WorkingTimeCreate.JSON_PROPERTY_START_LOCATION, + WorkingTimeCreate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeCreate { + public static final String JSON_PROPERTY_START = "start"; + + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + + private JsonNullable<@Nullable List> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_DURATION_TYPE = "duration_type"; + + private JsonNullable<@Nullable DurationType> durationType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private Boolean changed; + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private JsonNullable<@Nullable String> notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + + private String workingTimeTypeId; + + public static final String JSON_PROPERTY_STATUS = "status"; + + private WorkingTimeStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_USER_ID = "user_id"; + + private String userId; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + + private JsonNullable<@Nullable LocationCreate> startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + + private JsonNullable<@Nullable LocationCreate> endLocation = JsonNullable.undefined(); + + public WorkingTimeCreate() { + } + + public WorkingTimeCreate start(OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(OffsetDateTime start) { + this.start = start; + } + + + public WorkingTimeCreate end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public WorkingTimeCreate breakTimes(@Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public WorkingTimeCreate addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable List> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public WorkingTimeCreate durationType(@Nullable DurationType durationType) { + this.durationType = JsonNullable.of(durationType); + + return this; + } + + /** + * Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @return durationType + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable DurationType> getDurationType() { + return durationType; + } + + @JsonProperty(JSON_PROPERTY_DURATION_TYPE) + public void setDurationType(JsonNullable durationType) { + this.durationType = durationType; + } + + + + public WorkingTimeCreate changed(Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(Boolean changed) { + this.changed = changed; + } + + + public WorkingTimeCreate notes(@Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeCreate workingTimeTypeId(String workingTimeTypeId) { + + this.workingTimeTypeId = workingTimeTypeId; + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeTypeId(String workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + public WorkingTimeCreate status(WorkingTimeStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(WorkingTimeStatus status) { + this.status = status; + } + + + public WorkingTimeCreate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public WorkingTimeCreate userId(String userId) { + + this.userId = userId; + return this; + } + + /** + * Get userId + * @return userId + */ + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getUserId() { + return userId; + } + + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUserId(String userId) { + this.userId = userId; + } + + + public WorkingTimeCreate startLocation(@Nullable LocationCreate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationCreate> getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public WorkingTimeCreate endLocation(@Nullable LocationCreate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationCreate> getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeCreate workingTimeCreate = (WorkingTimeCreate) o; + return Objects.equals(this.start, workingTimeCreate.start) && + equalsNullable(this.end, workingTimeCreate.end) && + equalsNullable(this.breakTimes, workingTimeCreate.breakTimes) && + equalsNullable(this.durationType, workingTimeCreate.durationType) && + Objects.equals(this.changed, workingTimeCreate.changed) && + equalsNullable(this.notes, workingTimeCreate.notes) && + Objects.equals(this.workingTimeTypeId, workingTimeCreate.workingTimeTypeId) && + Objects.equals(this.status, workingTimeCreate.status) && + equalsNullable(this.metadata, workingTimeCreate.metadata) && + Objects.equals(this.userId, workingTimeCreate.userId) && + equalsNullable(this.startLocation, workingTimeCreate.startLocation) && + equalsNullable(this.endLocation, workingTimeCreate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(durationType), changed, hashCodeNullable(notes), workingTimeTypeId, status, hashCodeNullable(metadata), userId, hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeCreate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" durationType: ").append(toIndentedString(durationType)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpan.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpan.java new file mode 100644 index 0000000..454608e --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpan.java @@ -0,0 +1,493 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import com.timr.api.models.WorkingTimeTypePartial; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A span from `start` to `end` of a single `working_time_type`. Every working time derived for a covered day links back to it via `WorkingTime.working_time_date_span`. It can be created directly or become effective through an approved request. + */ +@JsonPropertyOrder({ + WorkingTimeDateSpan.JSON_PROPERTY_ID, + WorkingTimeDateSpan.JSON_PROPERTY_START, + WorkingTimeDateSpan.JSON_PROPERTY_START_HALF_DAY, + WorkingTimeDateSpan.JSON_PROPERTY_END, + WorkingTimeDateSpan.JSON_PROPERTY_END_HALF_DAY, + WorkingTimeDateSpan.JSON_PROPERTY_NOTES, + WorkingTimeDateSpan.JSON_PROPERTY_USER, + WorkingTimeDateSpan.JSON_PROPERTY_WORKING_TIME_TYPE, + WorkingTimeDateSpan.JSON_PROPERTY_SUBSTITUTE, + WorkingTimeDateSpan.JSON_PROPERTY_LAST_MODIFIED, + WorkingTimeDateSpan.JSON_PROPERTY_LAST_MODIFIED_BY, + WorkingTimeDateSpan.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpan { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_START = "start"; + + private LocalDate start; + + public static final String JSON_PROPERTY_START_HALF_DAY = "start_half_day"; + + private Boolean startHalfDay; + + public static final String JSON_PROPERTY_END = "end"; + + private LocalDate end; + + public static final String JSON_PROPERTY_END_HALF_DAY = "end_half_day"; + + private Boolean endHalfDay; + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private @Nullable String notes; + + public static final String JSON_PROPERTY_USER = "user"; + + private UserPartial user; + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE = "working_time_type"; + + private WorkingTimeTypePartial workingTimeType; + + public static final String JSON_PROPERTY_SUBSTITUTE = "substitute"; + + private JsonNullable<@Nullable UserPartial> substitute = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + + private @Nullable UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public WorkingTimeDateSpan() { + } + + public WorkingTimeDateSpan id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public WorkingTimeDateSpan start(LocalDate start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(LocalDate start) { + this.start = start; + } + + + public WorkingTimeDateSpan startHalfDay(Boolean startHalfDay) { + + this.startHalfDay = startHalfDay; + return this; + } + + /** + * Marks the first day of the working time date span as a half day. + * @return startHalfDay + */ + + @JsonProperty(value = JSON_PROPERTY_START_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getStartHalfDay() { + return startHalfDay; + } + + + @JsonProperty(value = JSON_PROPERTY_START_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartHalfDay(Boolean startHalfDay) { + this.startHalfDay = startHalfDay; + } + + + public WorkingTimeDateSpan end(LocalDate end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(LocalDate end) { + this.end = end; + } + + + public WorkingTimeDateSpan endHalfDay(Boolean endHalfDay) { + + this.endHalfDay = endHalfDay; + return this; + } + + /** + * Marks the last day of the working time date span as a half day. + * @return endHalfDay + */ + + @JsonProperty(value = JSON_PROPERTY_END_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getEndHalfDay() { + return endHalfDay; + } + + + @JsonProperty(value = JSON_PROPERTY_END_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndHalfDay(Boolean endHalfDay) { + this.endHalfDay = endHalfDay; + } + + + public WorkingTimeDateSpan notes(@Nullable String notes) { + + this.notes = notes; + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNotes() { + return notes; + } + + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNotes(@Nullable String notes) { + this.notes = notes; + } + + + public WorkingTimeDateSpan user(UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(UserPartial user) { + this.user = user; + } + + + public WorkingTimeDateSpan workingTimeType(WorkingTimeTypePartial workingTimeType) { + + this.workingTimeType = workingTimeType; + return this; + } + + /** + * Get workingTimeType + * @return workingTimeType + */ + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeTypePartial getWorkingTimeType() { + return workingTimeType; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeType(WorkingTimeTypePartial workingTimeType) { + this.workingTimeType = workingTimeType; + } + + + public WorkingTimeDateSpan substitute(@Nullable UserPartial substitute) { + this.substitute = JsonNullable.of(substitute); + + return this; + } + + /** + * Get substitute + * @return substitute + */ + + @JsonProperty(value = JSON_PROPERTY_SUBSTITUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable UserPartial> getSubstitute() { + return substitute; + } + + @JsonProperty(JSON_PROPERTY_SUBSTITUTE) + public void setSubstitute(JsonNullable substitute) { + this.substitute = substitute; + } + + + + public WorkingTimeDateSpan lastModified(OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public WorkingTimeDateSpan lastModifiedBy(@Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public WorkingTimeDateSpan metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeDateSpan putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpan workingTimeDateSpan = (WorkingTimeDateSpan) o; + return Objects.equals(this.id, workingTimeDateSpan.id) && + Objects.equals(this.start, workingTimeDateSpan.start) && + Objects.equals(this.startHalfDay, workingTimeDateSpan.startHalfDay) && + Objects.equals(this.end, workingTimeDateSpan.end) && + Objects.equals(this.endHalfDay, workingTimeDateSpan.endHalfDay) && + Objects.equals(this.notes, workingTimeDateSpan.notes) && + Objects.equals(this.user, workingTimeDateSpan.user) && + Objects.equals(this.workingTimeType, workingTimeDateSpan.workingTimeType) && + equalsNullable(this.substitute, workingTimeDateSpan.substitute) && + Objects.equals(this.lastModified, workingTimeDateSpan.lastModified) && + Objects.equals(this.lastModifiedBy, workingTimeDateSpan.lastModifiedBy) && + equalsNullable(this.metadata, workingTimeDateSpan.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, start, startHalfDay, end, endHalfDay, notes, user, workingTimeType, hashCodeNullable(substitute), lastModified, lastModifiedBy, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpan {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" workingTimeType: ").append(toIndentedString(workingTimeType)).append("\n"); + sb.append(" substitute: ").append(toIndentedString(substitute)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanCreate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanCreate.java new file mode 100644 index 0000000..e0d3546 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanCreate.java @@ -0,0 +1,387 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeDateSpanCreate + */ +@JsonPropertyOrder({ + WorkingTimeDateSpanCreate.JSON_PROPERTY_START, + WorkingTimeDateSpanCreate.JSON_PROPERTY_START_HALF_DAY, + WorkingTimeDateSpanCreate.JSON_PROPERTY_END, + WorkingTimeDateSpanCreate.JSON_PROPERTY_END_HALF_DAY, + WorkingTimeDateSpanCreate.JSON_PROPERTY_NOTES, + WorkingTimeDateSpanCreate.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeDateSpanCreate.JSON_PROPERTY_SUBSTITUTE_ID, + WorkingTimeDateSpanCreate.JSON_PROPERTY_METADATA, + WorkingTimeDateSpanCreate.JSON_PROPERTY_USER_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpanCreate { + public static final String JSON_PROPERTY_START = "start"; + + private LocalDate start; + + public static final String JSON_PROPERTY_START_HALF_DAY = "start_half_day"; + + private JsonNullable<@Nullable Boolean> startHalfDay = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private LocalDate end; + + public static final String JSON_PROPERTY_END_HALF_DAY = "end_half_day"; + + private JsonNullable<@Nullable Boolean> endHalfDay = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private JsonNullable<@Nullable String> notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + + private String workingTimeTypeId; + + public static final String JSON_PROPERTY_SUBSTITUTE_ID = "substitute_id"; + + private JsonNullable<@Nullable String> substituteId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_USER_ID = "user_id"; + + private String userId; + + public WorkingTimeDateSpanCreate() { + } + + public WorkingTimeDateSpanCreate start(LocalDate start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(LocalDate start) { + this.start = start; + } + + + public WorkingTimeDateSpanCreate startHalfDay(@Nullable Boolean startHalfDay) { + this.startHalfDay = JsonNullable.of(startHalfDay); + + return this; + } + + /** + * Get startHalfDay + * @return startHalfDay + */ + + @JsonProperty(value = JSON_PROPERTY_START_HALF_DAY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getStartHalfDay() { + return startHalfDay; + } + + @JsonProperty(JSON_PROPERTY_START_HALF_DAY) + public void setStartHalfDay(JsonNullable startHalfDay) { + this.startHalfDay = startHalfDay; + } + + + + public WorkingTimeDateSpanCreate end(LocalDate end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(LocalDate end) { + this.end = end; + } + + + public WorkingTimeDateSpanCreate endHalfDay(@Nullable Boolean endHalfDay) { + this.endHalfDay = JsonNullable.of(endHalfDay); + + return this; + } + + /** + * Get endHalfDay + * @return endHalfDay + */ + + @JsonProperty(value = JSON_PROPERTY_END_HALF_DAY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getEndHalfDay() { + return endHalfDay; + } + + @JsonProperty(JSON_PROPERTY_END_HALF_DAY) + public void setEndHalfDay(JsonNullable endHalfDay) { + this.endHalfDay = endHalfDay; + } + + + + public WorkingTimeDateSpanCreate notes(@Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeDateSpanCreate workingTimeTypeId(String workingTimeTypeId) { + + this.workingTimeTypeId = workingTimeTypeId; + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeTypeId(String workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + public WorkingTimeDateSpanCreate substituteId(@Nullable String substituteId) { + this.substituteId = JsonNullable.of(substituteId); + + return this; + } + + /** + * Get substituteId + * @return substituteId + */ + + @JsonProperty(value = JSON_PROPERTY_SUBSTITUTE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getSubstituteId() { + return substituteId; + } + + @JsonProperty(JSON_PROPERTY_SUBSTITUTE_ID) + public void setSubstituteId(JsonNullable substituteId) { + this.substituteId = substituteId; + } + + + + public WorkingTimeDateSpanCreate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeDateSpanCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public WorkingTimeDateSpanCreate userId(String userId) { + + this.userId = userId; + return this; + } + + /** + * Get userId + * @return userId + */ + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getUserId() { + return userId; + } + + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUserId(String userId) { + this.userId = userId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpanCreate workingTimeDateSpanCreate = (WorkingTimeDateSpanCreate) o; + return Objects.equals(this.start, workingTimeDateSpanCreate.start) && + equalsNullable(this.startHalfDay, workingTimeDateSpanCreate.startHalfDay) && + Objects.equals(this.end, workingTimeDateSpanCreate.end) && + equalsNullable(this.endHalfDay, workingTimeDateSpanCreate.endHalfDay) && + equalsNullable(this.notes, workingTimeDateSpanCreate.notes) && + Objects.equals(this.workingTimeTypeId, workingTimeDateSpanCreate.workingTimeTypeId) && + equalsNullable(this.substituteId, workingTimeDateSpanCreate.substituteId) && + equalsNullable(this.metadata, workingTimeDateSpanCreate.metadata) && + Objects.equals(this.userId, workingTimeDateSpanCreate.userId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, hashCodeNullable(startHalfDay), end, hashCodeNullable(endHalfDay), hashCodeNullable(notes), workingTimeTypeId, hashCodeNullable(substituteId), hashCodeNullable(metadata), userId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpanCreate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" substituteId: ").append(toIndentedString(substituteId)).append("\n"); + sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanPage.java new file mode 100644 index 0000000..96171c6 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkingTimeDateSpan; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeDateSpanPage + */ +@JsonPropertyOrder({ + WorkingTimeDateSpanPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + WorkingTimeDateSpanPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpanPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public WorkingTimeDateSpanPage() { + } + + public WorkingTimeDateSpanPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public WorkingTimeDateSpanPage data(List data) { + + this.data = data; + return this; + } + + public WorkingTimeDateSpanPage addDataItem(WorkingTimeDateSpan dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpanPage workingTimeDateSpanPage = (WorkingTimeDateSpanPage) o; + return Objects.equals(this.nextPageToken, workingTimeDateSpanPage.nextPageToken) && + Objects.equals(this.data, workingTimeDateSpanPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpanPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanPartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanPartial.java new file mode 100644 index 0000000..c452edf --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanPartial.java @@ -0,0 +1,118 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * References the date span this working time belongs to, if any. All working times generated for a date span reference the same span; working times recorded on their own have none. + */ +@JsonPropertyOrder({ + WorkingTimeDateSpanPartial.JSON_PROPERTY_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpanPartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public WorkingTimeDateSpanPartial() { + } + + public WorkingTimeDateSpanPartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpanPartial workingTimeDateSpanPartial = (WorkingTimeDateSpanPartial) o; + return Objects.equals(this.id, workingTimeDateSpanPartial.id); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpanPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanUpdate.java new file mode 100644 index 0000000..3243469 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpanUpdate.java @@ -0,0 +1,348 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeDateSpanUpdate + */ +@JsonPropertyOrder({ + WorkingTimeDateSpanUpdate.JSON_PROPERTY_START, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_START_HALF_DAY, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_END, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_END_HALF_DAY, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_NOTES, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_SUBSTITUTE_ID, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpanUpdate { + public static final String JSON_PROPERTY_START = "start"; + + private JsonNullable<@Nullable LocalDate> start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_HALF_DAY = "start_half_day"; + + private JsonNullable<@Nullable Boolean> startHalfDay = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable LocalDate> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_HALF_DAY = "end_half_day"; + + private JsonNullable<@Nullable Boolean> endHalfDay = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private JsonNullable<@Nullable String> notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + + private JsonNullable<@Nullable String> workingTimeTypeId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_SUBSTITUTE_ID = "substitute_id"; + + private JsonNullable<@Nullable String> substituteId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public WorkingTimeDateSpanUpdate() { + } + + public WorkingTimeDateSpanUpdate start(@Nullable LocalDate start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public WorkingTimeDateSpanUpdate startHalfDay(@Nullable Boolean startHalfDay) { + this.startHalfDay = JsonNullable.of(startHalfDay); + + return this; + } + + /** + * Get startHalfDay + * @return startHalfDay + */ + + @JsonProperty(value = JSON_PROPERTY_START_HALF_DAY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getStartHalfDay() { + return startHalfDay; + } + + @JsonProperty(JSON_PROPERTY_START_HALF_DAY) + public void setStartHalfDay(JsonNullable startHalfDay) { + this.startHalfDay = startHalfDay; + } + + + + public WorkingTimeDateSpanUpdate end(@Nullable LocalDate end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocalDate> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public WorkingTimeDateSpanUpdate endHalfDay(@Nullable Boolean endHalfDay) { + this.endHalfDay = JsonNullable.of(endHalfDay); + + return this; + } + + /** + * Get endHalfDay + * @return endHalfDay + */ + + @JsonProperty(value = JSON_PROPERTY_END_HALF_DAY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getEndHalfDay() { + return endHalfDay; + } + + @JsonProperty(JSON_PROPERTY_END_HALF_DAY) + public void setEndHalfDay(JsonNullable endHalfDay) { + this.endHalfDay = endHalfDay; + } + + + + public WorkingTimeDateSpanUpdate notes(@Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeDateSpanUpdate workingTimeTypeId(@Nullable String workingTimeTypeId) { + this.workingTimeTypeId = JsonNullable.of(workingTimeTypeId); + + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + @JsonProperty(JSON_PROPERTY_WORKING_TIME_TYPE_ID) + public void setWorkingTimeTypeId(JsonNullable workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + + public WorkingTimeDateSpanUpdate substituteId(@Nullable String substituteId) { + this.substituteId = JsonNullable.of(substituteId); + + return this; + } + + /** + * Get substituteId + * @return substituteId + */ + + @JsonProperty(value = JSON_PROPERTY_SUBSTITUTE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getSubstituteId() { + return substituteId; + } + + @JsonProperty(JSON_PROPERTY_SUBSTITUTE_ID) + public void setSubstituteId(JsonNullable substituteId) { + this.substituteId = substituteId; + } + + + + public WorkingTimeDateSpanUpdate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeDateSpanUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate = (WorkingTimeDateSpanUpdate) o; + return equalsNullable(this.start, workingTimeDateSpanUpdate.start) && + equalsNullable(this.startHalfDay, workingTimeDateSpanUpdate.startHalfDay) && + equalsNullable(this.end, workingTimeDateSpanUpdate.end) && + equalsNullable(this.endHalfDay, workingTimeDateSpanUpdate.endHalfDay) && + equalsNullable(this.notes, workingTimeDateSpanUpdate.notes) && + equalsNullable(this.workingTimeTypeId, workingTimeDateSpanUpdate.workingTimeTypeId) && + equalsNullable(this.substituteId, workingTimeDateSpanUpdate.substituteId) && + equalsNullable(this.metadata, workingTimeDateSpanUpdate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(startHalfDay), hashCodeNullable(end), hashCodeNullable(endHalfDay), hashCodeNullable(notes), hashCodeNullable(workingTimeTypeId), hashCodeNullable(substituteId), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpanUpdate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" substituteId: ").append(toIndentedString(substituteId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpansSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpansSortColumn.java new file mode 100644 index 0000000..05c17a8 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeDateSpansSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Working Time Date Spans. + */ +public enum WorkingTimeDateSpansSortColumn { + + START("start"); + + private String value; + + WorkingTimeDateSpansSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeDateSpansSortColumn fromValue(String value) { + for (WorkingTimeDateSpansSortColumn b : WorkingTimeDateSpansSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeRules.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeRules.java new file mode 100644 index 0000000..6b9dd7f --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeRules.java @@ -0,0 +1,150 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeRules + */ +@JsonPropertyOrder({ + WorkingTimeRules.JSON_PROPERTY_ID, + WorkingTimeRules.JSON_PROPERTY_NAME +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeRules { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public WorkingTimeRules() { + } + + public WorkingTimeRules id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public WorkingTimeRules name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeRules workingTimeRules = (WorkingTimeRules) o; + return Objects.equals(this.id, workingTimeRules.id) && + Objects.equals(this.name, workingTimeRules.name); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeRules {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeStatus.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeStatus.java new file mode 100644 index 0000000..535c782 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeStatus.java @@ -0,0 +1,71 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Processing state of a Working Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, closed and archived. + */ +public enum WorkingTimeStatus { + + RUNNING("running"), + + PAUSED("paused"), + + CHANGEABLE("changeable"), + + LOCKED("locked"), + + APPROVED("approved"), + + CLOSED("closed"), + + ARCHIVED("archived"); + + private String value; + + WorkingTimeStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeStatus fromValue(String value) { + for (WorkingTimeStatus b : WorkingTimeStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeType.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeType.java new file mode 100644 index 0000000..f0e02e7 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeType.java @@ -0,0 +1,446 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DurationUnit; +import com.timr.api.models.RecordingModeUser; +import com.timr.api.models.WorkingTimeTypeCategory; +import com.timr.api.models.WorkingTimeTypeSubCategory; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A working time type. `category` and `sub_category` place it in the classification, `edit_unit` decides whether it is recorded by time or by day, and `requires_substitute` governs how it is recorded. + */ +@JsonPropertyOrder({ + WorkingTimeType.JSON_PROPERTY_ID, + WorkingTimeType.JSON_PROPERTY_NAME, + WorkingTimeType.JSON_PROPERTY_SHORT_NAME, + WorkingTimeType.JSON_PROPERTY_DESCRIPTION, + WorkingTimeType.JSON_PROPERTY_EXTERNAL_ID, + WorkingTimeType.JSON_PROPERTY_EDIT_UNIT, + WorkingTimeType.JSON_PROPERTY_CATEGORY, + WorkingTimeType.JSON_PROPERTY_SUB_CATEGORY, + WorkingTimeType.JSON_PROPERTY_RECORDING_MODE_USER, + WorkingTimeType.JSON_PROPERTY_ARCHIVED, + WorkingTimeType.JSON_PROPERTY_REQUIRES_SUBSTITUTE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeType { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_SHORT_NAME = "short_name"; + + private @Nullable String shortName; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + + private @Nullable String description; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public static final String JSON_PROPERTY_EDIT_UNIT = "edit_unit"; + + private DurationUnit editUnit; + + public static final String JSON_PROPERTY_CATEGORY = "category"; + + private WorkingTimeTypeCategory category; + + public static final String JSON_PROPERTY_SUB_CATEGORY = "sub_category"; + + private @Nullable WorkingTimeTypeSubCategory subCategory; + + public static final String JSON_PROPERTY_RECORDING_MODE_USER = "recording_mode_user"; + + private RecordingModeUser recordingModeUser; + + public static final String JSON_PROPERTY_ARCHIVED = "archived"; + + private Boolean archived; + + public static final String JSON_PROPERTY_REQUIRES_SUBSTITUTE = "requires_substitute"; + + private JsonNullable<@Nullable Boolean> requiresSubstitute = JsonNullable.undefined(); + + public WorkingTimeType() { + } + + public WorkingTimeType id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public WorkingTimeType name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public WorkingTimeType shortName(@Nullable String shortName) { + + this.shortName = shortName; + return this; + } + + /** + * Get shortName + * @return shortName + */ + + @JsonProperty(value = JSON_PROPERTY_SHORT_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getShortName() { + return shortName; + } + + + @JsonProperty(value = JSON_PROPERTY_SHORT_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setShortName(@Nullable String shortName) { + this.shortName = shortName; + } + + + public WorkingTimeType description(@Nullable String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@Nullable String description) { + this.description = description; + } + + + public WorkingTimeType externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + public WorkingTimeType editUnit(DurationUnit editUnit) { + + this.editUnit = editUnit; + return this; + } + + /** + * Get editUnit + * @return editUnit + */ + + @JsonProperty(value = JSON_PROPERTY_EDIT_UNIT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DurationUnit getEditUnit() { + return editUnit; + } + + + @JsonProperty(value = JSON_PROPERTY_EDIT_UNIT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEditUnit(DurationUnit editUnit) { + this.editUnit = editUnit; + } + + + public WorkingTimeType category(WorkingTimeTypeCategory category) { + + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + + @JsonProperty(value = JSON_PROPERTY_CATEGORY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeTypeCategory getCategory() { + return category; + } + + + @JsonProperty(value = JSON_PROPERTY_CATEGORY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCategory(WorkingTimeTypeCategory category) { + this.category = category; + } + + + public WorkingTimeType subCategory(@Nullable WorkingTimeTypeSubCategory subCategory) { + + this.subCategory = subCategory; + return this; + } + + /** + * Get subCategory + * @return subCategory + */ + + @JsonProperty(value = JSON_PROPERTY_SUB_CATEGORY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable WorkingTimeTypeSubCategory getSubCategory() { + return subCategory; + } + + + @JsonProperty(value = JSON_PROPERTY_SUB_CATEGORY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSubCategory(@Nullable WorkingTimeTypeSubCategory subCategory) { + this.subCategory = subCategory; + } + + + public WorkingTimeType recordingModeUser(RecordingModeUser recordingModeUser) { + + this.recordingModeUser = recordingModeUser; + return this; + } + + /** + * Specifies how the user can record this working time type. + * @return recordingModeUser + */ + + @JsonProperty(value = JSON_PROPERTY_RECORDING_MODE_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public RecordingModeUser getRecordingModeUser() { + return recordingModeUser; + } + + + @JsonProperty(value = JSON_PROPERTY_RECORDING_MODE_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRecordingModeUser(RecordingModeUser recordingModeUser) { + this.recordingModeUser = recordingModeUser; + } + + + public WorkingTimeType archived(Boolean archived) { + + this.archived = archived; + return this; + } + + /** + * Get archived + * @return archived + */ + + @JsonProperty(value = JSON_PROPERTY_ARCHIVED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getArchived() { + return archived; + } + + + @JsonProperty(value = JSON_PROPERTY_ARCHIVED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setArchived(Boolean archived) { + this.archived = archived; + } + + + public WorkingTimeType requiresSubstitute(@Nullable Boolean requiresSubstitute) { + this.requiresSubstitute = JsonNullable.of(requiresSubstitute); + + return this; + } + + /** + * Get requiresSubstitute + * @return requiresSubstitute + */ + + @JsonProperty(value = JSON_PROPERTY_REQUIRES_SUBSTITUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getRequiresSubstitute() { + return requiresSubstitute; + } + + @JsonProperty(JSON_PROPERTY_REQUIRES_SUBSTITUTE) + public void setRequiresSubstitute(JsonNullable requiresSubstitute) { + this.requiresSubstitute = requiresSubstitute; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeType workingTimeType = (WorkingTimeType) o; + return Objects.equals(this.id, workingTimeType.id) && + Objects.equals(this.name, workingTimeType.name) && + Objects.equals(this.shortName, workingTimeType.shortName) && + Objects.equals(this.description, workingTimeType.description) && + Objects.equals(this.externalId, workingTimeType.externalId) && + Objects.equals(this.editUnit, workingTimeType.editUnit) && + Objects.equals(this.category, workingTimeType.category) && + Objects.equals(this.subCategory, workingTimeType.subCategory) && + Objects.equals(this.recordingModeUser, workingTimeType.recordingModeUser) && + Objects.equals(this.archived, workingTimeType.archived) && + equalsNullable(this.requiresSubstitute, workingTimeType.requiresSubstitute); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, shortName, description, externalId, editUnit, category, subCategory, recordingModeUser, archived, hashCodeNullable(requiresSubstitute)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeType {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" editUnit: ").append(toIndentedString(editUnit)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" subCategory: ").append(toIndentedString(subCategory)).append("\n"); + sb.append(" recordingModeUser: ").append(toIndentedString(recordingModeUser)).append("\n"); + sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); + sb.append(" requiresSubstitute: ").append(toIndentedString(requiresSubstitute)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypeCategory.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypeCategory.java new file mode 100644 index 0000000..9d670c8 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypeCategory.java @@ -0,0 +1,69 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Category of a Working Time Type. `attendance_time` counts as time at work, the remaining categories describe kinds of absence. + */ +public enum WorkingTimeTypeCategory { + + ATTENDANCE_TIME("attendance_time"), + + VACATION("vacation"), + + PAID_TIME_OFF("paid_time_off"), + + UNPAID_TIME_OFF("unpaid_time_off"), + + SUSPENSION("suspension"), + + BREAK_TIME("break_time"); + + private String value; + + WorkingTimeTypeCategory(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeTypeCategory fromValue(String value) { + for (WorkingTimeTypeCategory b : WorkingTimeTypeCategory.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypePartial.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypePartial.java new file mode 100644 index 0000000..e619bf2 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypePartial.java @@ -0,0 +1,182 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeTypePartial + */ +@JsonPropertyOrder({ + WorkingTimeTypePartial.JSON_PROPERTY_ID, + WorkingTimeTypePartial.JSON_PROPERTY_NAME, + WorkingTimeTypePartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeTypePartial { + public static final String JSON_PROPERTY_ID = "id"; + + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + + private String name; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + + private @Nullable String externalId; + + public WorkingTimeTypePartial() { + } + + public WorkingTimeTypePartial id(String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(String id) { + this.id = id; + } + + + public WorkingTimeTypePartial name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public WorkingTimeTypePartial externalId(@Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeTypePartial workingTimeTypePartial = (WorkingTimeTypePartial) o; + return Objects.equals(this.id, workingTimeTypePartial.id) && + Objects.equals(this.name, workingTimeTypePartial.name) && + Objects.equals(this.externalId, workingTimeTypePartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeTypePartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypeSubCategory.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypeSubCategory.java new file mode 100644 index 0000000..99a7065 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypeSubCategory.java @@ -0,0 +1,67 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Further classification of a Working Time Type within its category. + */ +public enum WorkingTimeTypeSubCategory { + + PRESENT("present"), + + WORK_FROM_HOME("work_from_home"), + + AWAY("away"), + + ACTIVE_DRIVING_TIME("active_driving_time"), + + PASSIVE_TRAVELLING_TIME("passive_travelling_time"); + + private String value; + + WorkingTimeTypeSubCategory(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeTypeSubCategory fromValue(String value) { + for (WorkingTimeTypeSubCategory b : WorkingTimeTypeSubCategory.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypesPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypesPage.java new file mode 100644 index 0000000..3bff372 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypesPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkingTimeType; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeTypesPage + */ +@JsonPropertyOrder({ + WorkingTimeTypesPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + WorkingTimeTypesPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeTypesPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public WorkingTimeTypesPage() { + } + + public WorkingTimeTypesPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public WorkingTimeTypesPage data(List data) { + + this.data = data; + return this; + } + + public WorkingTimeTypesPage addDataItem(WorkingTimeType dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeTypesPage workingTimeTypesPage = (WorkingTimeTypesPage) o; + return Objects.equals(this.nextPageToken, workingTimeTypesPage.nextPageToken) && + Objects.equals(this.data, workingTimeTypesPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeTypesPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypesSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypesSortColumn.java new file mode 100644 index 0000000..4656007 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeTypesSortColumn.java @@ -0,0 +1,59 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Working Time Types. + */ +public enum WorkingTimeTypesSortColumn { + + NAME("name"); + + private String value; + + WorkingTimeTypesSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeTypesSortColumn fromValue(String value) { + for (WorkingTimeTypesSortColumn b : WorkingTimeTypesSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeUpdate.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeUpdate.java new file mode 100644 index 0000000..f007bc1 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeUpdate.java @@ -0,0 +1,458 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.DurationType; +import com.timr.api.models.LocationUpdate; +import com.timr.api.models.WorkingTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeUpdate + */ +@JsonPropertyOrder({ + WorkingTimeUpdate.JSON_PROPERTY_START, + WorkingTimeUpdate.JSON_PROPERTY_END, + WorkingTimeUpdate.JSON_PROPERTY_BREAK_TIMES, + WorkingTimeUpdate.JSON_PROPERTY_DURATION_TYPE, + WorkingTimeUpdate.JSON_PROPERTY_CHANGED, + WorkingTimeUpdate.JSON_PROPERTY_NOTES, + WorkingTimeUpdate.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeUpdate.JSON_PROPERTY_STATUS, + WorkingTimeUpdate.JSON_PROPERTY_METADATA, + WorkingTimeUpdate.JSON_PROPERTY_START_LOCATION, + WorkingTimeUpdate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeUpdate { + public static final String JSON_PROPERTY_START = "start"; + + private JsonNullable<@Nullable OffsetDateTime> start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + + private JsonNullable<@Nullable List> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_DURATION_TYPE = "duration_type"; + + private JsonNullable<@Nullable DurationType> durationType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private JsonNullable<@Nullable Boolean> changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private JsonNullable<@Nullable String> notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + + private JsonNullable<@Nullable String> workingTimeTypeId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + + private JsonNullable<@Nullable WorkingTimeStatus> status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + + private JsonNullable<@Nullable LocationUpdate> startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + + private JsonNullable<@Nullable LocationUpdate> endLocation = JsonNullable.undefined(); + + public WorkingTimeUpdate() { + } + + public WorkingTimeUpdate start(@Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public WorkingTimeUpdate end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public WorkingTimeUpdate breakTimes(@Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public WorkingTimeUpdate addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable List> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public WorkingTimeUpdate durationType(@Nullable DurationType durationType) { + this.durationType = JsonNullable.of(durationType); + + return this; + } + + /** + * Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @return durationType + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable DurationType> getDurationType() { + return durationType; + } + + @JsonProperty(JSON_PROPERTY_DURATION_TYPE) + public void setDurationType(JsonNullable durationType) { + this.durationType = durationType; + } + + + + public WorkingTimeUpdate changed(@Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public WorkingTimeUpdate notes(@Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeUpdate workingTimeTypeId(@Nullable String workingTimeTypeId) { + this.workingTimeTypeId = JsonNullable.of(workingTimeTypeId); + + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + @JsonProperty(JSON_PROPERTY_WORKING_TIME_TYPE_ID) + public void setWorkingTimeTypeId(JsonNullable workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + + public WorkingTimeUpdate status(@Nullable WorkingTimeStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable WorkingTimeStatus> getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public WorkingTimeUpdate metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public WorkingTimeUpdate startLocation(@Nullable LocationUpdate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationUpdate> getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public WorkingTimeUpdate endLocation(@Nullable LocationUpdate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable LocationUpdate> getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeUpdate workingTimeUpdate = (WorkingTimeUpdate) o; + return equalsNullable(this.start, workingTimeUpdate.start) && + equalsNullable(this.end, workingTimeUpdate.end) && + equalsNullable(this.breakTimes, workingTimeUpdate.breakTimes) && + equalsNullable(this.durationType, workingTimeUpdate.durationType) && + equalsNullable(this.changed, workingTimeUpdate.changed) && + equalsNullable(this.notes, workingTimeUpdate.notes) && + equalsNullable(this.workingTimeTypeId, workingTimeUpdate.workingTimeTypeId) && + equalsNullable(this.status, workingTimeUpdate.status) && + equalsNullable(this.metadata, workingTimeUpdate.metadata) && + equalsNullable(this.startLocation, workingTimeUpdate.startLocation) && + equalsNullable(this.endLocation, workingTimeUpdate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(durationType), hashCodeNullable(changed), hashCodeNullable(notes), hashCodeNullable(workingTimeTypeId), hashCodeNullable(status), hashCodeNullable(metadata), hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeUpdate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" durationType: ").append(toIndentedString(durationType)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeUpsert.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeUpsert.java new file mode 100644 index 0000000..5d0352b --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimeUpsert.java @@ -0,0 +1,397 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.DurationType; +import com.timr.api.models.WorkingTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeUpsert + */ +@JsonPropertyOrder({ + WorkingTimeUpsert.JSON_PROPERTY_START, + WorkingTimeUpsert.JSON_PROPERTY_END, + WorkingTimeUpsert.JSON_PROPERTY_BREAK_TIMES, + WorkingTimeUpsert.JSON_PROPERTY_DURATION_TYPE, + WorkingTimeUpsert.JSON_PROPERTY_CHANGED, + WorkingTimeUpsert.JSON_PROPERTY_NOTES, + WorkingTimeUpsert.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeUpsert.JSON_PROPERTY_STATUS, + WorkingTimeUpsert.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeUpsert { + public static final String JSON_PROPERTY_START = "start"; + + private JsonNullable<@Nullable OffsetDateTime> start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + + private JsonNullable<@Nullable OffsetDateTime> end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + + private JsonNullable<@Nullable List> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_DURATION_TYPE = "duration_type"; + + private JsonNullable<@Nullable DurationType> durationType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + + private JsonNullable<@Nullable Boolean> changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + + private JsonNullable<@Nullable String> notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + + private JsonNullable<@Nullable String> workingTimeTypeId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + + private JsonNullable<@Nullable WorkingTimeStatus> status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + + private JsonNullable<@Nullable Map> metadata = JsonNullable.>undefined(); + + public WorkingTimeUpsert() { + } + + public WorkingTimeUpsert start(@Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * @return start + */ + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public WorkingTimeUpsert end(@Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * @return end + */ + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable OffsetDateTime> getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public WorkingTimeUpsert breakTimes(@Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public WorkingTimeUpsert addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable List> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public WorkingTimeUpsert durationType(@Nullable DurationType durationType) { + this.durationType = JsonNullable.of(durationType); + + return this; + } + + /** + * Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @return durationType + */ + + @JsonProperty(value = JSON_PROPERTY_DURATION_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable DurationType> getDurationType() { + return durationType; + } + + @JsonProperty(JSON_PROPERTY_DURATION_TYPE) + public void setDurationType(JsonNullable durationType) { + this.durationType = durationType; + } + + + + public WorkingTimeUpsert changed(@Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Boolean> getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public WorkingTimeUpsert notes(@Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeUpsert workingTimeTypeId(@Nullable String workingTimeTypeId) { + this.workingTimeTypeId = JsonNullable.of(workingTimeTypeId); + + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable String> getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + @JsonProperty(JSON_PROPERTY_WORKING_TIME_TYPE_ID) + public void setWorkingTimeTypeId(JsonNullable workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + + public WorkingTimeUpsert status(@Nullable WorkingTimeStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable WorkingTimeStatus> getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public WorkingTimeUpsert metadata(@Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeUpsert putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable<@Nullable Map> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeUpsert workingTimeUpsert = (WorkingTimeUpsert) o; + return equalsNullable(this.start, workingTimeUpsert.start) && + equalsNullable(this.end, workingTimeUpsert.end) && + equalsNullable(this.breakTimes, workingTimeUpsert.breakTimes) && + equalsNullable(this.durationType, workingTimeUpsert.durationType) && + equalsNullable(this.changed, workingTimeUpsert.changed) && + equalsNullable(this.notes, workingTimeUpsert.notes) && + equalsNullable(this.workingTimeTypeId, workingTimeUpsert.workingTimeTypeId) && + equalsNullable(this.status, workingTimeUpsert.status) && + equalsNullable(this.metadata, workingTimeUpsert.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(durationType), hashCodeNullable(changed), hashCodeNullable(notes), hashCodeNullable(workingTimeTypeId), hashCodeNullable(status), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeUpsert {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" durationType: ").append(toIndentedString(durationType)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimesPage.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimesPage.java new file mode 100644 index 0000000..ff57919 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimesPage.java @@ -0,0 +1,162 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkingTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimesPage + */ +@JsonPropertyOrder({ + WorkingTimesPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + WorkingTimesPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimesPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + + private @Nullable String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + + private List data; + + public WorkingTimesPage() { + } + + public WorkingTimesPage nextPageToken(@Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public @Nullable String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public WorkingTimesPage data(List data) { + + this.data = data; + return this; + } + + public WorkingTimesPage addDataItem(WorkingTime dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimesPage workingTimesPage = (WorkingTimesPage) o; + return Objects.equals(this.nextPageToken, workingTimesPage.nextPageToken) && + Objects.equals(this.data, workingTimesPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimesPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimesSortColumn.java b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimesSortColumn.java new file mode 100644 index 0000000..87a3287 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/WorkingTimesSortColumn.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import org.jspecify.annotations.Nullable; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Working Times. + */ +public enum WorkingTimesSortColumn { + + START("start"), + + LAST_MODIFIED("last_modified"); + + private String value; + + WorkingTimesSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimesSortColumn fromValue(String value) { + for (WorkingTimesSortColumn b : WorkingTimesSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-restclient/src/main/java/com/timr/api/models/package-info.java b/sdk/java-restclient/src/main/java/com/timr/api/models/package-info.java new file mode 100644 index 0000000..864b6aa --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/models/package-info.java @@ -0,0 +1,2 @@ +@org.jspecify.annotations.NullMarked +package com.timr.api.models; diff --git a/sdk/java-restclient/src/main/java/com/timr/api/package-info.java b/sdk/java-restclient/src/main/java/com/timr/api/package-info.java new file mode 100644 index 0000000..9e64254 --- /dev/null +++ b/sdk/java-restclient/src/main/java/com/timr/api/package-info.java @@ -0,0 +1,2 @@ +@org.jspecify.annotations.NullMarked +package com.timr.api; diff --git a/sdk/java-restclient/src/test/java/com/timr/api/ApiClientJackson3Test.java b/sdk/java-restclient/src/test/java/com/timr/api/ApiClientJackson3Test.java new file mode 100644 index 0000000..664b859 --- /dev/null +++ b/sdk/java-restclient/src/test/java/com/timr/api/ApiClientJackson3Test.java @@ -0,0 +1,106 @@ +package com.timr.api; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.junit.jupiter.api.Test; +import org.openapitools.jackson.nullable.JsonNullable; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.web.client.RestClient; + +import java.time.OffsetDateTime; +import java.text.DateFormat; +import java.lang.reflect.Modifier; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +class ApiClientJackson3Test { + + private final tools.jackson.databind.json.JsonMapper mapper = + ApiClient.createDefaultMapper(ApiClient.createDefaultDateFormat()); + + @Test + void doesNotExposeMapperOrRestClient() throws Exception { + var mapperFactory = ApiClient.class.getDeclaredMethod("createDefaultMapper", DateFormat.class); + + assertFalse(Modifier.isPublic(mapperFactory.getModifiers())); + assertThrows(NoSuchMethodException.class, () -> ApiClient.class.getMethod("getRestClient")); + } + + @Test + void preservesJsonNullableUndefinedNullAndValueStates() throws Exception { + var undefined = mapper.readValue("{}", NullablePayload.class); + var explicitNull = mapper.readValue("{\"value\":null}", NullablePayload.class); + var present = mapper.readValue("{\"value\":\"timr\"}", NullablePayload.class); + + assertFalse(undefined.value.isPresent()); + assertTrue(explicitNull.value.isPresent()); + assertNull(explicitNull.value.get()); + assertEquals("timr", present.value.get()); + + assertEquals("{}", mapper.writeValueAsString(undefined)); + assertEquals("{\"value\":null}", mapper.writeValueAsString(explicitNull)); + assertEquals("{\"value\":\"timr\"}", mapper.writeValueAsString(present)); + } + + @Test + void preservesRfc3339OffsetWhenReadingAndWriting() throws Exception { + var input = "2023-10-10T12:00:00.123+02:00"; + + var payload = mapper.readValue("{\"value\":\"" + input + "\"}", DateTimePayload.class); + + assertEquals(OffsetDateTime.parse(input), payload.value); + assertEquals("{\"value\":\"" + input + "\"}", mapper.writeValueAsString(payload)); + } + + @Test + void usesTheConfiguredRestClientBuilderAndJackson3Converter() { + var builder = RestClient.builder(); + var server = MockRestServiceServer.bindTo(builder).build(); + var client = new ApiClient(builder); + client.setBasePath("https://example.test"); + var input = "2023-10-10T12:00:00.123+02:00"; + + server.expect(requestTo("https://example.test/value")) + .andRespond(withSuccess("{\"value\":\"" + input + "\"}", MediaType.APPLICATION_JSON)); + + var response = client.invokeAPI( + "/value", + HttpMethod.GET, + Map.of(), + new LinkedMultiValueMap<>(), + null, + new HttpHeaders(), + new LinkedMultiValueMap<>(), + new LinkedMultiValueMap<>(), + List.of(MediaType.APPLICATION_JSON), + null, + new String[0], + new ParameterizedTypeReference() {}); + var payload = response.body(DateTimePayload.class); + + assertEquals(OffsetDateTime.parse(input), payload.value); + server.verify(); + } + + static final class NullablePayload { + @JsonProperty("value") + public JsonNullable value = JsonNullable.undefined(); + } + + static final class DateTimePayload { + @JsonProperty("value") + public OffsetDateTime value; + } +} diff --git a/sdk/java-restclient/src/test/java/com/timr/api/apis/UserApiTest.java b/sdk/java-restclient/src/test/java/com/timr/api/apis/UserApiTest.java new file mode 100644 index 0000000..9da7b6e --- /dev/null +++ b/sdk/java-restclient/src/test/java/com/timr/api/apis/UserApiTest.java @@ -0,0 +1,280 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.models.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestTemplate; + +import java.time.LocalDate; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +class UserApiTest { + + private static final String BASE_PATH = "http://localhost:8081/"; + + private MockRestServiceServer server; + private UserApi userApi; + + @BeforeEach + void setUp() { + RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory()); + server = MockRestServiceServer.bindTo(restTemplate).build(); + + RestClient.Builder restClientBuilder = RestClient.builder(restTemplate); + ApiClient apiClient = new ApiClient(restClientBuilder); + apiClient.setBasePath(BASE_PATH); + apiClient.getAuthentication().setAccessToken("dummyToken"); + + userApi = new UserApi(apiClient); + } + + @Test + void getUser() { + String id = "user123"; + String jsonResponse = """ + { + "id": "user123", + "firstname": "John", + "lastname": "Doe", + "fullname": "John Doe", + "email": "john.doe@example.com", + "employee_number": "E123", + "external_id": "EXT123", + "login": "johndoe", + "entry_date": "2023-01-01", + "resign_date": null, + "work_schedule_model": { + "id": "schedule123", + "name": "Standard Schedule" + }, + "holiday_calendar": { + "id": "calendar123", + "description": "Standard Holidays" + } + } + """; + + server.expect(requestTo(BASE_PATH + "users/" + id)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + User user = userApi.getUser(id); + + server.verify(); + + assertNotNull(user); + assertEquals("user123", user.getId()); + assertEquals("John", user.getFirstname()); + assertEquals("Doe", user.getLastname()); + assertEquals("John Doe", user.getFullname()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals("E123", user.getEmployeeNumber()); + assertEquals("EXT123", user.getExternalId()); + assertEquals("johndoe", user.getLogin().orElse(null)); + assertEquals(LocalDate.parse("2023-01-01"), user.getEntryDate().orElse(null)); + assertNull(user.getResignDate().orElse(null)); + + assertNotNull(user.getWorkScheduleModel().orElse(null)); + assertEquals("schedule123", user.getWorkScheduleModel().orElse(null).getId()); + assertEquals("Standard Schedule", user.getWorkScheduleModel().orElse(null).getName()); + + assertNotNull(user.getHolidayCalendar().orElse(null)); + assertEquals("calendar123", user.getHolidayCalendar().orElse(null).getId()); + assertEquals("Standard Holidays", user.getHolidayCalendar().orElse(null).getDescription()); + } + + @Test + void fetchUsers() { + String jsonResponse = """ + { + "next_page_token": "token123", + "data": [ + { + "id": "user123", + "firstname": "John", + "lastname": "Doe", + "fullname": "John Doe", + "email": "john.doe@example.com", + "employee_number": "E123", + "external_id": "EXT123", + "login": "johndoe", + "entry_date": "2023-01-01", + "resign_date": null, + "work_schedule_model": { + "id": "schedule123", + "name": "Standard Schedule" + }, + "holiday_calendar": { + "id": "calendar123", + "description": "Standard Holidays" + } + } + ] + } + """; + + server.expect(requestTo(BASE_PATH + "users?name=John&entry_date_from=2023-01-01&entry_date_to=2023-12-31&resign_date_from=2023-01-01&resign_date_to=2023-12-31&resigned=false&employee_number=E123&page_token=token123&limit=10&sort_direction=asc&sort_by=name")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + UsersPage usersPage = userApi.fetchUsers("John", + LocalDate.parse("2023-01-01"), + LocalDate.parse("2023-12-31"), + LocalDate.parse("2023-01-01"), + LocalDate.parse("2023-12-31"), + false, + "E123", + "token123", + 10, + SortDirection.ASC, + UsersSortColumn.NAME); + + server.verify(); + + assertNotNull(usersPage); + assertEquals("token123", usersPage.getNextPageToken()); + + List users = usersPage.getData(); + assertNotNull(users); + assertEquals(1, users.size()); + + User user = users.get(0); + assertNotNull(user); + assertEquals("user123", user.getId()); + assertEquals("John", user.getFirstname()); + assertEquals("Doe", user.getLastname()); + assertEquals("John Doe", user.getFullname()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals("E123", user.getEmployeeNumber()); + assertEquals("EXT123", user.getExternalId()); + assertEquals("johndoe", user.getLogin().orElse(null)); + assertEquals(LocalDate.parse("2023-01-01"), user.getEntryDate().orElse(null)); + assertNull(user.getResignDate().orElse(null)); + + assertNotNull(user.getWorkScheduleModel().orElse(null)); + assertEquals("schedule123", user.getWorkScheduleModel().orElse(null).getId()); + assertEquals("Standard Schedule", user.getWorkScheduleModel().orElse(null).getName()); + + assertNotNull(user.getHolidayCalendar().orElse(null)); + assertEquals("calendar123", user.getHolidayCalendar().orElse(null).getId()); + assertEquals("Standard Holidays", user.getHolidayCalendar().orElse(null).getDescription()); + } + + @Test + void createUser() { + // given + UserCreate userCreate = new UserCreate() + .login("johndoe") + .firstname("John") + .lastname("Doe") + .email("john.doe@example.com") + .entryDate(LocalDate.parse("2023-01-01")) + .resignDate(null) + .employeeNumber("E123") + .externalId("EXT123") + .authProvider("provider") + .authIdentifier("identifier"); + + server.expect(requestTo(BASE_PATH + "users")) + .andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.login").value("johndoe")) + .andExpect(jsonPath("$.firstname").value("John")) + .andExpect(jsonPath("$.lastname").value("Doe")) + .andExpect(jsonPath("$.email").value("john.doe@example.com")) + .andExpect(jsonPath("$.entry_date").value("2023-01-01")) + .andExpect(jsonPath("$.resign_date").doesNotExist()) + .andExpect(jsonPath("$.employee_number").value("E123")) + .andExpect(jsonPath("$.external_id").value("EXT123")) + .andExpect(jsonPath("$.auth_provider").value("provider")) + .andExpect(jsonPath("$.auth_identifier").value("identifier")) + .andRespond(withSuccess(""" + { + "id": "user123", + "login": "johndoe", + "firstname": "John", + "lastname": "Doe", + "email": "john.doe@example.com", + "entry_date": "2023-01-01", + "resign_date": null, + "employee_number": "E123", + "external_id": "EXT123" + } + """, MediaType.APPLICATION_JSON)); + + User user = userApi.createUser(userCreate); + + server.verify(); + + assertNotNull(user); + assertEquals("user123", user.getId()); + assertEquals("johndoe", user.getLogin().get()); + assertEquals("John", user.getFirstname()); + assertEquals("Doe", user.getLastname()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals(LocalDate.parse("2023-01-01"), user.getEntryDate().orElse(null)); + assertNull(user.getResignDate().orElse(null)); + assertEquals("E123", user.getEmployeeNumber()); + assertEquals("EXT123", user.getExternalId()); + } + + @Test + void updateUser() { + // given + UserUpdate userUpdate = new UserUpdate() + .login("johndoe") + .firstname("John") + .lastname("Doe") + .email("john.doe@example.com"); + + server.expect(requestTo(BASE_PATH + "users/user123")) + .andExpect(method(HttpMethod.PATCH)) + .andExpect(jsonPath("$.login").value("johndoe")) + .andExpect(jsonPath("$.firstname").value("John")) + .andExpect(jsonPath("$.lastname").value("Doe")) + .andExpect(jsonPath("$.email").value("john.doe@example.com")) + .andExpect(jsonPath("$.entry_date").doesNotExist()) + .andExpect(jsonPath("$.resign_date").doesNotExist()) + .andExpect(jsonPath("$.employee_number").doesNotExist()) + .andRespond(withSuccess(""" + { + "id": "user123", + "login": "johndoe", + "firstname": "John", + "lastname": "Doe", + "email": "john.doe@example.com", + "entry_date": "2023-01-01", + "resign_date": null, + "employee_number": "E123", + "external_id": "EXT123" + } + """, MediaType.APPLICATION_JSON)); + + // when + User user = userApi.updateUser("user123", userUpdate); + + // then + server.verify(); + + assertNotNull(user); + assertEquals("user123", user.getId()); + assertEquals("johndoe", user.getLogin().get()); + assertEquals("John", user.getFirstname()); + assertEquals("Doe", user.getLastname()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals(LocalDate.parse("2023-01-01"), user.getEntryDate().orElse(null)); + assertNull(user.getResignDate().orElse(null)); + assertEquals("E123", user.getEmployeeNumber()); + assertEquals("EXT123", user.getExternalId()); + } + +} diff --git a/sdk/java-restclient/src/test/java/com/timr/api/apis/WorkingTimeApiTest.java b/sdk/java-restclient/src/test/java/com/timr/api/apis/WorkingTimeApiTest.java new file mode 100644 index 0000000..c659897 --- /dev/null +++ b/sdk/java-restclient/src/test/java/com/timr/api/apis/WorkingTimeApiTest.java @@ -0,0 +1,422 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.models.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openapitools.jackson.nullable.JsonNullable; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestClient; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +@Disabled("Temporarily disabled pending investigation of RestClient mock setup") +class WorkingTimeApiTest { + + private static final String BASE_PATH = "http://localhost:8081/"; + + private MockRestServiceServer server; + private WorkingTimeApi workingTimeApi; + + @BeforeEach + void setUp() { + var restClientBuilder = RestClient.builder(); + + ApiClient apiClient = new ApiClient(restClientBuilder); + apiClient.setBasePath(BASE_PATH); + apiClient.getAuthentication().setAccessToken("dummyToken"); + + server = MockRestServiceServer.bindTo(restClientBuilder).build(); + workingTimeApi = new WorkingTimeApi(apiClient); + } + + @Test + void getWorkingTime1() { + String id = "123"; + String jsonResponse = """ + { + "id": "123", + "start": "2023-10-10T10:00:00Z", + "end": "2023-10-10T18:00:00Z", + "break_time_total_minutes": 60, + "break_times": [], + "duration": null, + "changed": true, + "notes": "Worked on project", + "user": { "id": "user123" }, + "working_time_type": { "id": "type123" }, + "working_time_date_span": null, + "start_location": null, + "end_location": null, + "start_platform": null, + "end_platform": null, + "last_modified": "2023-10-10T18:00:00Z", + "last_modified_by": { "id": "user123" }, + "status": "changeable", + "metadata": null + } + """; + + server.expect(requestTo(BASE_PATH + "working-times/" + id)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + WorkingTime workingTime = workingTimeApi.getWorkingTime(id); + + server.verify(); + + assertNotNull(workingTime); + assertEquals("123", workingTime.getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T10:00:00Z"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getEnd()); + assertEquals(60, workingTime.getBreakTimeTotalMinutes()); + assertTrue(workingTime.getBreakTimes().isEmpty()); + assertTrue(workingTime.getChanged()); + assertEquals("Worked on project", workingTime.getNotes()); + assertEquals("user123", workingTime.getUser().getId()); + assertEquals("type123", workingTime.getWorkingTimeType().getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getLastModified()); + assertEquals("user123", workingTime.getLastModifiedBy().getId()); + assertEquals(WorkingTimeStatus.CHANGEABLE, workingTime.getStatus()); + } + + @Test + void getWorkingTime2() { + String id = "123"; + String jsonResponse = """ + { + "id": "123", + "start": "2023-10-10T10:00:00Z", + "end": "2023-10-10T18:00:00Z", + "break_time_total_minutes": 60, + "break_times": [ + { + "type": "manual", + "start" : "2023-10-10T12:00:00Z", + "end" : "2023-10-10T12:30:00Z", + "duration_minutes": 30 + }, + { + "type": "automatic", + "start" : "2023-10-10T14:00:00Z", + "end" : "2023-10-10T15:00:00Z", + "duration_minutes": 60 + } + ], + "duration": null, + "changed": true, + "notes": "Worked on project", + "user": { "id": "user123" }, + "working_time_type": { "id": "type123" }, + "working_time_date_span": null, + "start_location": { + "lat": 12.34, + "lon": 56.78, + "timestamp": "2023-10-10T12:00:00Z", + "formatted_address": "Example street 123" + }, + "end_location": { + "lat": 98.76, + "lon": 55.77, + "timestamp": "2023-10-10T12:00:00Z", + "formatted_address": "Marina" + }, + "start_platform": "timr_api", + "end_platform": "timr_api", + "last_modified": "2023-10-10T18:00:00Z", + "last_modified_by": { "id": "user123" }, + "status": "changeable" + } + """; + + server.expect(requestTo(BASE_PATH + "working-times/" + id)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + WorkingTime workingTime = workingTimeApi.getWorkingTime(id); + + assertNotNull(workingTime); + assertEquals("123", workingTime.getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T10:00:00Z"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getEnd()); + assertEquals(60, workingTime.getBreakTimeTotalMinutes()); + + assertFalse(workingTime.getBreakTimes().isEmpty()); + assertEquals(BreakTimeType.MANUAL, workingTime.getBreakTimes().get(0).getType()); + BreakTimeManual manualModel = (BreakTimeManual) workingTime.getBreakTimes().get(0); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00Z"), manualModel.getStart().get()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:30:00Z"), manualModel.getEnd().get()); + assertEquals(30, manualModel.getDurationMinutes()); + assertEquals(BreakTimeType.AUTOMATIC, workingTime.getBreakTimes().get(1).getType()); + BreakTimeAutomatic automaticModel = (BreakTimeAutomatic) workingTime.getBreakTimes().get(1); + assertEquals(OffsetDateTime.parse("2023-10-10T14:00:00Z"), automaticModel.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T15:00:00Z"), automaticModel.getEnd()); + assertEquals(60, automaticModel.getDurationMinutes()); + + assertTrue(workingTime.getChanged()); + assertEquals("Worked on project", workingTime.getNotes()); + assertEquals("user123", workingTime.getUser().getId()); + assertEquals("type123", workingTime.getWorkingTimeType().getId()); + + assertEquals(12.34f, workingTime.getStartLocation().getLat()); + assertEquals(56.78f, workingTime.getStartLocation().getLon()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00Z"), workingTime.getStartLocation().getTimestamp().get()); + assertEquals("Example street 123", workingTime.getStartLocation().getFormattedAddress().get()); + assertNotNull(workingTime.getEndLocation()); + assertEquals(98.76f, workingTime.getEndLocation().getLat()); + assertEquals(55.77f, workingTime.getEndLocation().getLon()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00Z"), workingTime.getEndLocation().getTimestamp().get()); + assertEquals("Marina", workingTime.getEndLocation().getFormattedAddress().get()); + assertEquals(Platform.TIMR_API, workingTime.getStartPlatform()); + assertEquals(Platform.TIMR_API, workingTime.getEndPlatform()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getLastModified()); + assertEquals("user123", workingTime.getLastModifiedBy().getId()); + assertEquals(WorkingTimeStatus.CHANGEABLE, workingTime.getStatus()); + assertEquals(JsonNullable.undefined(), workingTime.getMetadata()); + + server.verify(); + } + + + @Test + void deserializesRfc3339DateTimeWithOffsetAndFraction() { + // RFC3339 permits a numeric UTC offset and fractional seconds (not just a trailing "Z"). + // Verify both are parsed to the correct instant. + String jsonResponse = """ + { + "id": "123", + "start": "2023-10-10T12:00:00.123+02:00", + "end": "2023-10-10T20:30:45-04:30", + "break_time_total_minutes": 60, + "break_times": [], + "changed": true, + "user": { "id": "user123" }, + "working_time_type": { "id": "type123" }, + "last_modified": "2023-10-10T18:00:00Z", + "status": "changeable" + } + """; + + server.expect(requestTo(BASE_PATH + "working-times/123")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + WorkingTime workingTime = workingTimeApi.getWorkingTime("123"); + + server.verify(); + // 12:00:00.123+02:00 is the same instant as 10:00:00.123Z + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00.123+02:00").toInstant(), workingTime.getStart().toInstant()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00.123+02:00"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T20:30:45-04:30"), workingTime.getEnd()); + // 20:30:45-04:30 is the same instant as 2023-10-11T01:00:45Z. + assertEquals(OffsetDateTime.parse("2023-10-11T01:00:45Z").toInstant(), workingTime.getEnd().toInstant()); + } + + @Test + void serializesRfc3339DateTimeWithNonUtcOffset() { + // A date-time carrying a non-UTC offset must be serialized as a valid RFC3339 string. + WorkingTimeCreate workingTimeCreate = new WorkingTimeCreate() + .start(OffsetDateTime.parse("2023-10-10T12:00:00+02:00")) + .end(OffsetDateTime.parse("2023-10-10T18:00:00Z")) + .breakTimes(new ArrayList<>()) + .changed(true) + .workingTimeTypeId("typeId") + .status(WorkingTimeStatus.CHANGEABLE) + .userId("userId"); + + server.expect(requestTo(BASE_PATH + "working-times")) + .andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.start").value("2023-10-10T12:00:00+02:00")) + .andExpect(jsonPath("$.end").value("2023-10-10T18:00:00Z")) + .andRespond(withSuccess(""" + { + "id": "id", + "start": "2023-10-10T12:00:00+02:00", + "end": "2023-10-10T18:00:00Z", + "break_times": [], + "changed": true, + "working_time_type": { "id" : "typeId" }, + "status": "changeable", + "user": {"id": "userId" } + } + """, MediaType.APPLICATION_JSON)); + + WorkingTime workingTime = workingTimeApi.createWorkingTime(workingTimeCreate); + + server.verify(); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00+02:00").toInstant(), workingTime.getStart().toInstant()); + } + + @Test + void createWorkingTime() { + // given + WorkingTimeCreate workingTimeCreate = new WorkingTimeCreate() + .start(OffsetDateTime.parse("2023-10-10T10:00:00Z")) + .end(OffsetDateTime.parse("2023-10-10T18:00:00Z")) + .breakTimes(new ArrayList<>()) + .durationType(DurationType.FULL_DAY) + .changed(true) + .notes("Test notes") + .workingTimeTypeId("typeId") + .status(WorkingTimeStatus.CHANGEABLE) + .metadata(Map.of("key", "value")) + .userId("userId"); + + server.expect(requestTo(BASE_PATH + "working-times")) + .andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.start").value("2023-10-10T10:00:00Z")) + .andExpect(jsonPath("$.end").value("2023-10-10T18:00:00Z")) + .andExpect(jsonPath("$.break_times").isEmpty()) + .andExpect(jsonPath("$.duration_type").value("full_day")) + .andExpect(jsonPath("$.changed").value(true)) + .andExpect(jsonPath("$.notes").value("Test notes")) + .andExpect(jsonPath("$.working_time_type_id").value("typeId")) + .andExpect(jsonPath("$.start_location").doesNotExist()) + .andExpect(jsonPath("$.end_location").doesNotExist()) + .andExpect(jsonPath("$.status").value("changeable")) + .andExpect(jsonPath("$.metadata.key").value("value")) + .andExpect(jsonPath("$.user_id").value("userId")) + .andExpect(jsonPath("$.status").value("changeable")) + .andRespond(withSuccess(""" + { + "id": "id", + "start": "2023-10-10T10:00:00Z", + "end": "2023-10-10T18:00:00Z", + "break_times": [], + "duration": { + "type": "full_day", + "minutes": 480 + }, + "changed": true, + "notes": "Test notes", + "working_time_type": { "id" : "typeId" }, + "start_location": {}, + "end_location": {}, + "status": "changeable", + "metadata": {"key": "value"}, + "user": {"id": "userId" } + } + """, MediaType.APPLICATION_JSON)); + + // when + WorkingTime workingTime = workingTimeApi.createWorkingTime(workingTimeCreate); + + // then + server.verify(); + + assertNotNull(workingTime); + assertEquals("id", workingTime.getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T10:00:00Z"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getEnd()); + assertEquals(0, workingTime.getBreakTimes().size()); + assertEquals(DurationType.FULL_DAY, workingTime.getDuration().getType()); + assertTrue(workingTime.getChanged()); + assertEquals("Test notes", workingTime.getNotes()); + assertEquals("typeId", workingTime.getWorkingTimeType().getId()); + assertNotNull(workingTime.getStartLocation()); + assertNotNull(workingTime.getEndLocation()); + assertEquals(WorkingTimeStatus.CHANGEABLE, workingTime.getStatus()); + assertEquals(JsonNullable.of(Map.of("key", "value")), workingTime.getMetadata()); + assertEquals("userId", workingTime.getUser().getId()); + + // todo breaktimes + } + + @Test + void updateWorkingTime() { + // given + var breakTimeManual = new BreakTimeManual() + .durationMinutes(30) + .start(OffsetDateTime.parse("2023-10-10T12:00:00Z")) + .end(OffsetDateTime.parse("2023-10-10T12:30:00Z")); + + WorkingTimeUpdate workingTimeUpdate = new WorkingTimeUpdate() + .start(OffsetDateTime.parse("2023-10-10T10:00:00Z")) + .end(OffsetDateTime.parse("2023-10-10T18:00:00Z")) + .breakTimes(List.of(breakTimeManual)) + .notes("Test notes") + .workingTimeTypeId("typeId") + .status(WorkingTimeStatus.CHANGEABLE) + .metadata(Map.of("key", "value")); + + server.expect(requestTo(BASE_PATH + "working-times/123")) + .andExpect(method(HttpMethod.PATCH)) + .andExpect(jsonPath("$.start").value("2023-10-10T10:00:00Z")) + .andExpect(jsonPath("$.end").value("2023-10-10T18:00:00Z")) + .andExpect(jsonPath("$.break_times[0].type").value("manual")) + .andExpect(jsonPath("$.break_times[0].start").value("2023-10-10T12:00:00Z")) + .andExpect(jsonPath("$.break_times[0].end").value("2023-10-10T12:30:00Z")) + .andExpect(jsonPath("$.break_times[0].duration_minutes").value(30)) + .andExpect(jsonPath("$.notes").value("Test notes")) + .andExpect(jsonPath("$.working_time_type_id").value("typeId")) + .andExpect(jsonPath("$.status").value("changeable")) + .andExpect(jsonPath("$.metadata.key").value("value")) + .andRespond(withSuccess(""" + { + "id": "123", + "start": "2023-10-10T10:00:00Z", + "end": "2023-10-10T18:00:00Z", + "break_time_total_minutes": 60, + "break_times": [ + { + "type": "manual", + "start" : "2023-10-10T12:00:00Z", + "end" : "2023-10-10T12:30:00Z", + "duration_minutes": 30 + } + ], + "duration": { + "type": "full_day", + "minutes": 480 + }, + "changed": true, + "notes": "Test notes", + "working_time_type": { "id" : "typeId" }, + "start_location": {}, + "end_location": {}, + "status": "changeable", + "metadata": {"key": "value"}, + "user": {"id": "userId" } + } + """, MediaType.APPLICATION_JSON)); + + // when + WorkingTime workingTime = workingTimeApi.updateWorkingTime("123", workingTimeUpdate); + + // then + server.verify(); + + assertNotNull(workingTime); + assertEquals("123", workingTime.getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T10:00:00Z"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getEnd()); + assertEquals(60, workingTime.getBreakTimeTotalMinutes()); + assertFalse(workingTime.getBreakTimes().isEmpty()); + assertEquals(BreakTimeType.MANUAL, workingTime.getBreakTimes().get(0).getType()); + BreakTimeManual manualModel = (BreakTimeManual) workingTime.getBreakTimes().get(0); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00Z"), manualModel.getStart().get()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:30:00Z"), manualModel.getEnd().get()); + assertEquals(30, manualModel.getDurationMinutes()); + assertEquals(DurationType.FULL_DAY, workingTime.getDuration().getType()); + assertEquals(480, workingTime.getDuration().getMinutes()); + assertTrue(workingTime.getChanged()); + assertEquals("Test notes", workingTime.getNotes()); + assertEquals("typeId", workingTime.getWorkingTimeType().getId()); + assertNotNull(workingTime.getStartLocation()); + assertNotNull(workingTime.getEndLocation()); + assertEquals(WorkingTimeStatus.CHANGEABLE, workingTime.getStatus()); + assertEquals(JsonNullable.of(Map.of("key", "value")), workingTime.getMetadata()); + assertEquals("userId", workingTime.getUser().getId()); + } + +} diff --git a/sdk/java-restclient/src/test/java/com/timr/api/apis/WorkingTimeTypeApiTest.java b/sdk/java-restclient/src/test/java/com/timr/api/apis/WorkingTimeTypeApiTest.java new file mode 100644 index 0000000..f915095 --- /dev/null +++ b/sdk/java-restclient/src/test/java/com/timr/api/apis/WorkingTimeTypeApiTest.java @@ -0,0 +1,117 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.models.DurationUnit; +import com.timr.api.models.RecordingModeUser; +import com.timr.api.models.WorkingTimeTypeCategory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestClient; + + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +@Disabled("Temporarily disabled pending investigation of RestClient mock setup") +class WorkingTimeTypeApiTest { + + private static final String BASE_PATH = "http://localhost:8080/"; + + private MockRestServiceServer server; + private WorkingTimeTypeApi workingTimeTypeApi; + + @BeforeEach + void setUp() { + var restClientBuilder = RestClient.builder(); + + ApiClient apiClient = new ApiClient(restClientBuilder); + apiClient.setBasePath(BASE_PATH); + apiClient.getAuthentication().setAccessToken("dummyToken"); + + server = MockRestServiceServer.bindTo(restClientBuilder).build(); + workingTimeTypeApi = new WorkingTimeTypeApi(apiClient); + } + + @Test + void getWorkingTimeTypes() { + //given + server.expect(requestTo(BASE_PATH + "working-time-types")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(""" + { + "next_page_token": "string", + "data": [ + { + "id": "id", + "name": "example", + "short_name": "exmpl", + "description": "attendance type", + "external_id": "external id", + "edit_unit": "minutes", + "category": "attendance_time", + "sub_category": "present", + "recording_mode_user": "not_allowed", + "archived": true + } + ] + } + """, MediaType.APPLICATION_JSON)); + + // when + var workingTimes = workingTimeTypeApi.fetchWorkingTimeTypes(null, null, null, null, null, null, null, null, null, null, null, null); + + // then + server.verify(); + var workingTimeType = workingTimes.getData().get(0); + assertEquals("id", workingTimeType.getId()); + assertEquals("example", workingTimeType.getName()); + assertEquals("exmpl", workingTimeType.getShortName()); + assertEquals("attendance type", workingTimeType.getDescription()); + assertEquals("external id", workingTimeType.getExternalId()); + assertEquals(true, workingTimeType.getArchived()); + } + + @Test + void getWorkingTimeType() { + //given + server.expect(requestTo(BASE_PATH + "working-time-types/id")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(""" + { + "id": "id", + "name": "example", + "short_name": "exmpl", + "description": "attendance type", + "external_id": "external id", + "edit_unit": "days", + "category": "paid_time_off", + "recording_mode_user": "by_request", + "archived": false + } + """, MediaType.APPLICATION_JSON)); + + // when + var workingTimeType = workingTimeTypeApi.getWorkingTimeType("id"); + + // then + server.verify(); + + assertNotNull(workingTimeType); + assertEquals("id", workingTimeType.getId()); + assertEquals("example", workingTimeType.getName()); + assertEquals("exmpl", workingTimeType.getShortName()); + assertEquals("attendance type", workingTimeType.getDescription()); + assertEquals("external id", workingTimeType.getExternalId()); + assertEquals(DurationUnit.DAYS, workingTimeType.getEditUnit()); + assertEquals(WorkingTimeTypeCategory.PAID_TIME_OFF, workingTimeType.getCategory()); + assertEquals(RecordingModeUser.BY_REQUEST, workingTimeType.getRecordingModeUser()); + assertFalse(workingTimeType.getArchived()); + } + +} diff --git a/sdk/java-restclient/src/test/java/com/timr/api/app/TestApp.java b/sdk/java-restclient/src/test/java/com/timr/api/app/TestApp.java new file mode 100644 index 0000000..ce7ea48 --- /dev/null +++ b/sdk/java-restclient/src/test/java/com/timr/api/app/TestApp.java @@ -0,0 +1,18 @@ +package com.timr.api.app; + +import com.timr.api.ApiClient; +import com.timr.api.TimrAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; + +@SpringBootApplication +@Import(TimrAutoConfiguration.class) +public class TestApp { + + @Bean + public ApiClient apiClient() { + return new ApiClient(); + } + +} diff --git a/sdk/java-restclient/src/test/java/com/timr/api/app/TestDependencies.java b/sdk/java-restclient/src/test/java/com/timr/api/app/TestDependencies.java new file mode 100644 index 0000000..f1c08be --- /dev/null +++ b/sdk/java-restclient/src/test/java/com/timr/api/app/TestDependencies.java @@ -0,0 +1,28 @@ +package com.timr.api.app; + +import com.timr.api.ApiClient; +import com.timr.api.TimrAutoConfiguration; +import com.timr.api.apis.UserApi; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest(classes = TestApp.class) +@ContextConfiguration(classes = {TimrAutoConfiguration.class}) +class TestDependencies { + + @Autowired(required = false) + private ApiClient apiClient; + + @Autowired(required = false) + private UserApi userApi; + + @Test + void test() { + assertThat(apiClient).isNotNull(); + assertThat(userApi).isNotNull(); + } +} diff --git a/sdk/java-restclient/src/test/java/com/timr/api/app/TimrAutoConfigurationTest.java b/sdk/java-restclient/src/test/java/com/timr/api/app/TimrAutoConfigurationTest.java new file mode 100644 index 0000000..5b60e3d --- /dev/null +++ b/sdk/java-restclient/src/test/java/com/timr/api/app/TimrAutoConfigurationTest.java @@ -0,0 +1,46 @@ +package com.timr.api.app; + +import com.timr.api.ApiClient; +import com.timr.api.TimrAutoConfiguration; +import com.timr.api.apis.CarApi; +import com.timr.api.apis.DriveLogApi; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class TimrAutoConfigurationTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(TimrAutoConfiguration.class)); + + @Test + void testCarApiBeanCreation() { + this.contextRunner.withUserConfiguration(ApiClientConfiguration.class) + .run(context -> { + assertThat(context).hasSingleBean(CarApi.class); + }); + } + + @Test + void testDriveLogApiBeanCreation() { + this.contextRunner.withUserConfiguration(ApiClientConfiguration.class) + .run(context -> { + assertThat(context).hasSingleBean(DriveLogApi.class); + }); + } + + + @Configuration + static class ApiClientConfiguration { + @Bean + public ApiClient apiClient() { + return new ApiClient(); + } + } +} diff --git a/sdk/java-restclient/src/test/java/com/timr/api/models/ModelToStringLogSafetyTest.java b/sdk/java-restclient/src/test/java/com/timr/api/models/ModelToStringLogSafetyTest.java new file mode 100644 index 0000000..c213649 --- /dev/null +++ b/sdk/java-restclient/src/test/java/com/timr/api/models/ModelToStringLogSafetyTest.java @@ -0,0 +1,44 @@ +package com.timr.api.models; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class ModelToStringLogSafetyTest { + + @Test + void durationToStringIncludesUsefulSummaryFields() { + String rendered = new Duration() + .type(DurationType.MINUTES) + .minutes(42L) + .minutesRounded(45L) + .toString(); + + assertTrue(rendered.contains("type: minutes")); + assertTrue(rendered.contains("minutes: 42")); + assertFalse(rendered.contains("minutesRounded: 45")); + } + + @Test + void breakTimeToStringIsNotEmpty() { + // type() is inherited from BreakTimeBase and returns the base type, so the + // variant's own setters have to come first for the chain to stay typed. + String rendered = new BreakTimeManual() + .durationMinutes(15) + .type(BreakTimeType.MANUAL) + .toString(); + + assertTrue(rendered.contains("type: manual")); + assertTrue(rendered.contains("durationMinutes: 15")); + } + + @Test + void pagingInformationToStringDoesNotExposePageToken() { + String rendered = new PagingInformation() + .nextPageToken("next-page-token") + .toString(); + + assertFalse(rendered.contains("next-page-token")); + } +} diff --git a/sdk/java-restclient/templates/nullable_var_annotations.mustache b/sdk/java-restclient/templates/nullable_var_annotations.mustache new file mode 100644 index 0000000..ef4e208 --- /dev/null +++ b/sdk/java-restclient/templates/nullable_var_annotations.mustache @@ -0,0 +1 @@ +{{#lambda.jSpecifyNullable}}{{#required}}{{#isNullable}}@{{javaxPackage}}.annotation.Nullable{{/isNullable}}{{^useJspecify}}{{^isNullable}}@{{javaxPackage}}.annotation.Nonnull{{/isNullable}}{{/useJspecify}}{{/required}}{{^required}}@{{javaxPackage}}.annotation.Nullable{{/required}}{{/lambda.jSpecifyNullable}} \ No newline at end of file diff --git a/sdk/java-restclient/templates/pojo.mustache b/sdk/java-restclient/templates/pojo.mustache new file mode 100644 index 0000000..f8d7f27 --- /dev/null +++ b/sdk/java-restclient/templates/pojo.mustache @@ -0,0 +1,625 @@ +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * {{description}}{{^description}}{{classname}}{{/description}}{{#isDeprecated}} + * @deprecated{{/isDeprecated}} + */{{#isDeprecated}} +@Deprecated{{/isDeprecated}} +{{#swagger1AnnotationLibrary}} +{{#description}} +@ApiModel(description = "{{{.}}}") +{{/description}} +{{/swagger1AnnotationLibrary}} +{{#swagger2AnnotationLibrary}} +{{#description}} +@Schema(description = "{{{.}}}") +{{/description}} +{{/swagger2AnnotationLibrary}} +{{#jackson}} +@JsonPropertyOrder({ +{{#vars}} + {{classname}}.JSON_PROPERTY_{{nameInSnakeCase}}{{^-last}},{{/-last}} +{{/vars}} +}) +{{#isClassnameSanitized}} +{{^hasDiscriminatorWithNonEmptyMapping}} +@JsonTypeName("{{name}}") +{{/hasDiscriminatorWithNonEmptyMapping}} +{{/isClassnameSanitized}} +{{/jackson}} +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{>xmlAnnotation}} +{{#vendorExtensions.x-class-extra-annotation}} +{{{vendorExtensions.x-class-extra-annotation}}} +{{/vendorExtensions.x-class-extra-annotation}} +public {{>sealed}}class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{#-last}} {{/-last}}{{/vendorExtensions.x-implements}}{{>permits}}{ +{{#serializableModel}} + private static final long serialVersionUID = 1L; + +{{/serializableModel}} + {{#vars}} + {{#isEnum}} + {{^isContainer}} +{{>modelInnerEnum}} + + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} +{{>modelInnerEnum}} + + {{/mostInnerItems}} + {{/isContainer}} + {{/isEnum}} + {{#gson}} + public static final String SERIALIZED_NAME_{{nameInSnakeCase}} = "{{baseName}}"; + {{/gson}} + {{#jackson}} + public static final String JSON_PROPERTY_{{nameInSnakeCase}} = "{{baseName}}"; + {{/jackson}} + {{#withXml}} + @Xml{{#isXmlAttribute}}Attribute{{/isXmlAttribute}}{{^isXmlAttribute}}Element{{/isXmlAttribute}}(name = "{{items.xmlName}}{{^items.xmlName}}{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}{{/items.xmlName}}"{{#xmlNamespace}}, namespace = "{{.}}"{{/xmlNamespace}}) + {{#isXmlWrapped}} + @XmlElementWrapper(name = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}"{{#xmlNamespace}}, namespace = "{{.}}"{{/xmlNamespace}}) + {{/isXmlWrapped}} + {{^isXmlAttribute}} + {{#isDateTime}} + @XmlJavaTypeAdapter(OffsetDateTimeXmlAdapter.class) + {{/isDateTime}} + {{/isXmlAttribute}} + {{/withXml}} + {{#gson}} + @SerializedName(SERIALIZED_NAME_{{nameInSnakeCase}}) + {{/gson}} + {{^isDiscriminator}} + {{>nullable_var_annotations}}{{! prevent indent}} + {{/isDiscriminator}} + {{#isDiscriminator}} + // The discriminator does not have Nullability-annotation since it is added during serialization by the @JsonTypeName annotation + {{/isDiscriminator}} + {{#vendorExtensions.x-field-extra-annotation}} + {{{.}}} + {{/vendorExtensions.x-field-extra-annotation}} + {{^required}} + {{#isContainer}} + {{#hasChildren}}protected{{/hasChildren}}{{^hasChildren}}private{{/hasChildren}} JsonNullable<{{>nullableDatatypeWithEnum}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined(); + {{/isContainer}} + {{^isContainer}} + {{#hasChildren}}protected{{/hasChildren}}{{^hasChildren}}private{{/hasChildren}} JsonNullable<{{>nullableDatatypeWithEnum}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; + {{/isContainer}} + {{/required}} + {{#required}} + {{#isContainer}} + {{#hasChildren}}protected{{/hasChildren}}{{^hasChildren}}private{{/hasChildren}} {{>nullableDatatypeWithEnum}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{/isContainer}} + {{^isContainer}} + {{#hasChildren}}protected{{/hasChildren}}{{^hasChildren}}private{{/hasChildren}} {{>nullableDatatypeWithEnum}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{/isContainer}} + {{/required}} + + {{/vars}} + public {{classname}}() { + {{#parent}} + {{#parcelableModel}} + super();{{/parcelableModel}} + {{/parent}} + {{#gson}} + {{#discriminator}} + {{#discriminator.isEnum}} + this.{{{discriminatorName}}} = this.getClass().getSimpleName(); + {{/discriminator.isEnum}} + {{/discriminator}} + {{/gson}} + } + {{#vendorExtensions.x-has-readonly-properties}} + {{^withXml}} + /** + * Constructor with only readonly parameters{{#generateConstructorWithAllArgs}}{{^vendorExtensions.x-java-all-args-constructor}} and all parameters{{/vendorExtensions.x-java-all-args-constructor}}{{/generateConstructorWithAllArgs}} + */ + {{#jsonb}}@JsonbCreator{{/jsonb}}{{#jackson}}@JsonCreator{{/jackson}} + public {{classname}}( + {{#readOnlyVars}} + {{#jsonb}}@JsonbProperty(value = "{{baseName}}"{{^required}}, nullable = true{{/required}}){{/jsonb}}{{#jackson}}@JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}){{/jackson}} {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} + {{/readOnlyVars}} + ) { + this(); + {{#readOnlyVars}} + this.{{name}} = {{^required}}{{name}} == null ? JsonNullable.<{{{datatypeWithEnum}}}>undefined() : JsonNullable.of({{name}}){{/required}}{{#required}}{{name}}{{/required}}; + {{/readOnlyVars}} + } + {{/withXml}} + {{/vendorExtensions.x-has-readonly-properties}} +{{#vendorExtensions.x-java-all-args-constructor}} + + /** + * Constructor with all args parameters + */ + public {{classname}}({{#vendorExtensions.x-java-all-args-constructor-vars}}{{#jsonb}}@JsonbProperty(value = "{{baseName}}"{{^required}}, nullable = true{{/required}}){{/jsonb}}{{#jackson}}@JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}){{/jackson}} {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-java-all-args-constructor-vars}}) { +{{#parent}} + super({{#parentVars}}{{name}}{{^-last}}, {{/-last}}{{/parentVars}}); +{{/parent}} + {{#vars}} + this.{{name}} = {{^required}}{{name}} == null ? JsonNullable.<{{{datatypeWithEnum}}}>undefined() : JsonNullable.of({{name}}){{/required}}{{#required}}{{name}}{{/required}}; +{{/vars}} + } +{{/vendorExtensions.x-java-all-args-constructor}} + +{{#vars}} + {{^isReadOnly}} + public {{classname}} {{name}}({{>nullableArgumentWithEnum}} {{name}}) { + {{^required}}this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}});{{/required}} + {{#required}}this.{{name}} = {{name}};{{/required}} + return this; + } + {{#isArray}} + + public {{classname}} add{{nameInPascalCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + {{^required}} + if (this.{{name}} == null || !this.{{name}}.isPresent()) { + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}{{^defaultValue}}new {{#uniqueItems}}LinkedHashSet{{/uniqueItems}}{{^uniqueItems}}ArrayList{{/uniqueItems}}<>(){{/defaultValue}}); + } + try { + this.{{name}}.get().add({{name}}Item); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + {{/required}} + {{#required}} + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}{{^defaultValue}}new {{#uniqueItems}}LinkedHashSet{{/uniqueItems}}{{^uniqueItems}}ArrayList{{/uniqueItems}}<>(){{/defaultValue}}; + } + this.{{name}}.add({{name}}Item); + return this; + {{/required}} + } + {{/isArray}} + {{#isMap}} + + public {{classname}} put{{nameInPascalCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + {{^required}} + if (this.{{name}} == null || !this.{{name}}.isPresent()) { + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}{{^defaultValue}}new HashMap<>(){{/defaultValue}}); + } + try { + this.{{name}}.get().put(key, {{name}}Item); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + {{/required}} + {{#required}} + {{^required}} + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}{{^defaultValue}}new HashMap<>(){{/defaultValue}}; + } + {{/required}} + this.{{name}}.put(key, {{name}}Item); + return this; + {{/required}} + } + {{/isMap}} + + {{/isReadOnly}} + /** + {{#description}} + * {{.}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + * @return {{name}} + {{#deprecated}} + * @deprecated + {{/deprecated}} + */ +{{#deprecated}} + @Deprecated +{{/deprecated}} + {{>nullable_var_annotations}}{{! prevent indent}} +{{#jsonb}} + @JsonbProperty("{{baseName}}") +{{/jsonb}} +{{#useBeanValidation}} +{{>beanValidation}} + +{{/useBeanValidation}} +{{#swagger1AnnotationLibrary}} + @ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{/swagger1AnnotationLibrary}} +{{#swagger2AnnotationLibrary}} + @Schema({{#example}}example = "{{{.}}}", {{/example}}requiredMode = {{#required}}Schema.RequiredMode.REQUIRED{{/required}}{{^required}}Schema.RequiredMode.NOT_REQUIRED{{/required}}, description = "{{{description}}}") +{{/swagger2AnnotationLibrary}} +{{#vendorExtensions.x-extra-annotation}} + {{{vendorExtensions.x-extra-annotation}}} +{{/vendorExtensions.x-extra-annotation}} +{{#required}}{{#jackson}}{{> jackson_annotations}}{{/jackson}} + public {{>nullableDatatypeWithEnum}} {{getter}}() { + return {{name}}; + } +{{/required}} +{{^required}} +{{> jackson_annotations}} + public JsonNullable<{{>nullableDatatypeWithEnum}}> {{getter}}() { + {{#isReadOnly}}{{! A readonly attribute doesn't have setter => jackson will set null directly if explicitly returned by API, so make sure we have an empty JsonNullable}} + if ({{name}} == null) { + {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; + } + {{/isReadOnly}} + return {{name}}; + } + + @JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}) + {{#isReadOnly}}private{{/isReadOnly}}{{^isReadOnly}}public{{/isReadOnly}} void {{setter}}(JsonNullable<{{{datatypeWithEnum}}}> {{name}}) { + {{! For getters/setters that have name differing from attribute name, we must include setter (albeit private) for jackson to be able to set the attribute}} + this.{{name}} = {{name}}; + } +{{/required}} + + {{^isReadOnly}}{{#required}} +{{#vendorExtensions.x-setter-extra-annotation}} {{{vendorExtensions.x-setter-extra-annotation}}} +{{/vendorExtensions.x-setter-extra-annotation}}{{#jackson}}{{> jackson_annotations}}{{/jackson}} public void {{setter}}({{>nullableArgumentWithEnum}} {{name}}) { + this.{{name}} = {{name}}; + } + {{/required}}{{/isReadOnly}} + + {{/vars}} +{{>libraries/restclient/additional_properties}} + + {{#parent}} + {{#readWriteVars}} + {{#isOverridden}} + @Override + public {{classname}} {{name}}({{>nullableArgumentWithEnum}} {{name}}) { + {{^required}} + this.{{setter}}(JsonNullable.<{{{datatypeWithEnum}}}>of({{name}})); + {{/required}} + {{#required}} + this.{{setter}}({{name}}); + {{/required}} + return this; + } + + {{/isOverridden}} + {{/readWriteVars}} + {{/parent}} + @Override + public boolean equals(Object o) { + {{#useReflectionEqualsHashCode}} + return EqualsBuilder.reflectionEquals(this, o, false, null, true); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}{{^required}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/required}}{{#required}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/required}}{{^-last}} && + {{/-last}}{{/vars}}{{#additionalPropertiesType}} && + Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/additionalPropertiesType}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} + return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} + {{/useReflectionEqualsHashCode}} + }{{#openApiNullable}} + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + }{{/openApiNullable}} + + @Override + public int hashCode() { + {{#useReflectionEqualsHashCode}} + return HashCodeBuilder.reflectionHashCode(this); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + return Objects.hash({{#vars}}{{^required}}hashCodeNullable({{name}}){{/required}}{{#required}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/required}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}, additionalProperties{{/additionalPropertiesType}}); + {{/useReflectionEqualsHashCode}} + }{{#openApiNullable}} + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + }{{/openApiNullable}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}} + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + {{/parent}} + {{#vars}} + {{#vendorExtensions.x-log}} + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); + {{/vendorExtensions.x-log}} + {{#vendorExtensions.x-log-count}} + {{^required}} + sb.append(" {{name}}: ").append(!{{name}}.isPresent() || {{name}}.get() == null ? "null" : {{name}}.get().size() + " entries").append("\n"); + {{/required}} + {{#required}} + sb.append(" {{name}}: ").append({{name}} == null ? "null" : {{name}}.size() + " entries").append("\n"); + {{/required}} + {{/vendorExtensions.x-log-count}} + {{/vars}} + {{#additionalPropertiesType}} + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + {{/additionalPropertiesType}} + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private{{#jsonb}} static{{/jsonb}} String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } +{{#supportUrlQuery}} + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + {{#allVars}} + // add `{{baseName}}` to the URL query string + {{#isArray}} + {{#items.isPrimitiveType}} + {{#uniqueItems}} + if ({{getter}}() != null) { + int i = 0; + for ({{{items.datatypeWithEnum}}} _item : {{getter}}()) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(String.valueOf(_item), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + i++; + } + {{/uniqueItems}} + {{^uniqueItems}} + if ({{getter}}() != null) { + for (int i = 0; i < {{getter}}().size(); i++) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(String.valueOf({{getter}}().get(i)), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + } + {{/uniqueItems}} + {{/items.isPrimitiveType}} + {{^items.isPrimitiveType}} + {{#items.isModel}} + {{#uniqueItems}} + if ({{getter}}() != null) { + int i = 0; + for ({{{items.dataType}}} _item : {{getter}}()) { + if (_item != null) { + joiner.add(_item.toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + i++; + } + {{/uniqueItems}} + {{^uniqueItems}} + if ({{getter}}() != null) { + for (int i = 0; i < {{getter}}().size(); i++) { + if ({{getter}}().get(i) != null) { + joiner.add({{getter}}().get(i).toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + {{/uniqueItems}} + {{/items.isModel}} + {{^items.isModel}} + {{#uniqueItems}} + if ({{getter}}() != null) { + int i = 0; + for ({{{items.dataType}}} _item : {{getter}}()) { + if (_item != null) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(String.valueOf(_item), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + i++; + } + } + {{/uniqueItems}} + {{^uniqueItems}} + if ({{getter}}() != null) { + for (int i = 0; i < {{getter}}().size(); i++) { + if ({{getter}}().get(i) != null) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(String.valueOf({{getter}}().get(i)), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + } + } + {{/uniqueItems}} + {{/items.isModel}} + {{/items.isPrimitiveType}} + {{/isArray}} + {{^isArray}} + {{#isMap}} + {{^items.isModel}} + if ({{getter}}() != null) { + for (String _key : {{getter}}().keySet()) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, _key, containerSuffix), + {{getter}}().get(_key), URLEncoder.encode(String.valueOf({{getter}}().get(_key)), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + } + {{/items.isModel}} + {{#items.isModel}} + if ({{getter}}() != null) { + for (String _key : {{getter}}().keySet()) { + if ({{getter}}().get(_key) != null) { + joiner.add({{getter}}().get(_key).toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, _key, containerSuffix)))); + } + } + } + {{/items.isModel}} + {{/isMap}} + {{^isMap}} + {{#isPrimitiveType}} + if ({{getter}}() != null) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{{baseName}}}%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf({{{getter}}}()), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isModel}} + if ({{getter}}() != null) { + joiner.add({{getter}}().toUrlQueryString(prefix + "{{{baseName}}}" + suffix)); + } + {{/isModel}} + {{^isModel}} + if ({{getter}}() != null) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{{baseName}}}%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf({{{getter}}}()), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + {{/isModel}} + {{/isPrimitiveType}} + {{/isMap}} + {{/isArray}} + + {{/allVars}} + return joiner.toString(); + } +{{/supportUrlQuery}} +{{#parcelableModel}} + + public void writeToParcel(Parcel out, int flags) { +{{#model}} +{{#isArray}} + out.writeList(this); +{{/isArray}} +{{^isArray}} +{{#parent}} + super.writeToParcel(out, flags); +{{/parent}} +{{#vars}} + out.writeValue({{name}}); +{{/vars}} +{{/isArray}} +{{/model}} + } + + {{classname}}(Parcel in) { +{{#isArray}} + in.readTypedList(this, {{arrayModelType}}.CREATOR); +{{/isArray}} +{{^isArray}} +{{#parent}} + super(in); +{{/parent}} +{{#vars}} +{{#isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); +{{/isPrimitiveType}} +{{^isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue({{complexType}}.class.getClassLoader()); +{{/isPrimitiveType}} +{{/vars}} +{{/isArray}} + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator<{{classname}}> CREATOR = new Parcelable.Creator<{{classname}}>() { + public {{classname}} createFromParcel(Parcel in) { +{{#model}} +{{#isArray}} + {{classname}} result = new {{classname}}(); + result.addAll(in.readArrayList({{arrayModelType}}.class.getClassLoader())); + return result; +{{/isArray}} +{{^isArray}} + return new {{classname}}(in); +{{/isArray}} +{{/model}} + } + public {{classname}}[] newArray(int size) { + return new {{classname}}[size]; + } + }; +{{/parcelableModel}} +{{#generateBuilders}} + + {{>javaBuilder}}{{! prevent indent}} +{{/generateBuilders}} + +} diff --git a/sdk/java-resttemplate/.gitignore b/sdk/java-resttemplate/.gitignore new file mode 100644 index 0000000..d919f54 --- /dev/null +++ b/sdk/java-resttemplate/.gitignore @@ -0,0 +1,2 @@ +# OpenApiGenerator generated meta files +.openapi-generator diff --git a/sdk/java-resttemplate/.openapi-generator-ignore b/sdk/java-resttemplate/.openapi-generator-ignore new file mode 100644 index 0000000..963a130 --- /dev/null +++ b/sdk/java-resttemplate/.openapi-generator-ignore @@ -0,0 +1,19 @@ +.github/** +.gitignore +.travis.yml +README.md +api/** +build.gradle +build.sbt +docs/** +git_push.sh +gradle.properties +gradle/** +gradlew +gradlew.bat +pom.xml +settings.gradle + +src/main/AndroidManifest.xml +src/main/java/com/timr/api/ApiClient.java +src/test/** diff --git a/sdk/java-resttemplate/build.gradle b/sdk/java-resttemplate/build.gradle new file mode 100644 index 0000000..9032340 --- /dev/null +++ b/sdk/java-resttemplate/build.gradle @@ -0,0 +1,78 @@ +plugins { + alias(libs.plugins.openapi) + id 'java-library' +} +repositories { + mavenCentral() +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(25) + } + withSourcesJar() + withJavadocJar() +} + +dependencies { + implementation platform(libs.spring.boot.dependencies) + + implementation 'tools.jackson.core:jackson-databind' + implementation 'com.fasterxml.jackson.core:jackson-annotations' + // JsonNullable is exposed in generated model getters/setters, so it is part of the public API + api libs.jackson.nullable + + implementation 'org.springframework:spring-web' + implementation 'org.springframework:spring-context' + + // @jakarta.annotation.Generated is emitted on every model + implementation libs.jakarta.annotation + // JSpecify annotations appear on generated public signatures, so consumers need them on their compile classpath + api libs.jspecify + implementation libs.swagger.annotations + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +test { + useJUnitPlatform() +} + +def cleanOpenApiGenerateTask = tasks.register('cleanOpenApiGenerate', Delete) { + delete fileTree("$projectDir/src/main/java/com/timr/api/apis") + delete fileTree("$projectDir/src/main/java/com/timr/api/models") +} + +openApiGenerate { + generatorName = 'java' + outputDir = "$projectDir" + templateDir = "$projectDir/templates" + configOptions = [ + library : 'resttemplate', + serializationLibrary : 'jackson', + useSpringBoot4 : 'true', + useJackson3 : 'true', + dateLibrary : 'java8', + openApiNullable : 'true', + containerDefaultToNull : 'true', + legacyDiscriminatorBehavior: 'true', + generateClientAsBean : 'true', + useJakartaEe : 'true', + apiPackage : 'com.timr.api.apis', + modelPackage : 'com.timr.api.models', + hideGenerationTimestamp : 'true' + ] +} + +tasks.named('openApiGenerate').configure { task -> + task.dependsOn(cleanOpenApiGenerateTask) +} + +// Generated sources are committed into this module's source set, so everything that reads them runs +// after generation; `build` on its own would otherwise quietly compile the previous generation's output. +tasks.matching { + it.name in ['compileJava', 'compileTestJava', 'processResources', 'processTestResources', 'sourcesJar', 'javadoc'] +}.configureEach { + dependsOn tasks.named('openApiGenerate') +} diff --git a/sdk/java-resttemplate/openapi-overlay.yaml b/sdk/java-resttemplate/openapi-overlay.yaml new file mode 100644 index 0000000..78c1fa6 --- /dev/null +++ b/sdk/java-resttemplate/openapi-overlay.yaml @@ -0,0 +1,52 @@ +overlay: 1.0.0 +info: + title: Java one-of interface support + version: 1.0.0 +actions: + - target: "$['info']" + update: + x-getter: true + x-implements: true + x-is-one-of-interface: true + # Inheritance is a generator capability, not part of the contract: the Java generator can + # extend a shared base, so the discriminator keeps its enum type instead of degrading to String. + - target: "$['components']['schemas']['BreakTimeBase']" + update: + x-parent: true + - target: "$['components']['schemas']['BreakTime']" + update: + x-is-one-of-interface: true + - target: "$['components']['schemas']['BreakTimeUpdate']" + update: + x-is-one-of-interface: true + - target: "$['components']['schemas']['BreakTimeManual']" + update: + x-implements: + - BreakTime + - BreakTimeUpdate + - target: "$['components']['schemas']['BreakTimeOngoing']" + update: + x-implements: + - BreakTime + - BreakTimeUpdate + - target: "$['components']['schemas']['BreakTimeAutomatic']" + update: + x-implements: + - BreakTime + # VacationAccount is the same oneOf + discriminator shape as BreakTime and needs the same + # treatment, otherwise the generator collapses it into one flat class carrying both variants' + # fields. + - target: "$['components']['schemas']['VacationAccountBase']" + update: + x-parent: true + - target: "$['components']['schemas']['VacationAccount']" + update: + x-is-one-of-interface: true + - target: "$['components']['schemas']['VacationAccountDays']" + update: + x-implements: + - VacationAccount + - target: "$['components']['schemas']['VacationAccountMinutes']" + update: + x-implements: + - VacationAccount diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/ApiClient.java b/sdk/java-resttemplate/src/main/java/com/timr/api/ApiClient.java new file mode 100644 index 0000000..70961c6 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/ApiClient.java @@ -0,0 +1,655 @@ +/* + * timr API + * timr API for time tracking + * + * The version of the OpenAPI document: 0.2.20 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.InvalidMediaTypeException; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.RequestEntity.BodyBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.web.util.DefaultUriBuilderFactory; +import org.openapitools.jackson.nullable.JsonNullableJackson3Module; +import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.cfg.DateTimeFeature; +import tools.jackson.databind.json.JsonMapper; + + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Map.Entry; +import java.util.TimeZone; +import java.util.function.Supplier; +import java.time.OffsetDateTime; + +import com.timr.api.auth.OAuth; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.ApiClient") +public class ApiClient extends JavaTimeFormatter { + public enum CollectionFormat { + CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null); + + protected final String separator; + + CollectionFormat(String separator) { + this.separator = separator; + } + + protected String collectionToString(Collection collection) { + return StringUtils.collectionToDelimitedString(collection, separator); + } + } + + protected HttpHeaders defaultHeaders = new HttpHeaders(); + protected MultiValueMap defaultCookies = new LinkedMultiValueMap(); + + protected String basePath = "https://api.timr.com/v1"; + + private final RestTemplate restTemplate; + + /** + * The credential sent with every request. The contract defines a single OAuth2 security + * scheme, so there is one credential rather than a registry keyed by scheme name. + * Obtaining and refreshing the token is the caller's business; this client only carries it. + */ + private OAuth authentication = new OAuth(); + + protected DateFormat dateFormat; + + public ApiClient() { + this(new RestTemplate()); + } + + @Autowired + public ApiClient(RestTemplate restTemplate) { + this.dateFormat = createDefaultDateFormat(); + this.restTemplate = configureRestTemplate(restTemplate, createDefaultMapper(this.dateFormat)); + init(); + } + + protected void init() { + // Set default User-Agent. + setUserAgent("OpenAPI-Generator/0.2.20/java"); + + } + + /** + * Create the default RFC3339 date format (UTC) used by the timr API. + * @return DateFormat the default date format + */ + public static DateFormat createDefaultDateFormat() { + // Use RFC3339 format for date and datetime, see + // http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + DateFormat dateFormat = new RFC3339DateFormat(); + // Use UTC as the default time zone. + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + return dateFormat; + } + + /** + * Create the default Jackson mapper used for JSON (de)serialization. + * @param dateFormat the date format to apply + * @return JsonMapper the configured mapper + */ + static JsonMapper createDefaultMapper(DateFormat dateFormat) { + return JsonMapper.builder() + .defaultDateFormat(dateFormat) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(DateTimeFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, + DateTimeFeature.WRITE_DATES_WITH_CONTEXT_TIME_ZONE) + .addModule(new JsonNullableJackson3Module()) + .addModule(new RFC3339JavaTimeModule()) + .build(); + } + + /** + * Get the current base path + * + * @return String the base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set the base path, which should include the host + * + * @param basePath the base path + * @return ApiClient this client + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * The credential sent with every request, for setting the access token on it. + * + * @return the current authentication + */ + public OAuth getAuthentication() { + return authentication; + } + + /** + * Replaces the credential sent with every request, for a caller that supplies its own — + * one backed by a token supplier that refreshes, for instance. + * + * @param authentication the authentication to use + */ + public void setAuthentication(OAuth authentication) { + this.authentication = Objects.requireNonNull(authentication, "authentication"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent the user agent string + * @return ApiClient this client + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param name The header's name + * @param value The header's value + * @return ApiClient this client + */ + public ApiClient addDefaultHeader(String name, String value) { + defaultHeaders.set(name, value); + return this; + } + + /** + * Add a default cookie. + * + * @param name The cookie's name + * @param value The cookie's value + * @return ApiClient this client + */ + public ApiClient addDefaultCookie(String name, String value) { + if (defaultCookies.containsKey(name)) { + defaultCookies.remove(name); + } + defaultCookies.add(name, value); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + * @return DateFormat format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + return this; + } + + /** + * Parse the given string into Date object. + * + * @param str the string to parse + * @return the Date parsed from the string + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + * + * @param date the date to format + * @return the formatted date as string + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * + * @param param the object to convert + * @return String the parameter represented as a String + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate( (Date) param); + } else if (param instanceof OffsetDateTime) { + return formatOffsetDateTime((OffsetDateTime) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection) param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param values The values of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(CollectionFormat collectionFormat, Collection values) { + // create the value based on the collection format + if (CollectionFormat.MULTI.equals(collectionFormat)) { + // not valid for path params + return parameterToString(values); + } + + // collectionFormat is assumed to be "csv" by default + if (collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + return collectionFormat.collectionToString(values); + } + + /** + * Converts a parameter to a {@link MultiValueMap} for use in REST requests + * + * @param collectionFormat The format to convert to + * @param name The name of the parameter + * @param value The parameter's value + * @return a Map containing the String value(s) of the input parameter + */ + public MultiValueMap parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) { + final MultiValueMap params = new LinkedMultiValueMap(); + + if (name == null || name.isEmpty() || value == null) { + return params; + } + + if (collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + if (value instanceof Map) { + @SuppressWarnings("unchecked") + final Map valuesMap = (Map) value; + for (final Entry entry : valuesMap.entrySet()) { + params.add(entry.getKey(), parameterToString(entry.getValue())); + } + return params; + } + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(name, parameterToString(value)); + return params; + } + + if (valueCollection.isEmpty()) { + return params; + } + + if (collectionFormat.equals(CollectionFormat.MULTI)) { + for (Object item : valueCollection) { + params.add(name, parameterToString(item)); + } + return params; + } + + List values = new ArrayList(); + for (Object o : valueCollection) { + values.add(parameterToString(o)); + } + params.add(name, collectionFormat.collectionToString(values)); + + return params; + } + + /** + * Check if the given {@code String} is a JSON MIME. + * + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(String mediaType) { + // "* / *" is default to JSON + if ("*/*".equals(mediaType)) { + return true; + } + + try { + return isJsonMime(MediaType.parseMediaType(mediaType)); + } catch (InvalidMediaTypeException e) { + } + return false; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(MediaType mediaType) { + return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); + } + + /** + * Check if the given {@code String} is a Problem JSON MIME (RFC-7807). + * + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents Problem JSON, false otherwise + */ + public boolean isProblemJsonMime(String mediaType) { + return "application/problem+json".equalsIgnoreCase(mediaType); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return List The list of MediaTypes to use for the Accept header + */ + public List selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + MediaType mediaType = MediaType.parseMediaType(accept); + if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) { + return Collections.singletonList(mediaType); + } + } + return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts)); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return MediaType The Content-Type header to use. If the given array is empty, JSON will be used. + */ + public MediaType selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return MediaType.APPLICATION_JSON; + } + for (String contentType : contentTypes) { + MediaType mediaType = MediaType.parseMediaType(contentType); + if (isJsonMime(mediaType)) { + return mediaType; + } + } + return MediaType.parseMediaType(contentTypes[0]); + } + + /** + * Select the body to use for the request + * + * @param obj the body object + * @param formParams the form parameters + * @param contentType the content type of the request + * @return Object the selected body + */ + protected Object selectBody(Object obj, MultiValueMap formParams, MediaType contentType) { + boolean isForm = MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType); + return isForm ? formParams : obj; + } + + /** + * Expand path template with variables + * + * @param pathTemplate path template with placeholders + * @param variables variables to replace + * @return path with placeholders replaced by variables + */ + public String expandPath(String pathTemplate, Map variables) { + return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString(); + } + + /** + * Include queryParams in uriParams taking into account the paramName + * + * @param queryParams The query parameters + * @param uriParams The path parameters + * return templatized query string + */ + public String generateQueryUri(MultiValueMap queryParams, Map uriParams) { + StringBuilder queryBuilder = new StringBuilder(); + queryParams.forEach((name, values) -> { + try { + final String encodedName = URLEncoder.encode(name.toString(), "UTF-8"); + if (CollectionUtils.isEmpty(values)) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(encodedName); + } else { + int valueItemCounter = 0; + for (Object value : values) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(encodedName); + if (value != null) { + String templatizedKey = encodedName + valueItemCounter++; + uriParams.put(templatizedKey, value.toString()); + queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + } + } + } + } catch (UnsupportedEncodingException e) { + + } + }); + return queryBuilder.toString(); + + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param the return type to use + * @param path The sub-path of the HTTP URL + * @param method The request method + * @param pathParams The path parameters + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return ResponseEntity<T> The response of the chosen type + */ + public ResponseEntity invokeAPI(String path, HttpMethod method, Map pathParams, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap cookieParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames, ParameterizedTypeReference returnType) throws RestClientException { + updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); + + Map uriParams = new HashMap<>(); + uriParams.putAll(pathParams); + + String finalUri = path; + + if (queryParams != null && !queryParams.isEmpty()) { + //Include queryParams in uriParams taking into account the paramName + String queryUri = generateQueryUri(queryParams, uriParams); + //Append to finalUri the templatized query string like "?param1={param1Value}&....... + finalUri += "?" + queryUri; + } + String expandedPath = this.expandPath(finalUri, uriParams); + final UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(basePath).path(expandedPath); + + URI uri; + try { + uri = new URI(builder.build().toUriString()); + } catch (URISyntaxException ex) { + throw new RestClientException("Could not build URL: " + builder.toUriString(), ex); + } + + final BodyBuilder requestBuilder = RequestEntity.method(method, UriComponentsBuilder.fromUriString(basePath).toUriString() + finalUri, uriParams); + if (accept != null) { + requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); + } + if (contentType != null) { + requestBuilder.contentType(contentType); + } + + addHeadersToRequest(headerParams, requestBuilder); + addHeadersToRequest(defaultHeaders, requestBuilder); + addCookiesToRequest(cookieParams, requestBuilder); + addCookiesToRequest(defaultCookies, requestBuilder); + + RequestEntity requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); + + ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + return responseEntity; + } else { + // The error handler built into the RestTemplate should handle 400 and 500 series errors. + throw new RestClientException("API returned " + responseEntity.getStatusCode() + " and it wasn't handled by the RestTemplate error handler"); + } + } + + /** + * Add headers to the request that is being built + * @param headers The headers to add + * @param requestBuilder The current request + */ + protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) { + for (Entry> entry : headers.headerSet()) { + List values = entry.getValue(); + for (String value : values) { + if (value != null) { + requestBuilder.header(entry.getKey(), value); + } + } + } + } + + /** + * Add cookies to the request that is being built + * + * @param cookies The cookies to add + * @param requestBuilder The current request + */ + protected void addCookiesToRequest(MultiValueMap cookies, BodyBuilder requestBuilder) { + if (!cookies.isEmpty()) { + requestBuilder.header("Cookie", buildCookieHeader(cookies)); + } + } + + /** + * Build cookie header. Keeps a single value per cookie (as per + * RFC6265 section 5.3). + * + * @param cookies map all cookies + * @return header string for cookies. + */ + protected String buildCookieHeader(MultiValueMap cookies) { + final StringBuilder cookieValue = new StringBuilder(); + String delimiter = ""; + for (final Map.Entry> entry : cookies.entrySet()) { + final String value = entry.getValue().get(entry.getValue().size() - 1); + cookieValue.append(String.format(java.util.Locale.ROOT, "%s%s=%s", delimiter, entry.getKey(), value)); + delimiter = "; "; + } + return cookieValue.toString(); + } + + /** + * Apply timr's Jackson 3 converter and URL encoding to the given RestTemplate. + * Used for both the default and the injected transport so offset preservation + * and query encoding behave identically regardless of how the client is constructed. + * @return RestTemplate + */ + private static RestTemplate configureRestTemplate(RestTemplate restTemplate, JsonMapper mapper) { + restTemplate.getMessageConverters().add(0, new JacksonJsonHttpMessageConverter(mapper)); + + // disable default URL encoding + DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(); + uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY); + restTemplate.setUriTemplateHandler(uriBuilderFactory); + return restTemplate; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams The query parameters + * @param headerParams The header parameters + */ + protected void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + // authNames is the generated call site telling us which schemes the operation declares. + // The contract declares exactly one, so the single credential applies to every request. + authentication.applyToParams(queryParams, headerParams, cookieParams); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/BaseApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/BaseApi.java new file mode 100644 index 0000000..363e44c --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/BaseApi.java @@ -0,0 +1,87 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api; + +import org.springframework.web.client.RestClientException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public abstract class BaseApi { + + protected ApiClient apiClient; + + public BaseApi() { + this(new ApiClient()); + } + + public BaseApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Directly invoke the API for the given URL. Useful if the API returns direct links/URLs for subsequent requests. + * @param url The URL for the request, either full URL or only the path. + * @param method The HTTP method for the request. + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity invokeAPI(String url, HttpMethod method) throws RestClientException { + return invokeAPI(url, method, null, new ParameterizedTypeReference() {}); + } + + /** + * Directly invoke the API for the given URL. Useful if the API returns direct links/URLs for subsequent requests. + * @param url The URL for the request, either full URL or only the path. + * @param method The HTTP method for the request. + * @param request The request object. + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request) throws RestClientException { + return invokeAPI(url, method, request, new ParameterizedTypeReference() {}); + } + + /** + * Directly invoke the API for the given URL. Useful if the API returns direct links/URLs for subsequent requests. + * @param url The URL for the request, either full URL or only the path. + * @param method The HTTP method for the request. + * @param returnType The return type. + * @return ResponseEntity in the specified type. + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity invokeAPI(String url, HttpMethod method, ParameterizedTypeReference returnType) throws RestClientException { + return invokeAPI(url, method, null, returnType); + } + + /** + * Directly invoke the API for the given URL. Useful if the API returns direct links/URLs for subsequent requests. + * @param url The URL for the request, either full URL or only the path. + * @param method The HTTP method for the request. + * @param request The request object. + * @param returnType The return type. + * @return ResponseEntity in the specified type. + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public abstract ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException; +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/JavaTimeFormatter.java b/sdk/java-resttemplate/src/main/java/com/timr/api/JavaTimeFormatter.java new file mode 100644 index 0000000..904acae --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/JavaTimeFormatter.java @@ -0,0 +1,68 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.timr.api; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class JavaTimeFormatter { + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given {@code OffsetDateTime} object into string. + * + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} \ No newline at end of file diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/RFC3339DateFormat.java b/sdk/java-resttemplate/src/main/java/com/timr/api/RFC3339DateFormat.java new file mode 100644 index 0000000..2d53335 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/RFC3339DateFormat.java @@ -0,0 +1,57 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.timr.api; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.text.DecimalFormat; +import java.util.GregorianCalendar; +import java.util.TimeZone; +import tools.jackson.databind.util.StdDateFormat; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + this.numberFormat = new DecimalFormat(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return super.clone(); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/RFC3339InstantDeserializer.java b/sdk/java-resttemplate/src/main/java/com/timr/api/RFC3339InstantDeserializer.java new file mode 100644 index 0000000..b3c934a --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/RFC3339InstantDeserializer.java @@ -0,0 +1,100 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.timr.api; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.Temporal; +import java.time.temporal.TemporalAccessor; +import java.util.function.BiFunction; +import java.util.function.Function; + +import tools.jackson.core.JacksonException; +import tools.jackson.core.JsonParser; +import tools.jackson.databind.DeserializationContext; +import tools.jackson.databind.cfg.DateTimeFeature; +import tools.jackson.databind.ext.javatime.deser.InstantDeserializer; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class RFC3339InstantDeserializer extends InstantDeserializer { + private static final long serialVersionUID = 1L; + private final static boolean DEFAULT_NORMALIZE_ZONE_ID = DateTimeFeature.NORMALIZE_DESERIALIZED_ZONE_ID.enabledByDefault(); + private final static boolean DEFAULT_ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS + = DateTimeFeature.ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS.enabledByDefault(); + + public static final RFC3339InstantDeserializer INSTANT = new RFC3339InstantDeserializer<>( + Instant.class, DateTimeFormatter.ISO_INSTANT, + Instant::from, + a -> Instant.ofEpochMilli( a.value ), + a -> Instant.ofEpochSecond( a.integer, a.fraction ), + null, + true, // yes, replace zero offset with Z + DEFAULT_NORMALIZE_ZONE_ID, + DEFAULT_ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS + ); + + public static final RFC3339InstantDeserializer OFFSET_DATE_TIME = new RFC3339InstantDeserializer<>( + OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, + OffsetDateTime::from, + a -> OffsetDateTime.ofInstant( Instant.ofEpochMilli( a.value ), a.zoneId ), + a -> OffsetDateTime.ofInstant( Instant.ofEpochSecond( a.integer, a.fraction ), a.zoneId ), + (d, z) -> ( d.isEqual( OffsetDateTime.MIN ) || d.isEqual( OffsetDateTime.MAX ) ? + d : + d.withOffsetSameInstant( z.getRules().getOffset( d.toLocalDateTime() ) ) ), + true, // yes, replace zero offset with Z + DEFAULT_NORMALIZE_ZONE_ID, + DEFAULT_ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS + ); + + public static final RFC3339InstantDeserializer ZONED_DATE_TIME = new RFC3339InstantDeserializer<>( + ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, + ZonedDateTime::from, + a -> ZonedDateTime.ofInstant( Instant.ofEpochMilli( a.value ), a.zoneId ), + a -> ZonedDateTime.ofInstant( Instant.ofEpochSecond( a.integer, a.fraction ), a.zoneId ), + ZonedDateTime::withZoneSameInstant, + false, // keep zero offset and Z separate since zones explicitly supported + DEFAULT_NORMALIZE_ZONE_ID, + DEFAULT_ALWAYS_ALLOW_STRINGIFIED_DATE_TIMESTAMPS + ); + + protected RFC3339InstantDeserializer( + Class supportedType, + DateTimeFormatter formatter, + Function parsedToValue, + Function fromMilliseconds, + Function fromNanoseconds, + BiFunction adjust, + boolean replaceZeroOffsetAsZ, + boolean normalizeZoneId, + boolean readNumericStringsAsTimestamp) { + super( + supportedType, + formatter, + parsedToValue, + fromMilliseconds, + fromNanoseconds, + adjust, + replaceZeroOffsetAsZ, + normalizeZoneId, + readNumericStringsAsTimestamp + ); + } + + @Override + protected T _fromString(JsonParser p, DeserializationContext ctxt, String string0) throws JacksonException { + return super._fromString(p, ctxt, string0.replace( ' ', 'T' )); + } +} \ No newline at end of file diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/RFC3339JavaTimeModule.java b/sdk/java-resttemplate/src/main/java/com/timr/api/RFC3339JavaTimeModule.java new file mode 100644 index 0000000..608948d --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/RFC3339JavaTimeModule.java @@ -0,0 +1,33 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.timr.api; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZonedDateTime; + +import tools.jackson.databind.module.SimpleModule; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class RFC3339JavaTimeModule extends SimpleModule { + private static final long serialVersionUID = 1L; + + public RFC3339JavaTimeModule() { + super("RFC3339JavaTimeModule"); + addDeserializer(Instant.class, RFC3339InstantDeserializer.INSTANT); + addDeserializer(OffsetDateTime.class, RFC3339InstantDeserializer.OFFSET_DATE_TIME); + addDeserializer(ZonedDateTime.class, RFC3339InstantDeserializer.ZONED_DATE_TIME); + } + + +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/ServerConfiguration.java b/sdk/java-resttemplate/src/main/java/com/timr/api/ServerConfiguration.java new file mode 100644 index 0000000..801f285 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/ServerConfiguration.java @@ -0,0 +1,72 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replace("{" + name + "}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/ServerVariable.java b/sdk/java-resttemplate/src/main/java/com/timr/api/ServerVariable.java new file mode 100644 index 0000000..73638a0 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/ServerVariable.java @@ -0,0 +1,37 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/CarApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/CarApi.java new file mode 100644 index 0000000..9182c58 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/CarApi.java @@ -0,0 +1,312 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Car; +import com.timr.api.models.CarCreate; +import com.timr.api.models.CarUpdate; +import com.timr.api.models.CarsPage; +import com.timr.api.models.CarsSortColumn; +import com.timr.api.models.Error; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.CarApi") +public class CarApi extends BaseApi { + + public CarApi() { + super(new ApiClient()); + } + + @Autowired + public CarApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a Car + * Creates a Car from the data in the request body. + *

201 - The created Car. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param carCreate Car entity (required) + * @return Car + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Car createCar(CarCreate carCreate) throws RestClientException { + return createCarWithHttpInfo(carCreate).getBody(); + } + + /** + * Create a Car + * Creates a Car from the data in the request body. + *

201 - The created Car. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param carCreate Car entity (required) + * @return ResponseEntity<Car> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createCarWithHttpInfo(CarCreate carCreate) throws RestClientException { + Object localVarPostBody = carCreate; + + // verify the required parameter 'carCreate' is set + if (carCreate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'carCreate' when calling createCar"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/cars", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Cars + * Lists the Cars the authenticated user or API token can access. + *

200 - Page of Cars. + *

400 - Bad Request + * @param nameOrPlate Only return Cars whose name or plate contains this text. (optional) + * @param usable Only return Cars that are usable (true) or not usable (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return CarsPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public CarsPage fetchCars(String nameOrPlate, Boolean usable, String pageToken, Integer limit, SortDirection sortDirection, CarsSortColumn sortBy) throws RestClientException { + return fetchCarsWithHttpInfo(nameOrPlate, usable, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Cars + * Lists the Cars the authenticated user or API token can access. + *

200 - Page of Cars. + *

400 - Bad Request + * @param nameOrPlate Only return Cars whose name or plate contains this text. (optional) + * @param usable Only return Cars that are usable (true) or not usable (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return ResponseEntity<CarsPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchCarsWithHttpInfo(String nameOrPlate, Boolean usable, String pageToken, Integer limit, SortDirection sortDirection, CarsSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "name_or_plate", nameOrPlate)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "usable", usable)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/cars", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Car + * Returns a single Car by its ID. + *

200 - The requested Car. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Car. (required) + * @return Car + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Car getCar(String id) throws RestClientException { + return getCarWithHttpInfo(id).getBody(); + } + + /** + * Get a Car + * Returns a single Car by its ID. + *

200 - The requested Car. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Car. (required) + * @return ResponseEntity<Car> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getCarWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getCar"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/cars/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Update a Car + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Car. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Car. (required) + * @param carUpdate Car entity (required) + * @return Car + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Car updateCar(String id, CarUpdate carUpdate) throws RestClientException { + return updateCarWithHttpInfo(id, carUpdate).getBody(); + } + + /** + * Update a Car + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Car. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Car. (required) + * @param carUpdate Car entity (required) + * @return ResponseEntity<Car> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateCarWithHttpInfo(String id, CarUpdate carUpdate) throws RestClientException { + Object localVarPostBody = carUpdate; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling updateCar"); + } + + // verify the required parameter 'carUpdate' is set + if (carUpdate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'carUpdate' when calling updateCar"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/cars/{id}", HttpMethod.PATCH, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/DriveLogApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/DriveLogApi.java new file mode 100644 index 0000000..938dfa4 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/DriveLogApi.java @@ -0,0 +1,451 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.DeletedEntryPage; +import com.timr.api.models.DeletedEntrySortColumn; +import com.timr.api.models.DriveLog; +import com.timr.api.models.DriveLogCreate; +import com.timr.api.models.DriveLogStatus; +import com.timr.api.models.DriveLogUpdate; +import com.timr.api.models.DriveLogsPage; +import com.timr.api.models.DriveLogsSortColumn; +import com.timr.api.models.Error; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.DriveLogApi") +public class DriveLogApi extends BaseApi { + + public DriveLogApi() { + super(new ApiClient()); + } + + @Autowired + public DriveLogApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a Drive Log + * Creates a Drive Log from the data in the request body. + *

201 - The created Drive Log. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param driveLogCreate Drive Log entity (required) + * @return DriveLog + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DriveLog createDriveLog(DriveLogCreate driveLogCreate) throws RestClientException { + return createDriveLogWithHttpInfo(driveLogCreate).getBody(); + } + + /** + * Create a Drive Log + * Creates a Drive Log from the data in the request body. + *

201 - The created Drive Log. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param driveLogCreate Drive Log entity (required) + * @return ResponseEntity<DriveLog> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createDriveLogWithHttpInfo(DriveLogCreate driveLogCreate) throws RestClientException { + Object localVarPostBody = driveLogCreate; + + // verify the required parameter 'driveLogCreate' is set + if (driveLogCreate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'driveLogCreate' when calling createDriveLog"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/drive-logs", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Delete a Drive Log + * Deletes the Drive Log, including its Track. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Drive Log. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteDriveLog(String id) throws RestClientException { + deleteDriveLogWithHttpInfo(id); + } + + /** + * Delete a Drive Log + * Deletes the Drive Log, including its Track. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Drive Log. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteDriveLogWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling deleteDriveLog"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/drive-logs/{id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List deleted Drive Logs + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Drive Logs. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to last_modified) + * @return DeletedEntryPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DeletedEntryPage fetchDeletedDriveLogs(OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientException { + return fetchDeletedDriveLogsWithHttpInfo(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List deleted Drive Logs + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Drive Logs. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to last_modified) + * @return ResponseEntity<DeletedEntryPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDeletedDriveLogsWithHttpInfo(OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/drive-logs:deleted", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Drive Logs + * Lists the Drive Logs the authenticated user or API token can access. + *

200 - Page of Drive Logs. + *

400 - Bad Request + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param cars Only return entries recorded for these Cars. (optional) + * @param driveLogCategories Only return entries in these Drive Log Categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param details Only return Drive Logs whose route, purpose or visited contains this text. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param hasTrack Only return Drive Logs that have a Track (true) or have none (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to start) + * @return DriveLogsPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DriveLogsPage fetchDriveLogs(LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, List cars, List driveLogCategories, List statuses, List users, String details, Boolean changed, Boolean hasTrack, String pageToken, Integer limit, SortDirection sortDirection, DriveLogsSortColumn sortBy) throws RestClientException { + return fetchDriveLogsWithHttpInfo(startFrom, startTo, lastModifiedAfter, cars, driveLogCategories, statuses, users, details, changed, hasTrack, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Drive Logs + * Lists the Drive Logs the authenticated user or API token can access. + *

200 - Page of Drive Logs. + *

400 - Bad Request + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param cars Only return entries recorded for these Cars. (optional) + * @param driveLogCategories Only return entries in these Drive Log Categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param details Only return Drive Logs whose route, purpose or visited contains this text. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param hasTrack Only return Drive Logs that have a Track (true) or have none (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to start) + * @return ResponseEntity<DriveLogsPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDriveLogsWithHttpInfo(LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, List cars, List driveLogCategories, List statuses, List users, String details, Boolean changed, Boolean hasTrack, String pageToken, Integer limit, SortDirection sortDirection, DriveLogsSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_from", startFrom)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_to", startTo)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "cars", cars)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "drive_log_categories", driveLogCategories)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "statuses", statuses)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "users", users)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "details", details)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "changed", changed)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "has_track", hasTrack)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/drive-logs", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Drive Log + * Returns a single Drive Log by its ID. + *

200 - The requested Drive Log. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log. (required) + * @return DriveLog + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DriveLog getDriveLog(String id) throws RestClientException { + return getDriveLogWithHttpInfo(id).getBody(); + } + + /** + * Get a Drive Log + * Returns a single Drive Log by its ID. + *

200 - The requested Drive Log. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log. (required) + * @return ResponseEntity<DriveLog> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getDriveLogWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getDriveLog"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/drive-logs/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Update a Drive Log + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Drive Log. (required) + * @param driveLogUpdate Drive Log entity (required) + * @return DriveLog + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DriveLog updateDriveLog(String id, DriveLogUpdate driveLogUpdate) throws RestClientException { + return updateDriveLogWithHttpInfo(id, driveLogUpdate).getBody(); + } + + /** + * Update a Drive Log + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Drive Log. (required) + * @param driveLogUpdate Drive Log entity (required) + * @return ResponseEntity<DriveLog> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateDriveLogWithHttpInfo(String id, DriveLogUpdate driveLogUpdate) throws RestClientException { + Object localVarPostBody = driveLogUpdate; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling updateDriveLog"); + } + + // verify the required parameter 'driveLogUpdate' is set + if (driveLogUpdate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'driveLogUpdate' when calling updateDriveLog"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/drive-logs/{id}", HttpMethod.PATCH, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/DriveLogCategoryApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/DriveLogCategoryApi.java new file mode 100644 index 0000000..2765387 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/DriveLogCategoryApi.java @@ -0,0 +1,178 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.DriveLogCategoriesPage; +import com.timr.api.models.DriveLogCategoriesSortColumn; +import com.timr.api.models.DriveLogCategory; +import com.timr.api.models.Error; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.DriveLogCategoryApi") +public class DriveLogCategoryApi extends BaseApi { + + public DriveLogCategoryApi() { + super(new ApiClient()); + } + + @Autowired + public DriveLogCategoryApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * List Drive Log Categories + * Lists the Drive Log Categories the authenticated user or API token can access. + *

200 - Page of Drive Log Categories. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return DriveLogCategoriesPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DriveLogCategoriesPage fetchDriveLogCategories(String pageToken, Integer limit, SortDirection sortDirection, DriveLogCategoriesSortColumn sortBy) throws RestClientException { + return fetchDriveLogCategoriesWithHttpInfo(pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Drive Log Categories + * Lists the Drive Log Categories the authenticated user or API token can access. + *

200 - Page of Drive Log Categories. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return ResponseEntity<DriveLogCategoriesPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDriveLogCategoriesWithHttpInfo(String pageToken, Integer limit, SortDirection sortDirection, DriveLogCategoriesSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/drive-log-categories", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Drive Log Category + * Returns a single Drive Log Category by its ID. + *

200 - The requested Drive Log Category. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log Category. (required) + * @return DriveLogCategory + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DriveLogCategory getDriveLogCategory(String id) throws RestClientException { + return getDriveLogCategoryWithHttpInfo(id).getBody(); + } + + /** + * Get a Drive Log Category + * Returns a single Drive Log Category by its ID. + *

200 - The requested Drive Log Category. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Drive Log Category. (required) + * @return ResponseEntity<DriveLogCategory> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getDriveLogCategoryWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getDriveLogCategory"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/drive-log-categories/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/HolidayCalendarApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/HolidayCalendarApi.java new file mode 100644 index 0000000..1c48f81 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/HolidayCalendarApi.java @@ -0,0 +1,249 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Error; +import com.timr.api.models.HolidayCalendarPartial; +import com.timr.api.models.HolidayCalendarsPage; +import com.timr.api.models.HolidayCalendarsSortColumn; +import com.timr.api.models.HolidaysPage; +import com.timr.api.models.HolidaysSortColumn; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.HolidayCalendarApi") +public class HolidayCalendarApi extends BaseApi { + + public HolidayCalendarApi() { + super(new ApiClient()); + } + + @Autowired + public HolidayCalendarApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * List Holiday Calendars + * Lists the Holiday Calendars the authenticated user or API token can access. + *

200 - Page of Holiday Calendars. + *

403 - Forbidden + *

404 - Not Found + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to description) + * @return HolidayCalendarsPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public HolidayCalendarsPage fetchHolidayCalendars(String pageToken, Integer limit, SortDirection sortDirection, HolidayCalendarsSortColumn sortBy) throws RestClientException { + return fetchHolidayCalendarsWithHttpInfo(pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Holiday Calendars + * Lists the Holiday Calendars the authenticated user or API token can access. + *

200 - Page of Holiday Calendars. + *

403 - Forbidden + *

404 - Not Found + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to description) + * @return ResponseEntity<HolidayCalendarsPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchHolidayCalendarsWithHttpInfo(String pageToken, Integer limit, SortDirection sortDirection, HolidayCalendarsSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/holiday-calendars", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Holidays + * Lists the Holidays in the Holiday Calendar. + *

200 - Page of Holidays in the Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to date) + * @return HolidaysPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public HolidaysPage fetchHolidays(String id, String pageToken, Integer limit, SortDirection sortDirection, HolidaysSortColumn sortBy) throws RestClientException { + return fetchHolidaysWithHttpInfo(id, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Holidays + * Lists the Holidays in the Holiday Calendar. + *

200 - Page of Holidays in the Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to date) + * @return ResponseEntity<HolidaysPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchHolidaysWithHttpInfo(String id, String pageToken, Integer limit, SortDirection sortDirection, HolidaysSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling fetchHolidays"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/holiday-calendars/{id}/holidays", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Holiday Calendar + * Returns a single Holiday Calendar by its ID. + *

200 - The requested Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. (required) + * @return HolidayCalendarPartial + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public HolidayCalendarPartial getHolidayCalendar(String id) throws RestClientException { + return getHolidayCalendarWithHttpInfo(id).getBody(); + } + + /** + * Get a Holiday Calendar + * Returns a single Holiday Calendar by its ID. + *

200 - The requested Holiday Calendar. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Holiday Calendar. (required) + * @return ResponseEntity<HolidayCalendarPartial> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getHolidayCalendarWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getHolidayCalendar"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/holiday-calendars/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/ProjectTimeApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/ProjectTimeApi.java new file mode 100644 index 0000000..4f98940 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/ProjectTimeApi.java @@ -0,0 +1,451 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.DeletedEntrySortColumn; +import com.timr.api.models.DeletedEntryWithMetadataPage; +import com.timr.api.models.Error; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import com.timr.api.models.ProjectTime; +import com.timr.api.models.ProjectTimeCreate; +import com.timr.api.models.ProjectTimeStatus; +import com.timr.api.models.ProjectTimeUpdate; +import com.timr.api.models.ProjectTimesPage; +import com.timr.api.models.ProjectTimesSortColumn; +import com.timr.api.models.SortDirection; +import java.net.URI; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.ProjectTimeApi") +public class ProjectTimeApi extends BaseApi { + + public ProjectTimeApi() { + super(new ApiClient()); + } + + @Autowired + public ProjectTimeApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a Project Time + * Creates a Project Time from the data in the request body. + *

201 - The created Project Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param projectTimeCreate Project Time entity (required) + * @return ProjectTime + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ProjectTime createProjectTime(ProjectTimeCreate projectTimeCreate) throws RestClientException { + return createProjectTimeWithHttpInfo(projectTimeCreate).getBody(); + } + + /** + * Create a Project Time + * Creates a Project Time from the data in the request body. + *

201 - The created Project Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param projectTimeCreate Project Time entity (required) + * @return ResponseEntity<ProjectTime> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createProjectTimeWithHttpInfo(ProjectTimeCreate projectTimeCreate) throws RestClientException { + Object localVarPostBody = projectTimeCreate; + + // verify the required parameter 'projectTimeCreate' is set + if (projectTimeCreate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'projectTimeCreate' when calling createProjectTime"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/project-times", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Delete a Project Time + * Deletes the Project Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Project Time. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteProjectTime(String id) throws RestClientException { + deleteProjectTimeWithHttpInfo(id); + } + + /** + * Delete a Project Time + * Deletes the Project Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Project Time. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteProjectTimeWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling deleteProjectTime"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/project-times/{id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List deleted Project Times + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Project Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to last_modified) + * @return DeletedEntryWithMetadataPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DeletedEntryWithMetadataPage fetchDeletedProjectTimes(OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientException { + return fetchDeletedProjectTimesWithHttpInfo(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List deleted Project Times + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Project Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to last_modified) + * @return ResponseEntity<DeletedEntryWithMetadataPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDeletedProjectTimesWithHttpInfo(OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/project-times:deleted", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Project Times + * Lists the Project Times the authenticated user or API token can access. + *

200 - Page of Project Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param task Only return entries recorded on the Task with this ID. (optional) + * @param traverseTaskTree Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to start) + * @return ProjectTimesPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ProjectTimesPage fetchProjectTimes(String notes, LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, String task, Boolean traverseTaskTree, Boolean billable, List statuses, List users, Boolean changed, String pageToken, Integer limit, SortDirection sortDirection, ProjectTimesSortColumn sortBy) throws RestClientException { + return fetchProjectTimesWithHttpInfo(notes, startFrom, startTo, lastModifiedAfter, task, traverseTaskTree, billable, statuses, users, changed, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Project Times + * Lists the Project Times the authenticated user or API token can access. + *

200 - Page of Project Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param task Only return entries recorded on the Task with this ID. (optional) + * @param traverseTaskTree Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to start) + * @return ResponseEntity<ProjectTimesPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchProjectTimesWithHttpInfo(String notes, LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, String task, Boolean traverseTaskTree, Boolean billable, List statuses, List users, Boolean changed, String pageToken, Integer limit, SortDirection sortDirection, ProjectTimesSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "notes", notes)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_from", startFrom)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_to", startTo)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "task", task)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "traverse_task_tree", traverseTaskTree)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "billable", billable)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "statuses", statuses)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "users", users)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "changed", changed)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/project-times", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Project Time + * Returns a single Project Time by its ID. + *

200 - The requested Project Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Project Time. (required) + * @return ProjectTime + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ProjectTime getProjectTime(String id) throws RestClientException { + return getProjectTimeWithHttpInfo(id).getBody(); + } + + /** + * Get a Project Time + * Returns a single Project Time by its ID. + *

200 - The requested Project Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Project Time. (required) + * @return ResponseEntity<ProjectTime> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getProjectTimeWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getProjectTime"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/project-times/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Update a Project Time + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Project Time. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Project Time. (required) + * @param projectTimeUpdate Project Time entity (required) + * @return ProjectTime + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ProjectTime updateProjectTime(String id, ProjectTimeUpdate projectTimeUpdate) throws RestClientException { + return updateProjectTimeWithHttpInfo(id, projectTimeUpdate).getBody(); + } + + /** + * Update a Project Time + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Project Time. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Project Time. (required) + * @param projectTimeUpdate Project Time entity (required) + * @return ResponseEntity<ProjectTime> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateProjectTimeWithHttpInfo(String id, ProjectTimeUpdate projectTimeUpdate) throws RestClientException { + Object localVarPostBody = projectTimeUpdate; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling updateProjectTime"); + } + + // verify the required parameter 'projectTimeUpdate' is set + if (projectTimeUpdate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'projectTimeUpdate' when calling updateProjectTime"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/project-times/{id}", HttpMethod.PATCH, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskApi.java new file mode 100644 index 0000000..1241a38 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskApi.java @@ -0,0 +1,407 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Error; +import java.time.LocalDate; +import com.timr.api.models.SortDirection; +import com.timr.api.models.Task; +import com.timr.api.models.TaskCreate; +import com.timr.api.models.TaskUpdate; +import com.timr.api.models.TasksPage; +import com.timr.api.models.TasksReducedPage; +import com.timr.api.models.TasksSortColumn; +import java.net.URI; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.TaskApi") +public class TaskApi extends BaseApi { + + public TaskApi() { + super(new ApiClient()); + } + + @Autowired + public TaskApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a Task + * Creates a Task from the data in the request body. + *

201 - The created Task. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskCreate Project Time entity (required) + * @return Task + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Task createTask(TaskCreate taskCreate) throws RestClientException { + return createTaskWithHttpInfo(taskCreate).getBody(); + } + + /** + * Create a Task + * Creates a Task from the data in the request body. + *

201 - The created Task. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskCreate Project Time entity (required) + * @return ResponseEntity<Task> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createTaskWithHttpInfo(TaskCreate taskCreate) throws RestClientException { + Object localVarPostBody = taskCreate; + + // verify the required parameter 'taskCreate' is set + if (taskCreate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskCreate' when calling createTask"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Tasks + * Lists the Tasks the authenticated user or API token can access. + *

200 - Page of Tasks. + *

400 - Bad Request + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return TasksPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TasksPage fetchTasks(String parentTaskId, Boolean traverseTaskTree, String name, Boolean bookable, Boolean billable, LocalDate activeAt, String pageToken, Integer limit, SortDirection sortDirection, TasksSortColumn sortBy) throws RestClientException { + return fetchTasksWithHttpInfo(parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Tasks + * Lists the Tasks the authenticated user or API token can access. + *

200 - Page of Tasks. + *

400 - Bad Request + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return ResponseEntity<TasksPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTasksWithHttpInfo(String parentTaskId, Boolean traverseTaskTree, String name, Boolean bookable, Boolean billable, LocalDate activeAt, String pageToken, Integer limit, SortDirection sortDirection, TasksSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "parent_task_id", parentTaskId)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "traverse_task_tree", traverseTaskTree)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "bookable", bookable)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "billable", billable)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "active_at", activeAt)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List a User's Tasks + * Lists the Tasks the User is assigned to and may record on. + *

200 - Page of Tasks the User is assigned to. + *

400 - Bad Request + * @param id ID of the User. (required) + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return TasksReducedPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TasksReducedPage fetchUserTasks(String id, String parentTaskId, Boolean traverseTaskTree, String name, Boolean bookable, Boolean billable, LocalDate activeAt, String pageToken, Integer limit, SortDirection sortDirection, TasksSortColumn sortBy) throws RestClientException { + return fetchUserTasksWithHttpInfo(id, parentTaskId, traverseTaskTree, name, bookable, billable, activeAt, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List a User's Tasks + * Lists the Tasks the User is assigned to and may record on. + *

200 - Page of Tasks the User is assigned to. + *

400 - Bad Request + * @param id ID of the User. (required) + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return ResponseEntity<TasksReducedPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchUserTasksWithHttpInfo(String id, String parentTaskId, Boolean traverseTaskTree, String name, Boolean bookable, Boolean billable, LocalDate activeAt, String pageToken, Integer limit, SortDirection sortDirection, TasksSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling fetchUserTasks"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "parent_task_id", parentTaskId)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "traverse_task_tree", traverseTaskTree)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "bookable", bookable)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "billable", billable)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "active_at", activeAt)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users/{id}/tasks", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Task + * Returns a single Task by its ID. + *

200 - The requested Task. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Task. (required) + * @return Task + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Task getTask(String id) throws RestClientException { + return getTaskWithHttpInfo(id).getBody(); + } + + /** + * Get a Task + * Returns a single Task by its ID. + *

200 - The requested Task. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Task. (required) + * @return ResponseEntity<Task> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTaskWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getTask"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Update a Task + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Task. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Task. (required) + * @param taskUpdate Task entity (required) + * @return Task + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Task updateTask(String id, TaskUpdate taskUpdate) throws RestClientException { + return updateTaskWithHttpInfo(id, taskUpdate).getBody(); + } + + /** + * Update a Task + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Task. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Task. (required) + * @param taskUpdate Task entity (required) + * @return ResponseEntity<Task> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateTaskWithHttpInfo(String id, TaskUpdate taskUpdate) throws RestClientException { + Object localVarPostBody = taskUpdate; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling updateTask"); + } + + // verify the required parameter 'taskUpdate' is set + if (taskUpdate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskUpdate' when calling updateTask"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{id}", HttpMethod.PATCH, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskToLeaderAssignmentApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskToLeaderAssignmentApi.java new file mode 100644 index 0000000..afead9e --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskToLeaderAssignmentApi.java @@ -0,0 +1,325 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Error; +import com.timr.api.models.SortDirection; +import com.timr.api.models.TaskToLeaderAssignment; +import com.timr.api.models.TaskToLeaderAssignmentsPage; +import com.timr.api.models.TaskToLeaderAssignmentsSortColumn; +import java.net.URI; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.TaskToLeaderAssignmentApi") +public class TaskToLeaderAssignmentApi extends BaseApi { + + public TaskToLeaderAssignmentApi() { + super(new ApiClient()); + } + + @Autowired + public TaskToLeaderAssignmentApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a Task to Leader Assignment + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The Task to Leader Assignment, which already existed. + *

201 - The created Task to Leader Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @return TaskToLeaderAssignment + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TaskToLeaderAssignment createTaskToLeaderAssignment(String taskId, String userId) throws RestClientException { + return createTaskToLeaderAssignmentWithHttpInfo(taskId, userId).getBody(); + } + + /** + * Create a Task to Leader Assignment + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The Task to Leader Assignment, which already existed. + *

201 - The created Task to Leader Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<TaskToLeaderAssignment> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createTaskToLeaderAssignmentWithHttpInfo(String taskId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling createTaskToLeaderAssignment"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling createTaskToLeaderAssignment"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/leaders/{user_id}", HttpMethod.PUT, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Delete a Task to Leader Assignment + * Removes the User's leader assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteTaskToLeaderAssignment(String taskId, String userId) throws RestClientException { + deleteTaskToLeaderAssignmentWithHttpInfo(taskId, userId); + } + + /** + * Delete a Task to Leader Assignment + * Removes the User's leader assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTaskToLeaderAssignmentWithHttpInfo(String taskId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling deleteTaskToLeaderAssignment"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling deleteTaskToLeaderAssignment"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/leaders/{user_id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Task to Leader Assignments + * Lists the Users assigned to the Task as leaders. + *

200 - Page of Task to Leader Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to user_name) + * @return TaskToLeaderAssignmentsPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TaskToLeaderAssignmentsPage fetchTaskToLeaderAssignments(String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToLeaderAssignmentsSortColumn sortBy) throws RestClientException { + return fetchTaskToLeaderAssignmentsWithHttpInfo(taskId, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Task to Leader Assignments + * Lists the Users assigned to the Task as leaders. + *

200 - Page of Task to Leader Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to user_name) + * @return ResponseEntity<TaskToLeaderAssignmentsPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTaskToLeaderAssignmentsWithHttpInfo(String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToLeaderAssignmentsSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling fetchTaskToLeaderAssignments"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/leaders", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Task to Leader Assignment + * Returns the leader assignment of a single User to the Task. + *

200 - The requested Task to Leader Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @return TaskToLeaderAssignment + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TaskToLeaderAssignment getTaskToLeaderAssignment(String taskId, String userId) throws RestClientException { + return getTaskToLeaderAssignmentWithHttpInfo(taskId, userId).getBody(); + } + + /** + * Get a Task to Leader Assignment + * Returns the leader assignment of a single User to the Task. + *

200 - The requested Task to Leader Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<TaskToLeaderAssignment> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTaskToLeaderAssignmentWithHttpInfo(String taskId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling getTaskToLeaderAssignment"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling getTaskToLeaderAssignment"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/leaders/{user_id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskToTeamAssignmentApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskToTeamAssignmentApi.java new file mode 100644 index 0000000..be00a75 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskToTeamAssignmentApi.java @@ -0,0 +1,325 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Error; +import com.timr.api.models.SortDirection; +import com.timr.api.models.TaskToTeamAssignment; +import com.timr.api.models.TaskToTeamAssignmentsPage; +import com.timr.api.models.TaskToTeamAssignmentsSortColumn; +import java.net.URI; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.TaskToTeamAssignmentApi") +public class TaskToTeamAssignmentApi extends BaseApi { + + public TaskToTeamAssignmentApi() { + super(new ApiClient()); + } + + @Autowired + public TaskToTeamAssignmentApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a Task to Team Assignment + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The updated Task to Team Assignment. + *

201 - The created Task to Team Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. (required) + * @param teamId ID of the Team. (required) + * @return TaskToTeamAssignment + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TaskToTeamAssignment createTaskToTeamAssignment(String taskId, String teamId) throws RestClientException { + return createTaskToTeamAssignmentWithHttpInfo(taskId, teamId).getBody(); + } + + /** + * Create a Task to Team Assignment + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + *

200 - The updated Task to Team Assignment. + *

201 - The created Task to Team Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. (required) + * @param teamId ID of the Team. (required) + * @return ResponseEntity<TaskToTeamAssignment> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createTaskToTeamAssignmentWithHttpInfo(String taskId, String teamId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling createTaskToTeamAssignment"); + } + + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamId' when calling createTaskToTeamAssignment"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + uriVariables.put("team_id", teamId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/teams/{team_id}", HttpMethod.PUT, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Delete a Task to Team Assignment + * Removes the Team's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. (required) + * @param teamId ID of the Team. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteTaskToTeamAssignment(String taskId, String teamId) throws RestClientException { + deleteTaskToTeamAssignmentWithHttpInfo(taskId, teamId); + } + + /** + * Delete a Task to Team Assignment + * Removes the Team's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. (required) + * @param teamId ID of the Team. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTaskToTeamAssignmentWithHttpInfo(String taskId, String teamId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling deleteTaskToTeamAssignment"); + } + + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamId' when calling deleteTaskToTeamAssignment"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + uriVariables.put("team_id", teamId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/teams/{team_id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Task to Team Assignments + * Lists the Teams assigned to the Task. + *

200 - Page of Task to Team Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to team_name) + * @return TaskToTeamAssignmentsPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TaskToTeamAssignmentsPage fetchTaskToTeamAssignments(String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToTeamAssignmentsSortColumn sortBy) throws RestClientException { + return fetchTaskToTeamAssignmentsWithHttpInfo(taskId, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Task to Team Assignments + * Lists the Teams assigned to the Task. + *

200 - Page of Task to Team Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to team_name) + * @return ResponseEntity<TaskToTeamAssignmentsPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTaskToTeamAssignmentsWithHttpInfo(String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToTeamAssignmentsSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling fetchTaskToTeamAssignments"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/teams", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Task to Team Assignment + * Returns the assignment of a single Team to the Task. + *

200 - The requested Task to Team Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param teamId ID of the Team. (required) + * @return TaskToTeamAssignment + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TaskToTeamAssignment getTaskToTeamAssignment(String taskId, String teamId) throws RestClientException { + return getTaskToTeamAssignmentWithHttpInfo(taskId, teamId).getBody(); + } + + /** + * Get a Task to Team Assignment + * Returns the assignment of a single Team to the Task. + *

200 - The requested Task to Team Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param teamId ID of the Team. (required) + * @return ResponseEntity<TaskToTeamAssignment> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTaskToTeamAssignmentWithHttpInfo(String taskId, String teamId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling getTaskToTeamAssignment"); + } + + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamId' when calling getTaskToTeamAssignment"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + uriVariables.put("team_id", teamId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/teams/{team_id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskToUserAssignmentApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskToUserAssignmentApi.java new file mode 100644 index 0000000..6c65507 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskToUserAssignmentApi.java @@ -0,0 +1,337 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Error; +import com.timr.api.models.SortDirection; +import com.timr.api.models.TaskToUserAssignment; +import com.timr.api.models.TaskToUserAssignmentUpsert; +import com.timr.api.models.TaskToUserAssignmentsPage; +import com.timr.api.models.TaskToUserAssignmentsSortColumn; +import java.net.URI; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.TaskToUserAssignmentApi") +public class TaskToUserAssignmentApi extends BaseApi { + + public TaskToUserAssignmentApi() { + super(new ApiClient()); + } + + @Autowired + public TaskToUserAssignmentApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Delete a Task to User Assignment + * Removes the User's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteTaskToUserAssignment(String taskId, String userId) throws RestClientException { + deleteTaskToUserAssignmentWithHttpInfo(taskId, userId); + } + + /** + * Delete a Task to User Assignment + * Removes the User's assignment to the Task. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTaskToUserAssignmentWithHttpInfo(String taskId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling deleteTaskToUserAssignment"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling deleteTaskToUserAssignment"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/users/{user_id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Task to User Assignments + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + *

200 - Page of Task to User Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to user_name) + * @return TaskToUserAssignmentsPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TaskToUserAssignmentsPage fetchTaskToUserAssignments(String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToUserAssignmentsSortColumn sortBy) throws RestClientException { + return fetchTaskToUserAssignmentsWithHttpInfo(taskId, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Task to User Assignments + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + *

200 - Page of Task to User Assignments. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to user_name) + * @return ResponseEntity<TaskToUserAssignmentsPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTaskToUserAssignmentsWithHttpInfo(String taskId, String pageToken, Integer limit, SortDirection sortDirection, TaskToUserAssignmentsSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling fetchTaskToUserAssignments"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/users", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Task to User Assignment + * Returns the assignment of a single User to the Task. + *

200 - The requested Task to User Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @return TaskToUserAssignment + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TaskToUserAssignment getTaskToUserAssignment(String taskId, String userId) throws RestClientException { + return getTaskToUserAssignmentWithHttpInfo(taskId, userId).getBody(); + } + + /** + * Get a Task to User Assignment + * Returns the assignment of a single User to the Task. + *

200 - The requested Task to User Assignment. + *

403 - Forbidden + *

404 - Not Found + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<TaskToUserAssignment> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTaskToUserAssignmentWithHttpInfo(String taskId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling getTaskToUserAssignment"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling getTaskToUserAssignment"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/users/{user_id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Create or update a Task to User Assignment + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + *

200 - The updated Task to User Assignment. + *

201 - The created Task to User Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @param taskToUserAssignmentUpsert Task to User Assignment entity (required) + * @return TaskToUserAssignment + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TaskToUserAssignment upsertTaskToUserAssignment(String taskId, String userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert) throws RestClientException { + return upsertTaskToUserAssignmentWithHttpInfo(taskId, userId, taskToUserAssignmentUpsert).getBody(); + } + + /** + * Create or update a Task to User Assignment + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + *

200 - The updated Task to User Assignment. + *

201 - The created Task to User Assignment. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param taskId ID of the Task. (required) + * @param userId ID of the User. (required) + * @param taskToUserAssignmentUpsert Task to User Assignment entity (required) + * @return ResponseEntity<TaskToUserAssignment> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity upsertTaskToUserAssignmentWithHttpInfo(String taskId, String userId, TaskToUserAssignmentUpsert taskToUserAssignmentUpsert) throws RestClientException { + Object localVarPostBody = taskToUserAssignmentUpsert; + + // verify the required parameter 'taskId' is set + if (taskId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskId' when calling upsertTaskToUserAssignment"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling upsertTaskToUserAssignment"); + } + + // verify the required parameter 'taskToUserAssignmentUpsert' is set + if (taskToUserAssignmentUpsert == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'taskToUserAssignmentUpsert' when calling upsertTaskToUserAssignment"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("task_id", taskId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{task_id}/users/{user_id}", HttpMethod.PUT, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TeamApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TeamApi.java new file mode 100644 index 0000000..90f467c --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TeamApi.java @@ -0,0 +1,870 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Error; +import com.timr.api.models.SortDirection; +import com.timr.api.models.Team; +import com.timr.api.models.TeamCreate; +import com.timr.api.models.TeamUpdate; +import com.timr.api.models.TeamsPage; +import com.timr.api.models.TeamsSortColumn; +import java.net.URI; +import com.timr.api.models.UserPartial; +import com.timr.api.models.UsersPartialPage; +import com.timr.api.models.UsersSortColumn; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.TeamApi") +public class TeamApi extends BaseApi { + + public TeamApi() { + super(new ApiClient()); + } + + @Autowired + public TeamApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Add a Team Leader + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + *

200 - The Team Leader, which was already assigned. + *

201 - The newly assigned Team Leader. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return UserPartial + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public UserPartial addTeamLeader(String teamId, String userId) throws RestClientException { + return addTeamLeaderWithHttpInfo(teamId, userId).getBody(); + } + + /** + * Add a Team Leader + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + *

200 - The Team Leader, which was already assigned. + *

201 - The newly assigned Team Leader. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<UserPartial> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity addTeamLeaderWithHttpInfo(String teamId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamId' when calling addTeamLeader"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling addTeamLeader"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("team_id", teamId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{team_id}/leaders/{user_id}", HttpMethod.PUT, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Add a Team Member + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + *

200 - The Team Member, which was already assigned. + *

201 - The newly assigned Team Member. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return UserPartial + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public UserPartial addTeamMember(String teamId, String userId) throws RestClientException { + return addTeamMemberWithHttpInfo(teamId, userId).getBody(); + } + + /** + * Add a Team Member + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + *

200 - The Team Member, which was already assigned. + *

201 - The newly assigned Team Member. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<UserPartial> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity addTeamMemberWithHttpInfo(String teamId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamId' when calling addTeamMember"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling addTeamMember"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("team_id", teamId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{team_id}/members/{user_id}", HttpMethod.PUT, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Create a Team + * Creates a Team from the data in the request body. + *

201 - The created Team. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamCreate Team entity (required) + * @return Team + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Team createTeam(TeamCreate teamCreate) throws RestClientException { + return createTeamWithHttpInfo(teamCreate).getBody(); + } + + /** + * Create a Team + * Creates a Team from the data in the request body. + *

201 - The created Team. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param teamCreate Team entity (required) + * @return ResponseEntity<Team> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createTeamWithHttpInfo(TeamCreate teamCreate) throws RestClientException { + Object localVarPostBody = teamCreate; + + // verify the required parameter 'teamCreate' is set + if (teamCreate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamCreate' when calling createTeam"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Delete a Team + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Team. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteTeam(String id) throws RestClientException { + deleteTeamWithHttpInfo(id); + } + + /** + * Delete a Team + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Team. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTeamWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling deleteTeam"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Team Leaders + * Lists the Users who lead the Team. + *

200 - Page of Team Leaders. + *

400 - Bad Request + * @param id ID of the Team. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return UsersPartialPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public UsersPartialPage fetchTeamLeaders(String id, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientException { + return fetchTeamLeadersWithHttpInfo(id, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Team Leaders + * Lists the Users who lead the Team. + *

200 - Page of Team Leaders. + *

400 - Bad Request + * @param id ID of the Team. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return ResponseEntity<UsersPartialPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTeamLeadersWithHttpInfo(String id, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling fetchTeamLeaders"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{id}/leaders", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Team Members + * Lists the Users who are members of the Team. + *

200 - Page of Team Members. + *

400 - Bad Request + * @param id ID of the Team. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return UsersPartialPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public UsersPartialPage fetchTeamMembers(String id, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientException { + return fetchTeamMembersWithHttpInfo(id, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Team Members + * Lists the Users who are members of the Team. + *

200 - Page of Team Members. + *

400 - Bad Request + * @param id ID of the Team. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return ResponseEntity<UsersPartialPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTeamMembersWithHttpInfo(String id, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling fetchTeamMembers"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{id}/members", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Teams + * Lists the Teams the authenticated user or API token can access. + *

200 - Page of Teams. + *

400 - Bad Request + * @param name Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return TeamsPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TeamsPage fetchTeams(String name, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientException { + return fetchTeamsWithHttpInfo(name, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Teams + * Lists the Teams the authenticated user or API token can access. + *

200 - Page of Teams. + *

400 - Bad Request + * @param name Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return ResponseEntity<TeamsPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchTeamsWithHttpInfo(String name, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Team + * Returns a single Team by its ID. + *

200 - The requested Team. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Team. (required) + * @return Team + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Team getTeam(String id) throws RestClientException { + return getTeamWithHttpInfo(id).getBody(); + } + + /** + * Get a Team + * Returns a single Team by its ID. + *

200 - The requested Team. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Team. (required) + * @return ResponseEntity<Team> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTeamWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getTeam"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Team Leader + * Returns the leadership of a single User in the Team. + *

200 - The requested Team Leader. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return UserPartial + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public UserPartial getTeamLeader(String teamId, String userId) throws RestClientException { + return getTeamLeaderWithHttpInfo(teamId, userId).getBody(); + } + + /** + * Get a Team Leader + * Returns the leadership of a single User in the Team. + *

200 - The requested Team Leader. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<UserPartial> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTeamLeaderWithHttpInfo(String teamId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamId' when calling getTeamLeader"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling getTeamLeader"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("team_id", teamId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{team_id}/leaders/{user_id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Team Member + * Returns the membership of a single User in the Team. + *

200 - The requested Team Member. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return UserPartial + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public UserPartial getTeamMember(String teamId, String userId) throws RestClientException { + return getTeamMemberWithHttpInfo(teamId, userId).getBody(); + } + + /** + * Get a Team Member + * Returns the membership of a single User in the Team. + *

200 - The requested Team Member. + *

403 - Forbidden + *

404 - Not Found + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<UserPartial> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getTeamMemberWithHttpInfo(String teamId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamId' when calling getTeamMember"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling getTeamMember"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("team_id", teamId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{team_id}/members/{user_id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Remove a Team Leader + * Removes the User's leadership of the Team. The User itself is not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void removeTeamLeader(String teamId, String userId) throws RestClientException { + removeTeamLeaderWithHttpInfo(teamId, userId); + } + + /** + * Remove a Team Leader + * Removes the User's leadership of the Team. The User itself is not deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity removeTeamLeaderWithHttpInfo(String teamId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamId' when calling removeTeamLeader"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling removeTeamLeader"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("team_id", teamId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{team_id}/leaders/{user_id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Remove a Team Member + * Removes the User's membership in the Team. The User itself is not deleted. + *

204 - Removed. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void removeTeamMember(String teamId, String userId) throws RestClientException { + removeTeamMemberWithHttpInfo(teamId, userId); + } + + /** + * Remove a Team Member + * Removes the User's membership in the Team. The User itself is not deleted. + *

204 - Removed. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param teamId ID of the Team. (required) + * @param userId ID of the User. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity removeTeamMemberWithHttpInfo(String teamId, String userId) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'teamId' is set + if (teamId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamId' when calling removeTeamMember"); + } + + // verify the required parameter 'userId' is set + if (userId == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userId' when calling removeTeamMember"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("team_id", teamId); + uriVariables.put("user_id", userId); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{team_id}/members/{user_id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Update a Team + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Team. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Team. (required) + * @param teamUpdate Team entity (required) + * @return Team + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Team updateTeam(String id, TeamUpdate teamUpdate) throws RestClientException { + return updateTeamWithHttpInfo(id, teamUpdate).getBody(); + } + + /** + * Update a Team + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Team. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Team. (required) + * @param teamUpdate Team entity (required) + * @return ResponseEntity<Team> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateTeamWithHttpInfo(String id, TeamUpdate teamUpdate) throws RestClientException { + Object localVarPostBody = teamUpdate; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling updateTeam"); + } + + // verify the required parameter 'teamUpdate' is set + if (teamUpdate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'teamUpdate' when calling updateTeam"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/teams/{id}", HttpMethod.PATCH, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TimeAccountApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TimeAccountApi.java new file mode 100644 index 0000000..c7f143d --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TimeAccountApi.java @@ -0,0 +1,189 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Accounts; +import com.timr.api.models.Error; +import java.time.LocalDate; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.TimeAccountApi") +public class TimeAccountApi extends BaseApi { + + public TimeAccountApi() { + super(new ApiClient()); + } + + @Autowired + public TimeAccountApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Get a User's accounts + * Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + *

200 - The User's account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. (required) + * @param date Day to return the balances for. (required) + * @return Accounts + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Accounts getUserAccounts(String id, LocalDate date) throws RestClientException { + return getUserAccountsWithHttpInfo(id, date).getBody(); + } + + /** + * Get a User's accounts + * Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + *

200 - The User's account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. (required) + * @param date Day to return the balances for. (required) + * @return ResponseEntity<Accounts> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserAccountsWithHttpInfo(String id, LocalDate date) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getUserAccounts"); + } + + // verify the required parameter 'date' is set + if (date == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'date' when calling getUserAccounts"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + uriVariables.put("date", date); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users/{id}/accounts/{date}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a User's working time accounts + * Returns the User's working time account balances as of the given day. + *

200 - The User's working time account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. (required) + * @param date Day to return the balances for. (required) + * @return Accounts + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Accounts getUserWorkingTimeAccounts(String id, LocalDate date) throws RestClientException { + return getUserWorkingTimeAccountsWithHttpInfo(id, date).getBody(); + } + + /** + * Get a User's working time accounts + * Returns the User's working time account balances as of the given day. + *

200 - The User's working time account balances on the given day. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. (required) + * @param date Day to return the balances for. (required) + * @return ResponseEntity<Accounts> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserWorkingTimeAccountsWithHttpInfo(String id, LocalDate date) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getUserWorkingTimeAccounts"); + } + + // verify the required parameter 'date' is set + if (date == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'date' when calling getUserWorkingTimeAccounts"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + uriVariables.put("date", date); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users/{id}/working-time-accounts/{date}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TrackApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TrackApi.java new file mode 100644 index 0000000..75b7795 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TrackApi.java @@ -0,0 +1,307 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Error; +import com.timr.api.models.Waypoint; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.TrackApi") +public class TrackApi extends BaseApi { + + public TrackApi() { + super(new ApiClient()); + } + + @Autowired + public TrackApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a Drive Log's Track + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id (required) + * @param waypoint Working Time Date Span entity (required) + * @return List<Waypoint> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public List createTrack(String id, List waypoint) throws RestClientException { + return createTrackWithHttpInfo(id, waypoint).getBody(); + } + + /** + * Create a Drive Log's Track + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id (required) + * @param waypoint Working Time Date Span entity (required) + * @return ResponseEntity<List<Waypoint>> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> createTrackWithHttpInfo(String id, List waypoint) throws RestClientException { + Object localVarPostBody = waypoint; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling createTrack"); + } + + // verify the required parameter 'waypoint' is set + if (waypoint == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'waypoint' when calling createTrack"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference> localReturnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI("/drive-logs/{id}/track", HttpMethod.POST, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Delete a Drive Log's Track + * Deletes the Drive Log's Track. The Drive Log itself is kept. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id drive log id (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteTrack(String id) throws RestClientException { + deleteTrackWithHttpInfo(id); + } + + /** + * Delete a Drive Log's Track + * Deletes the Drive Log's Track. The Drive Log itself is kept. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id drive log id (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTrackWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling deleteTrack"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/drive-logs/{id}/track", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Drive Log's Track + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + *

200 - The Track of the Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + * @param id drive log id (required) + * @return List<Waypoint> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public List getTrack(String id) throws RestClientException { + return getTrackWithHttpInfo(id).getBody(); + } + + /** + * Get a Drive Log's Track + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + *

200 - The Track of the Drive Log. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + * @param id drive log id (required) + * @return ResponseEntity<List<Waypoint>> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> getTrackWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getTrack"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference> localReturnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI("/drive-logs/{id}/track", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Replace a Drive Log's Track + * Replaces the Drive Log's Track with the waypoints in the request body. + *

200 - The updated Working Time Date Span. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id (required) + * @param waypoint working time date span entity (required) + * @return List<Waypoint> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public List updateTrack(String id, List waypoint) throws RestClientException { + return updateTrackWithHttpInfo(id, waypoint).getBody(); + } + + /** + * Replace a Drive Log's Track + * Replaces the Drive Log's Track with the waypoints in the request body. + *

200 - The updated Working Time Date Span. + *

400 - Bad Request + *

403 - Forbidden + *

409 - Conflict + *

422 - Unprocessable Content + * @param id drive log id (required) + * @param waypoint working time date span entity (required) + * @return ResponseEntity<List<Waypoint>> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity> updateTrackWithHttpInfo(String id, List waypoint) throws RestClientException { + Object localVarPostBody = waypoint; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling updateTrack"); + } + + // verify the required parameter 'waypoint' is set + if (waypoint == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'waypoint' when calling updateTrack"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference> localReturnType = new ParameterizedTypeReference>() {}; + return apiClient.invokeAPI("/drive-logs/{id}/track", HttpMethod.PUT, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/UserApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/UserApi.java new file mode 100644 index 0000000..0f9fa6e --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/UserApi.java @@ -0,0 +1,512 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Error; +import java.time.LocalDate; +import com.timr.api.models.SortDirection; +import com.timr.api.models.TeamsPartialPage; +import com.timr.api.models.TeamsSortColumn; +import java.net.URI; +import com.timr.api.models.User; +import com.timr.api.models.UserCreate; +import com.timr.api.models.UserUpdate; +import com.timr.api.models.UsersPage; +import com.timr.api.models.UsersSortColumn; +import com.timr.api.models.WorkScheduleModel; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.UserApi") +public class UserApi extends BaseApi { + + public UserApi() { + super(new ApiClient()); + } + + @Autowired + public UserApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a User + * Creates a User from the data in the request body. + *

201 - The created User. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param userCreate User entity (required) + * @return User + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public User createUser(UserCreate userCreate) throws RestClientException { + return createUserWithHttpInfo(userCreate).getBody(); + } + + /** + * Create a User + * Creates a User from the data in the request body. + *

201 - The created User. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param userCreate User entity (required) + * @return ResponseEntity<User> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createUserWithHttpInfo(UserCreate userCreate) throws RestClientException { + Object localVarPostBody = userCreate; + + // verify the required parameter 'userCreate' is set + if (userCreate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userCreate' when calling createUser"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List a User's Team leaderships + * Lists the Teams the User leads. + *

200 - Page of Teams the User leads. + *

400 - Bad Request + * @param id ID of the User. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return TeamsPartialPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TeamsPartialPage fetchUserTeamLeaderships(String id, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientException { + return fetchUserTeamLeadershipsWithHttpInfo(id, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List a User's Team leaderships + * Lists the Teams the User leads. + *

200 - Page of Teams the User leads. + *

400 - Bad Request + * @param id ID of the User. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return ResponseEntity<TeamsPartialPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchUserTeamLeadershipsWithHttpInfo(String id, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling fetchUserTeamLeaderships"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users/{id}/team-leaderships", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List a User's Team memberships + * Lists the Teams the User is a member of. + *

200 - Page of Teams the User is a member of. + *

400 - Bad Request + * @param id ID of the User. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return TeamsPartialPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public TeamsPartialPage fetchUserTeamMemberships(String id, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientException { + return fetchUserTeamMembershipsWithHttpInfo(id, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List a User's Team memberships + * Lists the Teams the User is a member of. + *

200 - Page of Teams the User is a member of. + *

400 - Bad Request + * @param id ID of the User. (required) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to breadcrumbs) + * @return ResponseEntity<TeamsPartialPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchUserTeamMembershipsWithHttpInfo(String id, String pageToken, Integer limit, SortDirection sortDirection, TeamsSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling fetchUserTeamMemberships"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users/{id}/team-memberships", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Users + * Lists the Users the authenticated user or API token can access. + *

200 - Page of Users. + *

400 - Bad Request + * @param name Only return Users whose name contains this text. (optional) + * @param entryDateFrom Only return Users whose entry date is on or after this day. (optional) + * @param entryDateTo Only return Users whose entry date is on or before this day. (optional) + * @param resignDateFrom Only return Users whose resignation date is on or after this day. (optional) + * @param resignDateTo Only return Users whose resignation date is on or before this day. (optional) + * @param resigned Only return Users who have resigned (true) or have not resigned (false). (optional) + * @param employeeNumber Only return Users with this employee number. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return UsersPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public UsersPage fetchUsers(String name, LocalDate entryDateFrom, LocalDate entryDateTo, LocalDate resignDateFrom, LocalDate resignDateTo, Boolean resigned, String employeeNumber, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientException { + return fetchUsersWithHttpInfo(name, entryDateFrom, entryDateTo, resignDateFrom, resignDateTo, resigned, employeeNumber, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Users + * Lists the Users the authenticated user or API token can access. + *

200 - Page of Users. + *

400 - Bad Request + * @param name Only return Users whose name contains this text. (optional) + * @param entryDateFrom Only return Users whose entry date is on or after this day. (optional) + * @param entryDateTo Only return Users whose entry date is on or before this day. (optional) + * @param resignDateFrom Only return Users whose resignation date is on or after this day. (optional) + * @param resignDateTo Only return Users whose resignation date is on or before this day. (optional) + * @param resigned Only return Users who have resigned (true) or have not resigned (false). (optional) + * @param employeeNumber Only return Users with this employee number. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return ResponseEntity<UsersPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchUsersWithHttpInfo(String name, LocalDate entryDateFrom, LocalDate entryDateTo, LocalDate resignDateFrom, LocalDate resignDateTo, Boolean resigned, String employeeNumber, String pageToken, Integer limit, SortDirection sortDirection, UsersSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "entry_date_from", entryDateFrom)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "entry_date_to", entryDateTo)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "resign_date_from", resignDateFrom)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "resign_date_to", resignDateTo)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "resigned", resigned)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "employee_number", employeeNumber)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a User + * Returns a single User by its ID. + *

200 - The requested User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. (required) + * @return User + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public User getUser(String id) throws RestClientException { + return getUserWithHttpInfo(id).getBody(); + } + + /** + * Get a User + * Returns a single User by its ID. + *

200 - The requested User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. (required) + * @return ResponseEntity<User> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getUser"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a User's Work Schedule Model + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + *

200 - The Work Schedule Model assigned to the User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. (required) + * @return WorkScheduleModel + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkScheduleModel getUserWorkScheduleModel(String id) throws RestClientException { + return getUserWorkScheduleModelWithHttpInfo(id).getBody(); + } + + /** + * Get a User's Work Schedule Model + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + *

200 - The Work Schedule Model assigned to the User. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the User. (required) + * @return ResponseEntity<WorkScheduleModel> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getUserWorkScheduleModelWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getUserWorkScheduleModel"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users/{id}/work-schedule-model", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Update a User + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated User. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the User. (required) + * @param userUpdate User entity (required) + * @return User + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public User updateUser(String id, UserUpdate userUpdate) throws RestClientException { + return updateUserWithHttpInfo(id, userUpdate).getBody(); + } + + /** + * Update a User + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated User. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the User. (required) + * @param userUpdate User entity (required) + * @return ResponseEntity<User> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateUserWithHttpInfo(String id, UserUpdate userUpdate) throws RestClientException { + Object localVarPostBody = userUpdate; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling updateUser"); + } + + // verify the required parameter 'userUpdate' is set + if (userUpdate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'userUpdate' when calling updateUser"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/users/{id}", HttpMethod.PATCH, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkScheduleModelApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkScheduleModelApi.java new file mode 100644 index 0000000..0a624b1 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkScheduleModelApi.java @@ -0,0 +1,232 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.Error; +import com.timr.api.models.SortDirection; +import java.net.URI; +import com.timr.api.models.WorkScheduleModel; +import com.timr.api.models.WorkScheduleModelSortColumn; +import com.timr.api.models.WorkScheduleModelsPage; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.WorkScheduleModelApi") +public class WorkScheduleModelApi extends BaseApi { + + public WorkScheduleModelApi() { + super(new ApiClient()); + } + + @Autowired + public WorkScheduleModelApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Delete a Work Schedule Model + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Work Schedule Model. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteWorkScheduleModel(String id) throws RestClientException { + deleteWorkScheduleModelWithHttpInfo(id); + } + + /** + * Delete a Work Schedule Model + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Work Schedule Model. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteWorkScheduleModelWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling deleteWorkScheduleModel"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/work-schedule-models/{id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Work Schedule Models + * Lists the Work Schedule Models the authenticated user or API token can access. + *

200 - Page of Work Schedule Models. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return WorkScheduleModelsPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkScheduleModelsPage fetchWorkScheduleModels(String pageToken, Integer limit, SortDirection sortDirection, WorkScheduleModelSortColumn sortBy) throws RestClientException { + return fetchWorkScheduleModelsWithHttpInfo(pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Work Schedule Models + * Lists the Work Schedule Models the authenticated user or API token can access. + *

200 - Page of Work Schedule Models. + *

400 - Bad Request + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return ResponseEntity<WorkScheduleModelsPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchWorkScheduleModelsWithHttpInfo(String pageToken, Integer limit, SortDirection sortDirection, WorkScheduleModelSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/work-schedule-models", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Work Schedule Model + * Returns a single Work Schedule Model by its ID. + *

200 - The requested Work Schedule Model. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Work Schedule Model. (required) + * @return WorkScheduleModel + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkScheduleModel getWorkScheduleModel(String id) throws RestClientException { + return getWorkScheduleModelWithHttpInfo(id).getBody(); + } + + /** + * Get a Work Schedule Model + * Returns a single Work Schedule Model by its ID. + *

200 - The requested Work Schedule Model. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Work Schedule Model. (required) + * @return ResponseEntity<WorkScheduleModel> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getWorkScheduleModelWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getWorkScheduleModel"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/work-schedule-models/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkingTimeApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkingTimeApi.java new file mode 100644 index 0000000..8b5f03c --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkingTimeApi.java @@ -0,0 +1,451 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.DeletedEntrySortColumn; +import com.timr.api.models.DeletedEntryWithMetadataPage; +import com.timr.api.models.Error; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import com.timr.api.models.SortDirection; +import java.net.URI; +import com.timr.api.models.WorkingTime; +import com.timr.api.models.WorkingTimeCreate; +import com.timr.api.models.WorkingTimeStatus; +import com.timr.api.models.WorkingTimeTypeCategory; +import com.timr.api.models.WorkingTimeUpdate; +import com.timr.api.models.WorkingTimesPage; +import com.timr.api.models.WorkingTimesSortColumn; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.WorkingTimeApi") +public class WorkingTimeApi extends BaseApi { + + public WorkingTimeApi() { + super(new ApiClient()); + } + + @Autowired + public WorkingTimeApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a Working Time + * Creates a Working Time from the data in the request body. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeCreate Working Time entity (required) + * @return WorkingTime + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTime createWorkingTime(WorkingTimeCreate workingTimeCreate) throws RestClientException { + return createWorkingTimeWithHttpInfo(workingTimeCreate).getBody(); + } + + /** + * Create a Working Time + * Creates a Working Time from the data in the request body. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeCreate Working Time entity (required) + * @return ResponseEntity<WorkingTime> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createWorkingTimeWithHttpInfo(WorkingTimeCreate workingTimeCreate) throws RestClientException { + Object localVarPostBody = workingTimeCreate; + + // verify the required parameter 'workingTimeCreate' is set + if (workingTimeCreate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'workingTimeCreate' when calling createWorkingTime"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-times", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Delete a Working Time + * Deletes the Working Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteWorkingTime(String id) throws RestClientException { + deleteWorkingTimeWithHttpInfo(id); + } + + /** + * Delete a Working Time + * Deletes the Working Time. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteWorkingTimeWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling deleteWorkingTime"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-times/{id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List deleted Working Times + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to last_modified) + * @return DeletedEntryWithMetadataPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DeletedEntryWithMetadataPage fetchDeletedWorkingTimes(OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientException { + return fetchDeletedWorkingTimesWithHttpInfo(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List deleted Working Times + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Times. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to last_modified) + * @return ResponseEntity<DeletedEntryWithMetadataPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDeletedWorkingTimesWithHttpInfo(OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-times:deleted", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Working Times + * Lists the Working Times the authenticated user or API token can access. + *

200 - Page of Working Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param workingTimeTypeCategories Only return entries whose Working Time Type is in one of these categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to start) + * @return WorkingTimesPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTimesPage fetchWorkingTimes(String notes, LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, List workingTimeTypes, List workingTimeTypeCategories, List statuses, List users, Boolean changed, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimesSortColumn sortBy) throws RestClientException { + return fetchWorkingTimesWithHttpInfo(notes, startFrom, startTo, lastModifiedAfter, workingTimeTypes, workingTimeTypeCategories, statuses, users, changed, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Working Times + * Lists the Working Times the authenticated user or API token can access. + *

200 - Page of Working Times. + *

400 - Bad Request + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param workingTimeTypeCategories Only return entries whose Working Time Type is in one of these categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to start) + * @return ResponseEntity<WorkingTimesPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchWorkingTimesWithHttpInfo(String notes, LocalDate startFrom, LocalDate startTo, OffsetDateTime lastModifiedAfter, List workingTimeTypes, List workingTimeTypeCategories, List statuses, List users, Boolean changed, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimesSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "notes", notes)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_from", startFrom)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "start_to", startTo)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "working_time_types", workingTimeTypes)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "working_time_type_categories", workingTimeTypeCategories)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "statuses", statuses)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "users", users)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "changed", changed)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-times", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Working Time + * Returns a single Working Time by its ID. + *

200 - The requested Working Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time. (required) + * @return WorkingTime + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTime getWorkingTime(String id) throws RestClientException { + return getWorkingTimeWithHttpInfo(id).getBody(); + } + + /** + * Get a Working Time + * Returns a single Working Time by its ID. + *

200 - The requested Working Time. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time. (required) + * @return ResponseEntity<WorkingTime> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getWorkingTimeWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getWorkingTime"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-times/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Update a Working Time + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Working Time. + *

302 - No Working Time was created because the working time type requires a request (recordingMode BY_REQUEST); a Working Time Request was created instead. The Location header points to the created Working Time Request. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time. (required) + * @param workingTimeUpdate Working Time entity (required) + * @return WorkingTime + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTime updateWorkingTime(String id, WorkingTimeUpdate workingTimeUpdate) throws RestClientException { + return updateWorkingTimeWithHttpInfo(id, workingTimeUpdate).getBody(); + } + + /** + * Update a Working Time + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + *

200 - The updated Working Time. + *

302 - No Working Time was created because the working time type requires a request (recordingMode BY_REQUEST); a Working Time Request was created instead. The Location header points to the created Working Time Request. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time. (required) + * @param workingTimeUpdate Working Time entity (required) + * @return ResponseEntity<WorkingTime> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateWorkingTimeWithHttpInfo(String id, WorkingTimeUpdate workingTimeUpdate) throws RestClientException { + Object localVarPostBody = workingTimeUpdate; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling updateWorkingTime"); + } + + // verify the required parameter 'workingTimeUpdate' is set + if (workingTimeUpdate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'workingTimeUpdate' when calling updateWorkingTime"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-times/{id}", HttpMethod.PATCH, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkingTimeDateSpanApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkingTimeDateSpanApi.java new file mode 100644 index 0000000..c704810 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkingTimeDateSpanApi.java @@ -0,0 +1,437 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.DeletedEntrySortColumn; +import com.timr.api.models.DeletedEntryWithMetadataPage; +import com.timr.api.models.Error; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import com.timr.api.models.SortDirection; +import java.net.URI; +import com.timr.api.models.WorkingTimeDateSpan; +import com.timr.api.models.WorkingTimeDateSpanCreate; +import com.timr.api.models.WorkingTimeDateSpanPage; +import com.timr.api.models.WorkingTimeDateSpanUpdate; +import com.timr.api.models.WorkingTimeDateSpansSortColumn; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.WorkingTimeDateSpanApi") +public class WorkingTimeDateSpanApi extends BaseApi { + + public WorkingTimeDateSpanApi() { + super(new ApiClient()); + } + + @Autowired + public WorkingTimeDateSpanApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Create a Working Time Date Span + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeDateSpanCreate Working Time Date Span entity (required) + * @return WorkingTimeDateSpan + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTimeDateSpan createWorkingTimeDateSpan(WorkingTimeDateSpanCreate workingTimeDateSpanCreate) throws RestClientException { + return createWorkingTimeDateSpanWithHttpInfo(workingTimeDateSpanCreate).getBody(); + } + + /** + * Create a Working Time Date Span + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + *

201 - The created Working Time. + *

400 - Bad Request + *

409 - Conflict + *

422 - Unprocessable Content + * @param workingTimeDateSpanCreate Working Time Date Span entity (required) + * @return ResponseEntity<WorkingTimeDateSpan> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity createWorkingTimeDateSpanWithHttpInfo(WorkingTimeDateSpanCreate workingTimeDateSpanCreate) throws RestClientException { + Object localVarPostBody = workingTimeDateSpanCreate; + + // verify the required parameter 'workingTimeDateSpanCreate' is set + if (workingTimeDateSpanCreate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'workingTimeDateSpanCreate' when calling createWorkingTimeDateSpan"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-time-date-spans", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Delete a Working Time Date Span + * Deletes the Working Time Date Span together with the Working Times it covers. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Date Span. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteWorkingTimeDateSpan(String id) throws RestClientException { + deleteWorkingTimeDateSpanWithHttpInfo(id); + } + + /** + * Delete a Working Time Date Span + * Deletes the Working Time Date Span together with the Working Times it covers. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Date Span. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteWorkingTimeDateSpanWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling deleteWorkingTimeDateSpan"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-time-date-spans/{id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List deleted Working Time Date Spans + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Time Date Spans. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to last_modified) + * @return DeletedEntryWithMetadataPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public DeletedEntryWithMetadataPage fetchDeletedWorkingTimeDateSpans(OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientException { + return fetchDeletedWorkingTimeDateSpansWithHttpInfo(lastModifiedAfter, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List deleted Working Time Date Spans + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + *

200 - Page of deleted Working Time Date Spans. + *

400 - Bad Request + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to last_modified) + * @return ResponseEntity<DeletedEntryWithMetadataPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchDeletedWorkingTimeDateSpansWithHttpInfo(OffsetDateTime lastModifiedAfter, String pageToken, Integer limit, SortDirection sortDirection, DeletedEntrySortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-time-date-spans:deleted", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Working Time Date Spans + * Lists the Working Time Date Spans the authenticated user or API token can access. + *

200 - Page of Working Time Date Spans. + *

400 - Bad Request + * @param from Only return Working Time Date Spans that end on or after this day. (optional) + * @param to Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to start) + * @return WorkingTimeDateSpanPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTimeDateSpanPage fetchWorkingTimeDateSpans(LocalDate from, LocalDate to, OffsetDateTime lastModifiedAfter, List workingTimeTypes, List users, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimeDateSpansSortColumn sortBy) throws RestClientException { + return fetchWorkingTimeDateSpansWithHttpInfo(from, to, lastModifiedAfter, workingTimeTypes, users, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Working Time Date Spans + * Lists the Working Time Date Spans the authenticated user or API token can access. + *

200 - Page of Working Time Date Spans. + *

400 - Bad Request + * @param from Only return Working Time Date Spans that end on or after this day. (optional) + * @param to Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to start) + * @return ResponseEntity<WorkingTimeDateSpanPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchWorkingTimeDateSpansWithHttpInfo(LocalDate from, LocalDate to, OffsetDateTime lastModifiedAfter, List workingTimeTypes, List users, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimeDateSpansSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "from", from)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "to", to)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "last_modified_after", lastModifiedAfter)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "working_time_types", workingTimeTypes)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "users", users)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-time-date-spans", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Working Time Date Span + * Returns a single Working Time Date Span by its ID. + *

200 - The requested Working Time Date Span. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Date Span. (required) + * @return WorkingTimeDateSpan + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTimeDateSpan getWorkingTimeDateSpan(String id) throws RestClientException { + return getWorkingTimeDateSpanWithHttpInfo(id).getBody(); + } + + /** + * Get a Working Time Date Span + * Returns a single Working Time Date Span by its ID. + *

200 - The requested Working Time Date Span. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Date Span. (required) + * @return ResponseEntity<WorkingTimeDateSpan> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getWorkingTimeDateSpanWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getWorkingTimeDateSpan"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-time-date-spans/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Update a Working Time Date Span + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + *

200 - The updated Working Time Date Span. + *

204 - Empty response indicating that a date span got deleted. This can happen when it is updated to a day where no working hours can be booked. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time Date Span. (required) + * @param workingTimeDateSpanUpdate working time date span entity (required) + * @return WorkingTimeDateSpan + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTimeDateSpan updateWorkingTimeDateSpan(String id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate) throws RestClientException { + return updateWorkingTimeDateSpanWithHttpInfo(id, workingTimeDateSpanUpdate).getBody(); + } + + /** + * Update a Working Time Date Span + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + *

200 - The updated Working Time Date Span. + *

204 - Empty response indicating that a date span got deleted. This can happen when it is updated to a day where no working hours can be booked. + *

400 - Bad Request + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + *

422 - Unprocessable Content + * @param id ID of the Working Time Date Span. (required) + * @param workingTimeDateSpanUpdate working time date span entity (required) + * @return ResponseEntity<WorkingTimeDateSpan> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity updateWorkingTimeDateSpanWithHttpInfo(String id, WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate) throws RestClientException { + Object localVarPostBody = workingTimeDateSpanUpdate; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling updateWorkingTimeDateSpan"); + } + + // verify the required parameter 'workingTimeDateSpanUpdate' is set + if (workingTimeDateSpanUpdate == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'workingTimeDateSpanUpdate' when calling updateWorkingTimeDateSpan"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-time-date-spans/{id}", HttpMethod.PATCH, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkingTimeTypeApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkingTimeTypeApi.java new file mode 100644 index 0000000..67d54bf --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/WorkingTimeTypeApi.java @@ -0,0 +1,260 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.BaseApi; + +import com.timr.api.models.DurationUnit; +import com.timr.api.models.Error; +import com.timr.api.models.RecordingModeUser; +import com.timr.api.models.SortDirection; +import java.net.URI; +import com.timr.api.models.WorkingTimeType; +import com.timr.api.models.WorkingTimeTypeCategory; +import com.timr.api.models.WorkingTimeTypeSubCategory; +import com.timr.api.models.WorkingTimeTypesPage; +import com.timr.api.models.WorkingTimeTypesSortColumn; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@Component("com.timr.api.apis.WorkingTimeTypeApi") +public class WorkingTimeTypeApi extends BaseApi { + + public WorkingTimeTypeApi() { + super(new ApiClient()); + } + + @Autowired + public WorkingTimeTypeApi(ApiClient apiClient) { + super(apiClient); + } + + /** + * Delete a Working Time Type + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Type. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteWorkingTimeType(String id) throws RestClientException { + deleteWorkingTimeTypeWithHttpInfo(id); + } + + /** + * Delete a Working Time Type + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Working Time Type. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteWorkingTimeTypeWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling deleteWorkingTimeType"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-time-types/{id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * List Working Time Types + * Lists the Working Time Types the authenticated user or API token can access. + *

200 - Page of Working Time Types. + *

400 - Bad Request + * @param name Only return entries whose name contains this text. (optional) + * @param shortName filter by short name (optional) + * @param description filter by description (optional) + * @param categories filter by WorkingTimeTypeCategory (optional) + * @param subCategories filter by WorkingTimeTypeSubCategory (optional) + * @param editUnits filter by WorkingTimeType's DurationUnit (optional) + * @param archived Only return entries that are archived (true) or not archived (false). (optional) + * @param recordingModes filter entries bAWS on their RecordingMode (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return WorkingTimeTypesPage + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTimeTypesPage fetchWorkingTimeTypes(String name, String shortName, String description, List categories, List subCategories, List editUnits, Boolean archived, List recordingModes, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimeTypesSortColumn sortBy) throws RestClientException { + return fetchWorkingTimeTypesWithHttpInfo(name, shortName, description, categories, subCategories, editUnits, archived, recordingModes, pageToken, limit, sortDirection, sortBy).getBody(); + } + + /** + * List Working Time Types + * Lists the Working Time Types the authenticated user or API token can access. + *

200 - Page of Working Time Types. + *

400 - Bad Request + * @param name Only return entries whose name contains this text. (optional) + * @param shortName filter by short name (optional) + * @param description filter by description (optional) + * @param categories filter by WorkingTimeTypeCategory (optional) + * @param subCategories filter by WorkingTimeTypeSubCategory (optional) + * @param editUnits filter by WorkingTimeType's DurationUnit (optional) + * @param archived Only return entries that are archived (true) or not archived (false). (optional) + * @param recordingModes filter entries bAWS on their RecordingMode (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional, default to asc) + * @param sortBy Property to sort the entries by. (optional, default to name) + * @return ResponseEntity<WorkingTimeTypesPage> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity fetchWorkingTimeTypesWithHttpInfo(String name, String shortName, String description, List categories, List subCategories, List editUnits, Boolean archived, List recordingModes, String pageToken, Integer limit, SortDirection sortDirection, WorkingTimeTypesSortColumn sortBy) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", name)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "short_name", shortName)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "description", description)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "categories", categories)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "sub_categories", subCategories)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "edit_units", editUnits)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "archived", archived)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "recording_modes", recordingModes)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "page_token", pageToken)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "limit", limit)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_direction", sortDirection)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "sort_by", sortBy)); + + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-time-types", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Get a Working Time Type + * Returns a single Working Time Type by its ID. + *

200 - The requested Working Time Type. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Type. (required) + * @return WorkingTimeType + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public WorkingTimeType getWorkingTimeType(String id) throws RestClientException { + return getWorkingTimeTypeWithHttpInfo(id).getBody(); + } + + /** + * Get a Working Time Type + * Returns a single Working Time Type by its ID. + *

200 - The requested Working Time Type. + *

403 - Forbidden + *

404 - Not Found + * @param id ID of the Working Time Type. (required) + * @return ResponseEntity<WorkingTimeType> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity getWorkingTimeTypeWithHttpInfo(String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling getWorkingTimeType"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/working-time-types/{id}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + + @Override + public ResponseEntity invokeAPI(String url, HttpMethod method, Object request, ParameterizedTypeReference returnType) throws RestClientException { + String localVarPath = url.replace(apiClient.getBasePath(), ""); + Object localVarPostBody = request; + + final Map uriVariables = new HashMap(); + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json", "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + return apiClient.invokeAPI(localVarPath, method, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, returnType); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/auth/ApiKeyAuth.java b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/ApiKeyAuth.java new file mode 100644 index 0000000..c62fc26 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/ApiKeyAuth.java @@ -0,0 +1,75 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location.equals("query")) { + queryParams.add(paramName, value); + } else if (location.equals("header")) { + headerParams.add(paramName, value); + } else if (location.equals("cookie")) { + cookieParams.add(paramName, value); + } + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/auth/Authentication.java b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/Authentication.java new file mode 100644 index 0000000..b453ce3 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/Authentication.java @@ -0,0 +1,29 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public interface Authentication { + /** + * Apply authentication settings to header and / or query parameters. + * + * @param queryParams The query parameters for the request + * @param headerParams The header parameters for the request + * @param cookieParams The cookie parameters for the request + */ + void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams); +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/auth/HttpBasicAuth.java b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/HttpBasicAuth.java new file mode 100644 index 0000000..cb4452f --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/HttpBasicAuth.java @@ -0,0 +1,51 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/auth/HttpBearerAuth.java b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/HttpBearerAuth.java new file mode 100644 index 0000000..3cd16f1 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/HttpBearerAuth.java @@ -0,0 +1,69 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import java.util.Optional; +import java.util.function.Supplier; +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private Supplier tokenSupplier; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return tokenSupplier.get(); + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { + return; + } + headerParams.add(HttpHeaders.AUTHORIZATION, (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/auth/OAuth.java b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/OAuth.java new file mode 100644 index 0000000..ef6ccf0 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/OAuth.java @@ -0,0 +1,61 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +import java.util.Optional; +import java.util.function.Supplier; +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +/** + * Provides support for RFC 6750 - Bearer Token usage for OAUTH 2.0 Authorization. + */ +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class OAuth implements Authentication { + private Supplier tokenSupplier; + + /** + * Returns the bearer token used for Authorization. + * + * @return The bearer token + */ + public String getAccessToken() { + return tokenSupplier.get(); + } + + /** + * Sets the bearer access token used for Authorization. + * + * @param accessToken The bearer token to send in the Authorization header + */ + public void setAccessToken(String accessToken) { + setAccessToken(() -> accessToken); + } + + /** + * Sets the supplier of bearer tokens used for Authorization. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setAccessToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + Optional.ofNullable(tokenSupplier).map(Supplier::get).ifPresent(accessToken -> + headerParams.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) + ); + } +} diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/auth/OAuthFlow.java b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/OAuthFlow.java new file mode 100644 index 0000000..afcd5c1 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/auth/OAuthFlow.java @@ -0,0 +1,18 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Accounts.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Accounts.java new file mode 100644 index 0000000..848d75f --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Accounts.java @@ -0,0 +1,233 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.OvertimeSurchargeAccounts; +import com.timr.api.models.TimeAccount; +import com.timr.api.models.VacationAccount; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Accounts + */ +@JsonPropertyOrder({ + Accounts.JSON_PROPERTY_LAST_BALANCE_DATE, + Accounts.JSON_PROPERTY_TIME_ACCOUNT, + Accounts.JSON_PROPERTY_OVERTIME_SURCHARGE_ACCOUNTS, + Accounts.JSON_PROPERTY_VACATION_ACCOUNT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Accounts { + public static final String JSON_PROPERTY_LAST_BALANCE_DATE = "last_balance_date"; + @jakarta.annotation.Nullable + private LocalDate lastBalanceDate; + + public static final String JSON_PROPERTY_TIME_ACCOUNT = "time_account"; + @jakarta.annotation.Nullable + private JsonNullable timeAccount = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_OVERTIME_SURCHARGE_ACCOUNTS = "overtime_surcharge_accounts"; + @jakarta.annotation.Nullable + private JsonNullable> overtimeSurchargeAccounts = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_VACATION_ACCOUNT = "vacation_account"; + @jakarta.annotation.Nullable + private JsonNullable vacationAccount = JsonNullable.undefined(); + + public Accounts() { + } + + public Accounts lastBalanceDate(@jakarta.annotation.Nullable LocalDate lastBalanceDate) { + + this.lastBalanceDate = lastBalanceDate; + return this; + } + + /** + * date of last balance + * @return lastBalanceDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAST_BALANCE_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getLastBalanceDate() { + return lastBalanceDate; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_BALANCE_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastBalanceDate(@jakarta.annotation.Nullable LocalDate lastBalanceDate) { + this.lastBalanceDate = lastBalanceDate; + } + + + public Accounts timeAccount(@jakarta.annotation.Nullable TimeAccount timeAccount) { + this.timeAccount = JsonNullable.of(timeAccount); + + return this; + } + + /** + * Get timeAccount + * @return timeAccount + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_TIME_ACCOUNT, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getTimeAccount() { + return timeAccount; + } + + @JsonProperty(JSON_PROPERTY_TIME_ACCOUNT) + public void setTimeAccount(JsonNullable timeAccount) { + this.timeAccount = timeAccount; + } + + + + public Accounts overtimeSurchargeAccounts(@jakarta.annotation.Nullable List overtimeSurchargeAccounts) { + this.overtimeSurchargeAccounts = JsonNullable.>of(overtimeSurchargeAccounts); + + return this; + } + + public Accounts addOvertimeSurchargeAccountsItem(OvertimeSurchargeAccounts overtimeSurchargeAccountsItem) { + if (this.overtimeSurchargeAccounts == null || !this.overtimeSurchargeAccounts.isPresent()) { + this.overtimeSurchargeAccounts = JsonNullable.>of(new ArrayList<>()); + } + try { + this.overtimeSurchargeAccounts.get().add(overtimeSurchargeAccountsItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get overtimeSurchargeAccounts + * @return overtimeSurchargeAccounts + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_OVERTIME_SURCHARGE_ACCOUNTS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getOvertimeSurchargeAccounts() { + return overtimeSurchargeAccounts; + } + + @JsonProperty(JSON_PROPERTY_OVERTIME_SURCHARGE_ACCOUNTS) + public void setOvertimeSurchargeAccounts(JsonNullable> overtimeSurchargeAccounts) { + this.overtimeSurchargeAccounts = overtimeSurchargeAccounts; + } + + + + public Accounts vacationAccount(@jakarta.annotation.Nullable VacationAccount vacationAccount) { + this.vacationAccount = JsonNullable.of(vacationAccount); + + return this; + } + + /** + * Get vacationAccount + * @return vacationAccount + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_VACATION_ACCOUNT, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getVacationAccount() { + return vacationAccount; + } + + @JsonProperty(JSON_PROPERTY_VACATION_ACCOUNT) + public void setVacationAccount(JsonNullable vacationAccount) { + this.vacationAccount = vacationAccount; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Accounts accounts = (Accounts) o; + return Objects.equals(this.lastBalanceDate, accounts.lastBalanceDate) && + equalsNullable(this.timeAccount, accounts.timeAccount) && + equalsNullable(this.overtimeSurchargeAccounts, accounts.overtimeSurchargeAccounts) && + equalsNullable(this.vacationAccount, accounts.vacationAccount); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lastBalanceDate, hashCodeNullable(timeAccount), hashCodeNullable(overtimeSurchargeAccounts), hashCodeNullable(vacationAccount)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Accounts {\n"); + sb.append(" lastBalanceDate: ").append(toIndentedString(lastBalanceDate)).append("\n"); + sb.append(" timeAccount: ").append(toIndentedString(timeAccount)).append("\n"); + sb.append(" overtimeSurchargeAccounts: ").append(!overtimeSurchargeAccounts.isPresent() || overtimeSurchargeAccounts.get() == null ? "null" : overtimeSurchargeAccounts.get().size() + " entries").append("\n"); + sb.append(" vacationAccount: ").append(toIndentedString(vacationAccount)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTime.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTime.java new file mode 100644 index 0000000..da05a22 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTime.java @@ -0,0 +1,49 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeAutomatic; +import com.timr.api.models.BreakTimeManual; +import com.timr.api.models.BreakTimeOngoing; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@JsonIgnoreProperties( + value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the type to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = BreakTimeAutomatic.class, name = "automatic"), + @JsonSubTypes.Type(value = BreakTimeManual.class, name = "manual"), + @JsonSubTypes.Type(value = BreakTimeOngoing.class, name = "ongoing"), +}) + +public interface BreakTime { + public BreakTimeType getType(); +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeAutomatic.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeAutomatic.java new file mode 100644 index 0000000..4869dbb --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeAutomatic.java @@ -0,0 +1,189 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeBase; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * BreakTimeAutomatic + */ +@JsonPropertyOrder({ + BreakTimeAutomatic.JSON_PROPERTY_DURATION_MINUTES, + BreakTimeAutomatic.JSON_PROPERTY_START, + BreakTimeAutomatic.JSON_PROPERTY_END +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class BreakTimeAutomatic extends BreakTimeBase implements BreakTime { + public static final String JSON_PROPERTY_DURATION_MINUTES = "duration_minutes"; + @jakarta.annotation.Nonnull + private Integer durationMinutes; + + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private OffsetDateTime end; + + public BreakTimeAutomatic() { + + } + + public BreakTimeAutomatic durationMinutes(@jakarta.annotation.Nonnull Integer durationMinutes) { + + this.durationMinutes = durationMinutes; + return this; + } + + /** + * Duration of break in minutes + * @return durationMinutes + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getDurationMinutes() { + return durationMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDurationMinutes(@jakarta.annotation.Nonnull Integer durationMinutes) { + this.durationMinutes = durationMinutes; + } + + + public BreakTimeAutomatic start(@jakarta.annotation.Nullable OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nullable OffsetDateTime start) { + this.start = start; + } + + + public BreakTimeAutomatic end(@jakarta.annotation.Nullable OffsetDateTime end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = end; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BreakTimeAutomatic breakTimeAutomatic = (BreakTimeAutomatic) o; + return Objects.equals(this.durationMinutes, breakTimeAutomatic.durationMinutes) && + Objects.equals(this.start, breakTimeAutomatic.start) && + Objects.equals(this.end, breakTimeAutomatic.end) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(durationMinutes, start, end, super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BreakTimeAutomatic {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" durationMinutes: ").append(toIndentedString(durationMinutes)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeBase.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeBase.java new file mode 100644 index 0000000..be8bed1 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeBase.java @@ -0,0 +1,118 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeType; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Members shared by every kind of break time, including the discriminator. + */ +@JsonPropertyOrder({ + BreakTimeBase.JSON_PROPERTY_TYPE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class BreakTimeBase { + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + protected BreakTimeType type; + + public BreakTimeBase() { + } + + public BreakTimeBase type(@jakarta.annotation.Nonnull BreakTimeType type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public BreakTimeType getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull BreakTimeType type) { + this.type = type; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BreakTimeBase breakTimeBase = (BreakTimeBase) o; + return Objects.equals(this.type, breakTimeBase.type); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BreakTimeBase {\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeManual.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeManual.java new file mode 100644 index 0000000..20fc0ff --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeManual.java @@ -0,0 +1,189 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeBase; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * BreakTimeManual + */ +@JsonPropertyOrder({ + BreakTimeManual.JSON_PROPERTY_DURATION_MINUTES, + BreakTimeManual.JSON_PROPERTY_START, + BreakTimeManual.JSON_PROPERTY_END +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class BreakTimeManual extends BreakTimeBase implements BreakTime, BreakTimeUpdate { + public static final String JSON_PROPERTY_DURATION_MINUTES = "duration_minutes"; + @jakarta.annotation.Nonnull + private Integer durationMinutes; + + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private JsonNullable start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public BreakTimeManual() { + + } + + public BreakTimeManual durationMinutes(@jakarta.annotation.Nonnull Integer durationMinutes) { + + this.durationMinutes = durationMinutes; + return this; + } + + /** + * Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. + * @return durationMinutes + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getDurationMinutes() { + return durationMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDurationMinutes(@jakarta.annotation.Nonnull Integer durationMinutes) { + this.durationMinutes = durationMinutes; + } + + + public BreakTimeManual start(@jakarta.annotation.Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public BreakTimeManual end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BreakTimeManual breakTimeManual = (BreakTimeManual) o; + return Objects.equals(this.durationMinutes, breakTimeManual.durationMinutes) && + equalsNullable(this.start, breakTimeManual.start) && + equalsNullable(this.end, breakTimeManual.end) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(durationMinutes, hashCodeNullable(start), hashCodeNullable(end), super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BreakTimeManual {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" durationMinutes: ").append(toIndentedString(durationMinutes)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeOngoing.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeOngoing.java new file mode 100644 index 0000000..cb0f0fa --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeOngoing.java @@ -0,0 +1,123 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeBase; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * BreakTimeOngoing + */ +@JsonPropertyOrder({ + BreakTimeOngoing.JSON_PROPERTY_START +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class BreakTimeOngoing extends BreakTimeBase implements BreakTime, BreakTimeUpdate { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nonnull + private OffsetDateTime start; + + public BreakTimeOngoing() { + + } + + public BreakTimeOngoing start(@jakarta.annotation.Nonnull OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nonnull OffsetDateTime start) { + this.start = start; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BreakTimeOngoing breakTimeOngoing = (BreakTimeOngoing) o; + return Objects.equals(this.start, breakTimeOngoing.start) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BreakTimeOngoing {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeType.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeType.java new file mode 100644 index 0000000..18201c7 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeType.java @@ -0,0 +1,62 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Kind of break. `manual` was entered by the user, `automatic` was deducted by timr, `ongoing` is a break that has started and not yet ended. + */ +public enum BreakTimeType { + + MANUAL("manual"), + + ONGOING("ongoing"), + + AUTOMATIC("automatic"); + + private String value; + + BreakTimeType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static BreakTimeType fromValue(String value) { + for (BreakTimeType b : BreakTimeType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeUpdate.java new file mode 100644 index 0000000..6385cf5 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BreakTimeUpdate.java @@ -0,0 +1,51 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeManual; +import com.timr.api.models.BreakTimeOngoing; +import com.timr.api.models.BreakTimeType; +import java.time.OffsetDateTime; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@JsonIgnoreProperties( + value = "type", // ignore manually set type, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the type to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = BreakTimeManual.class, name = "manual"), + @JsonSubTypes.Type(value = BreakTimeOngoing.class, name = "ongoing"), +}) + +public interface BreakTimeUpdate { + public BreakTimeType getType(); +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/BudgetPlanningType.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BudgetPlanningType.java new file mode 100644 index 0000000..99511fb --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BudgetPlanningType.java @@ -0,0 +1,64 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set for the remaining two types all budget properties are supported + */ +public enum BudgetPlanningType { + + NONE("none"), + + TASK_HOURLY_RATE("task_hourly_rate"), + + USER_HOURLY_RATE("user_hourly_rate"), + + FIXED_PRICE("fixed_price"); + + private String value; + + BudgetPlanningType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static BudgetPlanningType fromValue(String value) { + for (BudgetPlanningType b : BudgetPlanningType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/BudgetPlanningTypeRequest.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BudgetPlanningTypeRequest.java new file mode 100644 index 0000000..794925f --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/BudgetPlanningTypeRequest.java @@ -0,0 +1,66 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set * inherited: budget settings are inherited from the parent task for the remaining two types all budget properties are supported + */ +public enum BudgetPlanningTypeRequest { + + NONE("none"), + + TASK_HOURLY_RATE("task_hourly_rate"), + + USER_HOURLY_RATE("user_hourly_rate"), + + FIXED_PRICE("fixed_price"), + + INHERITED("inherited"); + + private String value; + + BudgetPlanningTypeRequest(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static BudgetPlanningTypeRequest fromValue(String value) { + for (BudgetPlanningTypeRequest b : BudgetPlanningTypeRequest.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Car.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Car.java new file mode 100644 index 0000000..2b23afb --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Car.java @@ -0,0 +1,294 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A vehicle identified by `name` and license `plate`. `usable` says whether it can currently be selected. + */ +@JsonPropertyOrder({ + Car.JSON_PROPERTY_ID, + Car.JSON_PROPERTY_NAME, + Car.JSON_PROPERTY_PLATE, + Car.JSON_PROPERTY_EXTERNAL_ID, + Car.JSON_PROPERTY_USABLE, + Car.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Car { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_PLATE = "plate"; + @jakarta.annotation.Nonnull + private String plate; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public static final String JSON_PROPERTY_USABLE = "usable"; + @jakarta.annotation.Nonnull + private Boolean usable; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public Car() { + } + + public Car id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public Car name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public Car plate(@jakarta.annotation.Nonnull String plate) { + + this.plate = plate; + return this; + } + + /** + * Get plate + * @return plate + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getPlate() { + return plate; + } + + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPlate(@jakarta.annotation.Nonnull String plate) { + this.plate = plate; + } + + + public Car externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + public Car usable(@jakarta.annotation.Nonnull Boolean usable) { + + this.usable = usable; + return this; + } + + /** + * Get usable + * @return usable + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getUsable() { + return usable; + } + + + @JsonProperty(value = JSON_PROPERTY_USABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUsable(@jakarta.annotation.Nonnull Boolean usable) { + this.usable = usable; + } + + + public Car metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public Car putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Car car = (Car) o; + return Objects.equals(this.id, car.id) && + Objects.equals(this.name, car.name) && + Objects.equals(this.plate, car.plate) && + Objects.equals(this.externalId, car.externalId) && + Objects.equals(this.usable, car.usable) && + equalsNullable(this.metadata, car.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, plate, externalId, usable, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Car {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" usable: ").append(toIndentedString(usable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarCreate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarCreate.java new file mode 100644 index 0000000..15cfe12 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarCreate.java @@ -0,0 +1,257 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * CarCreate + */ +@JsonPropertyOrder({ + CarCreate.JSON_PROPERTY_NAME, + CarCreate.JSON_PROPERTY_PLATE, + CarCreate.JSON_PROPERTY_EXTERNAL_ID, + CarCreate.JSON_PROPERTY_USABLE, + CarCreate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class CarCreate { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_PLATE = "plate"; + @jakarta.annotation.Nonnull + private String plate; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private JsonNullable externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_USABLE = "usable"; + @jakarta.annotation.Nullable + private JsonNullable usable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public CarCreate() { + } + + public CarCreate name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public CarCreate plate(@jakarta.annotation.Nonnull String plate) { + + this.plate = plate; + return this; + } + + /** + * Get plate + * @return plate + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getPlate() { + return plate; + } + + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPlate(@jakarta.annotation.Nonnull String plate) { + this.plate = plate; + } + + + public CarCreate externalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public CarCreate usable(@jakarta.annotation.Nullable Boolean usable) { + this.usable = JsonNullable.of(usable); + + return this; + } + + /** + * Get usable + * @return usable + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_USABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getUsable() { + return usable; + } + + @JsonProperty(JSON_PROPERTY_USABLE) + public void setUsable(JsonNullable usable) { + this.usable = usable; + } + + + + public CarCreate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public CarCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CarCreate carCreate = (CarCreate) o; + return Objects.equals(this.name, carCreate.name) && + Objects.equals(this.plate, carCreate.plate) && + equalsNullable(this.externalId, carCreate.externalId) && + equalsNullable(this.usable, carCreate.usable) && + equalsNullable(this.metadata, carCreate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(name, plate, hashCodeNullable(externalId), hashCodeNullable(usable), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CarCreate {\n"); + sb.append(" usable: ").append(toIndentedString(usable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarPartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarPartial.java new file mode 100644 index 0000000..a610135 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarPartial.java @@ -0,0 +1,213 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * CarPartial + */ +@JsonPropertyOrder({ + CarPartial.JSON_PROPERTY_ID, + CarPartial.JSON_PROPERTY_NAME, + CarPartial.JSON_PROPERTY_PLATE, + CarPartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class CarPartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_PLATE = "plate"; + @jakarta.annotation.Nonnull + private String plate; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public CarPartial() { + } + + public CarPartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public CarPartial name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public CarPartial plate(@jakarta.annotation.Nonnull String plate) { + + this.plate = plate; + return this; + } + + /** + * Get plate + * @return plate + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getPlate() { + return plate; + } + + + @JsonProperty(value = JSON_PROPERTY_PLATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPlate(@jakarta.annotation.Nonnull String plate) { + this.plate = plate; + } + + + public CarPartial externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CarPartial carPartial = (CarPartial) o; + return Objects.equals(this.id, carPartial.id) && + Objects.equals(this.name, carPartial.name) && + Objects.equals(this.plate, carPartial.plate) && + Objects.equals(this.externalId, carPartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, plate, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CarPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarUpdate.java new file mode 100644 index 0000000..e137034 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarUpdate.java @@ -0,0 +1,253 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * CarUpdate + */ +@JsonPropertyOrder({ + CarUpdate.JSON_PROPERTY_NAME, + CarUpdate.JSON_PROPERTY_PLATE, + CarUpdate.JSON_PROPERTY_EXTERNAL_ID, + CarUpdate.JSON_PROPERTY_USABLE, + CarUpdate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class CarUpdate { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private JsonNullable name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PLATE = "plate"; + @jakarta.annotation.Nullable + private JsonNullable plate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private JsonNullable externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_USABLE = "usable"; + @jakarta.annotation.Nullable + private JsonNullable usable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public CarUpdate() { + } + + public CarUpdate name(@jakarta.annotation.Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public CarUpdate plate(@jakarta.annotation.Nullable String plate) { + this.plate = JsonNullable.of(plate); + + return this; + } + + /** + * Get plate + * @return plate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PLATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getPlate() { + return plate; + } + + @JsonProperty(JSON_PROPERTY_PLATE) + public void setPlate(JsonNullable plate) { + this.plate = plate; + } + + + + public CarUpdate externalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public CarUpdate usable(@jakarta.annotation.Nullable Boolean usable) { + this.usable = JsonNullable.of(usable); + + return this; + } + + /** + * Get usable + * @return usable + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_USABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getUsable() { + return usable; + } + + @JsonProperty(JSON_PROPERTY_USABLE) + public void setUsable(JsonNullable usable) { + this.usable = usable; + } + + + + public CarUpdate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public CarUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CarUpdate carUpdate = (CarUpdate) o; + return equalsNullable(this.name, carUpdate.name) && + equalsNullable(this.plate, carUpdate.plate) && + equalsNullable(this.externalId, carUpdate.externalId) && + equalsNullable(this.usable, carUpdate.usable) && + equalsNullable(this.metadata, carUpdate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(name), hashCodeNullable(plate), hashCodeNullable(externalId), hashCodeNullable(usable), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CarUpdate {\n"); + sb.append(" usable: ").append(toIndentedString(usable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarsPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarsPage.java new file mode 100644 index 0000000..44de3de --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarsPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.Car; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * CarsPage + */ +@JsonPropertyOrder({ + CarsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + CarsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class CarsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public CarsPage() { + } + + public CarsPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public CarsPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public CarsPage addDataItem(Car dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CarsPage carsPage = (CarsPage) o; + return Objects.equals(this.nextPageToken, carsPage.nextPageToken) && + Objects.equals(this.data, carsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CarsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarsSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarsSortColumn.java new file mode 100644 index 0000000..8b0d5dc --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/CarsSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Cars. + */ +public enum CarsSortColumn { + + NAME("name"); + + private String value; + + CarsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static CarsSortColumn fromValue(String value) { + for (CarsSortColumn b : CarsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DailyWorkSchedule.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DailyWorkSchedule.java new file mode 100644 index 0000000..041341e --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DailyWorkSchedule.java @@ -0,0 +1,163 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.NormalWorkingTimes; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DailyWorkSchedule + */ +@JsonPropertyOrder({ + DailyWorkSchedule.JSON_PROPERTY_TARGET_DURATION_MINUTES, + DailyWorkSchedule.JSON_PROPERTY_NORMAL_WORKING_TIMES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DailyWorkSchedule { + public static final String JSON_PROPERTY_TARGET_DURATION_MINUTES = "target_duration_minutes"; + @jakarta.annotation.Nonnull + private Long targetDurationMinutes; + + public static final String JSON_PROPERTY_NORMAL_WORKING_TIMES = "normal_working_times"; + @jakarta.annotation.Nullable + private JsonNullable> normalWorkingTimes = JsonNullable.>undefined(); + + public DailyWorkSchedule() { + } + + public DailyWorkSchedule targetDurationMinutes(@jakarta.annotation.Nonnull Long targetDurationMinutes) { + + this.targetDurationMinutes = targetDurationMinutes; + return this; + } + + /** + * value in minutes + * @return targetDurationMinutes + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TARGET_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getTargetDurationMinutes() { + return targetDurationMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_TARGET_DURATION_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTargetDurationMinutes(@jakarta.annotation.Nonnull Long targetDurationMinutes) { + this.targetDurationMinutes = targetDurationMinutes; + } + + + public DailyWorkSchedule normalWorkingTimes(@jakarta.annotation.Nullable List normalWorkingTimes) { + this.normalWorkingTimes = JsonNullable.>of(normalWorkingTimes); + + return this; + } + + public DailyWorkSchedule addNormalWorkingTimesItem(NormalWorkingTimes normalWorkingTimesItem) { + if (this.normalWorkingTimes == null || !this.normalWorkingTimes.isPresent()) { + this.normalWorkingTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.normalWorkingTimes.get().add(normalWorkingTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set + * @return normalWorkingTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NORMAL_WORKING_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getNormalWorkingTimes() { + return normalWorkingTimes; + } + + @JsonProperty(JSON_PROPERTY_NORMAL_WORKING_TIMES) + public void setNormalWorkingTimes(JsonNullable> normalWorkingTimes) { + this.normalWorkingTimes = normalWorkingTimes; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DailyWorkSchedule dailyWorkSchedule = (DailyWorkSchedule) o; + return Objects.equals(this.targetDurationMinutes, dailyWorkSchedule.targetDurationMinutes) && + equalsNullable(this.normalWorkingTimes, dailyWorkSchedule.normalWorkingTimes); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(targetDurationMinutes, hashCodeNullable(normalWorkingTimes)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DailyWorkSchedule {\n"); + sb.append(" normalWorkingTimes: ").append(toIndentedString(normalWorkingTimes)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryPage.java new file mode 100644 index 0000000..67914e5 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DeletedEntryPartial; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DeletedEntryPage + */ +@JsonPropertyOrder({ + DeletedEntryPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + DeletedEntryPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DeletedEntryPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public DeletedEntryPage() { + } + + public DeletedEntryPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public DeletedEntryPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public DeletedEntryPage addDataItem(DeletedEntryPartial dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeletedEntryPage deletedEntryPage = (DeletedEntryPage) o; + return Objects.equals(this.nextPageToken, deletedEntryPage.nextPageToken) && + Objects.equals(this.data, deletedEntryPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeletedEntryPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryPartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryPartial.java new file mode 100644 index 0000000..cb4035b --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryPartial.java @@ -0,0 +1,185 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import java.time.OffsetDateTime; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DeletedEntryPartial + */ +@JsonPropertyOrder({ + DeletedEntryPartial.JSON_PROPERTY_ID, + DeletedEntryPartial.JSON_PROPERTY_LAST_MODIFIED, + DeletedEntryPartial.JSON_PROPERTY_LAST_MODIFIED_BY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DeletedEntryPartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + @jakarta.annotation.Nonnull + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + @jakarta.annotation.Nullable + private UserPartial lastModifiedBy; + + public DeletedEntryPartial() { + } + + public DeletedEntryPartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public DeletedEntryPartial lastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public DeletedEntryPartial lastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeletedEntryPartial deletedEntryPartial = (DeletedEntryPartial) o; + return Objects.equals(this.id, deletedEntryPartial.id) && + Objects.equals(this.lastModified, deletedEntryPartial.lastModified) && + Objects.equals(this.lastModifiedBy, deletedEntryPartial.lastModifiedBy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, lastModified, lastModifiedBy); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeletedEntryPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" lastModified: ").append(toIndentedString(lastModified)).append("\n"); + sb.append(" lastModifiedBy: ").append(toIndentedString(lastModifiedBy)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntrySortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntrySortColumn.java new file mode 100644 index 0000000..06f1a0d --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntrySortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for deleted entries. + */ +public enum DeletedEntrySortColumn { + + LAST_MODIFIED("last_modified"); + + private String value; + + DeletedEntrySortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DeletedEntrySortColumn fromValue(String value) { + for (DeletedEntrySortColumn b : DeletedEntrySortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryWithMetadata.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryWithMetadata.java new file mode 100644 index 0000000..71976f1 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryWithMetadata.java @@ -0,0 +1,233 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DeletedEntryWithMetadata + */ +@JsonPropertyOrder({ + DeletedEntryWithMetadata.JSON_PROPERTY_ID, + DeletedEntryWithMetadata.JSON_PROPERTY_LAST_MODIFIED, + DeletedEntryWithMetadata.JSON_PROPERTY_LAST_MODIFIED_BY, + DeletedEntryWithMetadata.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DeletedEntryWithMetadata { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + @jakarta.annotation.Nonnull + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + @jakarta.annotation.Nullable + private UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public DeletedEntryWithMetadata() { + } + + public DeletedEntryWithMetadata id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public DeletedEntryWithMetadata lastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public DeletedEntryWithMetadata lastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public DeletedEntryWithMetadata metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DeletedEntryWithMetadata putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeletedEntryWithMetadata deletedEntryWithMetadata = (DeletedEntryWithMetadata) o; + return Objects.equals(this.id, deletedEntryWithMetadata.id) && + Objects.equals(this.lastModified, deletedEntryWithMetadata.lastModified) && + Objects.equals(this.lastModifiedBy, deletedEntryWithMetadata.lastModifiedBy) && + equalsNullable(this.metadata, deletedEntryWithMetadata.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, lastModified, lastModifiedBy, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeletedEntryWithMetadata {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" lastModified: ").append(toIndentedString(lastModified)).append("\n"); + sb.append(" lastModifiedBy: ").append(toIndentedString(lastModifiedBy)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryWithMetadataPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryWithMetadataPage.java new file mode 100644 index 0000000..b7d3e7d --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DeletedEntryWithMetadataPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DeletedEntryWithMetadata; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DeletedEntryWithMetadataPage + */ +@JsonPropertyOrder({ + DeletedEntryWithMetadataPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + DeletedEntryWithMetadataPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DeletedEntryWithMetadataPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public DeletedEntryWithMetadataPage() { + } + + public DeletedEntryWithMetadataPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public DeletedEntryWithMetadataPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public DeletedEntryWithMetadataPage addDataItem(DeletedEntryWithMetadata dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeletedEntryWithMetadataPage deletedEntryWithMetadataPage = (DeletedEntryWithMetadataPage) o; + return Objects.equals(this.nextPageToken, deletedEntryWithMetadataPage.nextPageToken) && + Objects.equals(this.data, deletedEntryWithMetadataPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeletedEntryWithMetadataPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLog.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLog.java new file mode 100644 index 0000000..3fd99be --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLog.java @@ -0,0 +1,921 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.CarPartial; +import com.timr.api.models.DriveLogCategoryPartial; +import com.timr.api.models.DriveLogStatus; +import com.timr.api.models.Duration; +import com.timr.api.models.Location; +import com.timr.api.models.Platform; +import com.timr.api.models.UserPartial; +import com.timr.api.models.VenuePartial; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * One trip in a `car`: `start` and `end`, `start_mileage` and `end_mileage` with the resulting `distance`, the `purpose`, the places `visited`, and its `drive_log_category`. May include a recorded GPS `route`. + */ +@JsonPropertyOrder({ + DriveLog.JSON_PROPERTY_ID, + DriveLog.JSON_PROPERTY_START, + DriveLog.JSON_PROPERTY_END, + DriveLog.JSON_PROPERTY_DURATION, + DriveLog.JSON_PROPERTY_CHANGED, + DriveLog.JSON_PROPERTY_START_MILEAGE, + DriveLog.JSON_PROPERTY_END_MILEAGE, + DriveLog.JSON_PROPERTY_DISTANCE, + DriveLog.JSON_PROPERTY_ROUTE, + DriveLog.JSON_PROPERTY_PURPOSE, + DriveLog.JSON_PROPERTY_VISITED, + DriveLog.JSON_PROPERTY_USER, + DriveLog.JSON_PROPERTY_CAR, + DriveLog.JSON_PROPERTY_DRIVE_LOG_CATEGORY, + DriveLog.JSON_PROPERTY_START_VENUE, + DriveLog.JSON_PROPERTY_END_VENUE, + DriveLog.JSON_PROPERTY_HAS_TRACK, + DriveLog.JSON_PROPERTY_START_LOCATION, + DriveLog.JSON_PROPERTY_END_LOCATION, + DriveLog.JSON_PROPERTY_START_PLATFORM, + DriveLog.JSON_PROPERTY_END_PLATFORM, + DriveLog.JSON_PROPERTY_LAST_MODIFIED, + DriveLog.JSON_PROPERTY_LAST_MODIFIED_BY, + DriveLog.JSON_PROPERTY_STATUS, + DriveLog.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLog { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nonnull + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private OffsetDateTime end; + + public static final String JSON_PROPERTY_DURATION = "duration"; + @jakarta.annotation.Nullable + private Duration duration; + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nonnull + private Boolean changed; + + public static final String JSON_PROPERTY_START_MILEAGE = "start_mileage"; + @jakarta.annotation.Nonnull + private Long startMileage; + + public static final String JSON_PROPERTY_END_MILEAGE = "end_mileage"; + @jakarta.annotation.Nullable + private Long endMileage; + + public static final String JSON_PROPERTY_DISTANCE = "distance"; + @jakarta.annotation.Nullable + private Long distance; + + public static final String JSON_PROPERTY_ROUTE = "route"; + @jakarta.annotation.Nullable + private String route; + + public static final String JSON_PROPERTY_PURPOSE = "purpose"; + @jakarta.annotation.Nullable + private String purpose; + + public static final String JSON_PROPERTY_VISITED = "visited"; + @jakarta.annotation.Nullable + private String visited; + + public static final String JSON_PROPERTY_USER = "user"; + @jakarta.annotation.Nonnull + private UserPartial user; + + public static final String JSON_PROPERTY_CAR = "car"; + @jakarta.annotation.Nonnull + private CarPartial car; + + public static final String JSON_PROPERTY_DRIVE_LOG_CATEGORY = "drive_log_category"; + @jakarta.annotation.Nonnull + private DriveLogCategoryPartial driveLogCategory; + + public static final String JSON_PROPERTY_START_VENUE = "start_venue"; + @jakarta.annotation.Nullable + private VenuePartial startVenue; + + public static final String JSON_PROPERTY_END_VENUE = "end_venue"; + @jakarta.annotation.Nullable + private VenuePartial endVenue; + + public static final String JSON_PROPERTY_HAS_TRACK = "has_track"; + @jakarta.annotation.Nonnull + private Boolean hasTrack; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + @jakarta.annotation.Nullable + private Location startLocation; + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + @jakarta.annotation.Nullable + private Location endLocation; + + public static final String JSON_PROPERTY_START_PLATFORM = "start_platform"; + @jakarta.annotation.Nullable + private Platform startPlatform; + + public static final String JSON_PROPERTY_END_PLATFORM = "end_platform"; + @jakarta.annotation.Nullable + private Platform endPlatform; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + @jakarta.annotation.Nonnull + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + @jakarta.annotation.Nullable + private UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private DriveLogStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public DriveLog() { + } + + public DriveLog id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public DriveLog start(@jakarta.annotation.Nonnull OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nonnull OffsetDateTime start) { + this.start = start; + } + + + public DriveLog end(@jakarta.annotation.Nullable OffsetDateTime end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = end; + } + + + public DriveLog duration(@jakarta.annotation.Nullable Duration duration) { + + this.duration = duration; + return this; + } + + /** + * Get duration + * @return duration + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Duration getDuration() { + return duration; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDuration(@jakarta.annotation.Nullable Duration duration) { + this.duration = duration; + } + + + public DriveLog changed(@jakarta.annotation.Nonnull Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(@jakarta.annotation.Nonnull Boolean changed) { + this.changed = changed; + } + + + public DriveLog startMileage(@jakarta.annotation.Nonnull Long startMileage) { + + this.startMileage = startMileage; + return this; + } + + /** + * Get startMileage + * @return startMileage + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getStartMileage() { + return startMileage; + } + + + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartMileage(@jakarta.annotation.Nonnull Long startMileage) { + this.startMileage = startMileage; + } + + + public DriveLog endMileage(@jakarta.annotation.Nullable Long endMileage) { + + this.endMileage = endMileage; + return this; + } + + /** + * Get endMileage + * @return endMileage + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getEndMileage() { + return endMileage; + } + + + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndMileage(@jakarta.annotation.Nullable Long endMileage) { + this.endMileage = endMileage; + } + + + public DriveLog distance(@jakarta.annotation.Nullable Long distance) { + + this.distance = distance; + return this; + } + + /** + * Driven distance in kilometers + * @return distance + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DISTANCE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getDistance() { + return distance; + } + + + @JsonProperty(value = JSON_PROPERTY_DISTANCE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDistance(@jakarta.annotation.Nullable Long distance) { + this.distance = distance; + } + + + public DriveLog route(@jakarta.annotation.Nullable String route) { + + this.route = route; + return this; + } + + /** + * Get route + * @return route + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getRoute() { + return route; + } + + + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRoute(@jakarta.annotation.Nullable String route) { + this.route = route; + } + + + public DriveLog purpose(@jakarta.annotation.Nullable String purpose) { + + this.purpose = purpose; + return this; + } + + /** + * Get purpose + * @return purpose + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getPurpose() { + return purpose; + } + + + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPurpose(@jakarta.annotation.Nullable String purpose) { + this.purpose = purpose; + } + + + public DriveLog visited(@jakarta.annotation.Nullable String visited) { + + this.visited = visited; + return this; + } + + /** + * Get visited + * @return visited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getVisited() { + return visited; + } + + + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setVisited(@jakarta.annotation.Nullable String visited) { + this.visited = visited; + } + + + public DriveLog user(@jakarta.annotation.Nonnull UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(@jakarta.annotation.Nonnull UserPartial user) { + this.user = user; + } + + + public DriveLog car(@jakarta.annotation.Nonnull CarPartial car) { + + this.car = car; + return this; + } + + /** + * Get car + * @return car + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CAR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public CarPartial getCar() { + return car; + } + + + @JsonProperty(value = JSON_PROPERTY_CAR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCar(@jakarta.annotation.Nonnull CarPartial car) { + this.car = car; + } + + + public DriveLog driveLogCategory(@jakarta.annotation.Nonnull DriveLogCategoryPartial driveLogCategory) { + + this.driveLogCategory = driveLogCategory; + return this; + } + + /** + * Get driveLogCategory + * @return driveLogCategory + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DriveLogCategoryPartial getDriveLogCategory() { + return driveLogCategory; + } + + + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDriveLogCategory(@jakarta.annotation.Nonnull DriveLogCategoryPartial driveLogCategory) { + this.driveLogCategory = driveLogCategory; + } + + + public DriveLog startVenue(@jakarta.annotation.Nullable VenuePartial startVenue) { + + this.startVenue = startVenue; + return this; + } + + /** + * Get startVenue + * @return startVenue + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_VENUE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public VenuePartial getStartVenue() { + return startVenue; + } + + + @JsonProperty(value = JSON_PROPERTY_START_VENUE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartVenue(@jakarta.annotation.Nullable VenuePartial startVenue) { + this.startVenue = startVenue; + } + + + public DriveLog endVenue(@jakarta.annotation.Nullable VenuePartial endVenue) { + + this.endVenue = endVenue; + return this; + } + + /** + * Get endVenue + * @return endVenue + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_VENUE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public VenuePartial getEndVenue() { + return endVenue; + } + + + @JsonProperty(value = JSON_PROPERTY_END_VENUE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndVenue(@jakarta.annotation.Nullable VenuePartial endVenue) { + this.endVenue = endVenue; + } + + + public DriveLog hasTrack(@jakarta.annotation.Nonnull Boolean hasTrack) { + + this.hasTrack = hasTrack; + return this; + } + + /** + * Get hasTrack + * @return hasTrack + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_HAS_TRACK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getHasTrack() { + return hasTrack; + } + + + @JsonProperty(value = JSON_PROPERTY_HAS_TRACK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setHasTrack(@jakarta.annotation.Nonnull Boolean hasTrack) { + this.hasTrack = hasTrack; + } + + + public DriveLog startLocation(@jakarta.annotation.Nullable Location startLocation) { + + this.startLocation = startLocation; + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Location getStartLocation() { + return startLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartLocation(@jakarta.annotation.Nullable Location startLocation) { + this.startLocation = startLocation; + } + + + public DriveLog endLocation(@jakarta.annotation.Nullable Location endLocation) { + + this.endLocation = endLocation; + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Location getEndLocation() { + return endLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndLocation(@jakarta.annotation.Nullable Location endLocation) { + this.endLocation = endLocation; + } + + + public DriveLog startPlatform(@jakarta.annotation.Nullable Platform startPlatform) { + + this.startPlatform = startPlatform; + return this; + } + + /** + * Get startPlatform + * @return startPlatform + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Platform getStartPlatform() { + return startPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartPlatform(@jakarta.annotation.Nullable Platform startPlatform) { + this.startPlatform = startPlatform; + } + + + public DriveLog endPlatform(@jakarta.annotation.Nullable Platform endPlatform) { + + this.endPlatform = endPlatform; + return this; + } + + /** + * Get endPlatform + * @return endPlatform + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Platform getEndPlatform() { + return endPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndPlatform(@jakarta.annotation.Nullable Platform endPlatform) { + this.endPlatform = endPlatform; + } + + + public DriveLog lastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public DriveLog lastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public DriveLog status(@jakarta.annotation.Nonnull DriveLogStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DriveLogStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull DriveLogStatus status) { + this.status = status; + } + + + public DriveLog metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DriveLog putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLog driveLog = (DriveLog) o; + return Objects.equals(this.id, driveLog.id) && + Objects.equals(this.start, driveLog.start) && + Objects.equals(this.end, driveLog.end) && + Objects.equals(this.duration, driveLog.duration) && + Objects.equals(this.changed, driveLog.changed) && + Objects.equals(this.startMileage, driveLog.startMileage) && + Objects.equals(this.endMileage, driveLog.endMileage) && + Objects.equals(this.distance, driveLog.distance) && + Objects.equals(this.route, driveLog.route) && + Objects.equals(this.purpose, driveLog.purpose) && + Objects.equals(this.visited, driveLog.visited) && + Objects.equals(this.user, driveLog.user) && + Objects.equals(this.car, driveLog.car) && + Objects.equals(this.driveLogCategory, driveLog.driveLogCategory) && + Objects.equals(this.startVenue, driveLog.startVenue) && + Objects.equals(this.endVenue, driveLog.endVenue) && + Objects.equals(this.hasTrack, driveLog.hasTrack) && + Objects.equals(this.startLocation, driveLog.startLocation) && + Objects.equals(this.endLocation, driveLog.endLocation) && + Objects.equals(this.startPlatform, driveLog.startPlatform) && + Objects.equals(this.endPlatform, driveLog.endPlatform) && + Objects.equals(this.lastModified, driveLog.lastModified) && + Objects.equals(this.lastModifiedBy, driveLog.lastModifiedBy) && + Objects.equals(this.status, driveLog.status) && + equalsNullable(this.metadata, driveLog.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, start, end, duration, changed, startMileage, endMileage, distance, route, purpose, visited, user, car, driveLogCategory, startVenue, endVenue, hasTrack, startLocation, endLocation, startPlatform, endPlatform, lastModified, lastModifiedBy, status, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLog {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" startMileage: ").append(toIndentedString(startMileage)).append("\n"); + sb.append(" endMileage: ").append(toIndentedString(endMileage)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" car: ").append(toIndentedString(car)).append("\n"); + sb.append(" driveLogCategory: ").append(toIndentedString(driveLogCategory)).append("\n"); + sb.append(" startVenue: ").append(toIndentedString(startVenue)).append("\n"); + sb.append(" endVenue: ").append(toIndentedString(endVenue)).append("\n"); + sb.append(" hasTrack: ").append(toIndentedString(hasTrack)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategoriesPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategoriesPage.java new file mode 100644 index 0000000..b024567 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategoriesPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLogCategory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogCategoriesPage + */ +@JsonPropertyOrder({ + DriveLogCategoriesPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + DriveLogCategoriesPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogCategoriesPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public DriveLogCategoriesPage() { + } + + public DriveLogCategoriesPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public DriveLogCategoriesPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public DriveLogCategoriesPage addDataItem(DriveLogCategory dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogCategoriesPage driveLogCategoriesPage = (DriveLogCategoriesPage) o; + return Objects.equals(this.nextPageToken, driveLogCategoriesPage.nextPageToken) && + Objects.equals(this.data, driveLogCategoriesPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogCategoriesPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategoriesSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategoriesSortColumn.java new file mode 100644 index 0000000..b784e7d --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategoriesSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Drive Log Categories. + */ +public enum DriveLogCategoriesSortColumn { + + NAME("name"); + + private String value; + + DriveLogCategoriesSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DriveLogCategoriesSortColumn fromValue(String value) { + for (DriveLogCategoriesSortColumn b : DriveLogCategoriesSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategory.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategory.java new file mode 100644 index 0000000..f6c0239 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategory.java @@ -0,0 +1,280 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import java.time.OffsetDateTime; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A drive log category with a `name` and a display `color`; `business` marks it as business travel. + */ +@JsonPropertyOrder({ + DriveLogCategory.JSON_PROPERTY_ID, + DriveLogCategory.JSON_PROPERTY_NAME, + DriveLogCategory.JSON_PROPERTY_BUSINESS, + DriveLogCategory.JSON_PROPERTY_COLOR, + DriveLogCategory.JSON_PROPERTY_LAST_MODIFIED, + DriveLogCategory.JSON_PROPERTY_LAST_MODIFIED_BY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogCategory { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_BUSINESS = "business"; + @jakarta.annotation.Nonnull + private Boolean business; + + public static final String JSON_PROPERTY_COLOR = "color"; + @jakarta.annotation.Nonnull + private String color; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + @jakarta.annotation.Nonnull + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + @jakarta.annotation.Nullable + private UserPartial lastModifiedBy; + + public DriveLogCategory() { + } + + public DriveLogCategory id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public DriveLogCategory name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public DriveLogCategory business(@jakarta.annotation.Nonnull Boolean business) { + + this.business = business; + return this; + } + + /** + * Get business + * @return business + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BUSINESS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBusiness() { + return business; + } + + + @JsonProperty(value = JSON_PROPERTY_BUSINESS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBusiness(@jakarta.annotation.Nonnull Boolean business) { + this.business = business; + } + + + public DriveLogCategory color(@jakarta.annotation.Nonnull String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_COLOR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getColor() { + return color; + } + + + @JsonProperty(value = JSON_PROPERTY_COLOR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setColor(@jakarta.annotation.Nonnull String color) { + this.color = color; + } + + + public DriveLogCategory lastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public DriveLogCategory lastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogCategory driveLogCategory = (DriveLogCategory) o; + return Objects.equals(this.id, driveLogCategory.id) && + Objects.equals(this.name, driveLogCategory.name) && + Objects.equals(this.business, driveLogCategory.business) && + Objects.equals(this.color, driveLogCategory.color) && + Objects.equals(this.lastModified, driveLogCategory.lastModified) && + Objects.equals(this.lastModifiedBy, driveLogCategory.lastModifiedBy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, business, color, lastModified, lastModifiedBy); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogCategory {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" business: ").append(toIndentedString(business)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategoryPartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategoryPartial.java new file mode 100644 index 0000000..fcdf87d --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCategoryPartial.java @@ -0,0 +1,214 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogCategoryPartial + */ +@JsonPropertyOrder({ + DriveLogCategoryPartial.JSON_PROPERTY_ID, + DriveLogCategoryPartial.JSON_PROPERTY_NAME, + DriveLogCategoryPartial.JSON_PROPERTY_BUSINESS, + DriveLogCategoryPartial.JSON_PROPERTY_COLOR +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogCategoryPartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_BUSINESS = "business"; + @jakarta.annotation.Nonnull + private Boolean business; + + public static final String JSON_PROPERTY_COLOR = "color"; + @jakarta.annotation.Nonnull + private String color; + + public DriveLogCategoryPartial() { + } + + public DriveLogCategoryPartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public DriveLogCategoryPartial name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public DriveLogCategoryPartial business(@jakarta.annotation.Nonnull Boolean business) { + + this.business = business; + return this; + } + + /** + * Get business + * @return business + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BUSINESS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBusiness() { + return business; + } + + + @JsonProperty(value = JSON_PROPERTY_BUSINESS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBusiness(@jakarta.annotation.Nonnull Boolean business) { + this.business = business; + } + + + public DriveLogCategoryPartial color(@jakarta.annotation.Nonnull String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_COLOR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getColor() { + return color; + } + + + @JsonProperty(value = JSON_PROPERTY_COLOR, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setColor(@jakarta.annotation.Nonnull String color) { + this.color = color; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogCategoryPartial driveLogCategoryPartial = (DriveLogCategoryPartial) o; + return Objects.equals(this.id, driveLogCategoryPartial.id) && + Objects.equals(this.name, driveLogCategoryPartial.name) && + Objects.equals(this.business, driveLogCategoryPartial.business) && + Objects.equals(this.color, driveLogCategoryPartial.color); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, business, color); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogCategoryPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" business: ").append(toIndentedString(business)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCreate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCreate.java new file mode 100644 index 0000000..a951d62 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogCreate.java @@ -0,0 +1,575 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLogStatus; +import com.timr.api.models.LocationCreate; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogCreate + */ +@JsonPropertyOrder({ + DriveLogCreate.JSON_PROPERTY_START, + DriveLogCreate.JSON_PROPERTY_END, + DriveLogCreate.JSON_PROPERTY_CHANGED, + DriveLogCreate.JSON_PROPERTY_START_MILEAGE, + DriveLogCreate.JSON_PROPERTY_END_MILEAGE, + DriveLogCreate.JSON_PROPERTY_ROUTE, + DriveLogCreate.JSON_PROPERTY_PURPOSE, + DriveLogCreate.JSON_PROPERTY_VISITED, + DriveLogCreate.JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, + DriveLogCreate.JSON_PROPERTY_STATUS, + DriveLogCreate.JSON_PROPERTY_METADATA, + DriveLogCreate.JSON_PROPERTY_USER_ID, + DriveLogCreate.JSON_PROPERTY_CAR_ID, + DriveLogCreate.JSON_PROPERTY_START_LOCATION, + DriveLogCreate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogCreate { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nonnull + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nonnull + private Boolean changed; + + public static final String JSON_PROPERTY_START_MILEAGE = "start_mileage"; + @jakarta.annotation.Nonnull + private Long startMileage; + + public static final String JSON_PROPERTY_END_MILEAGE = "end_mileage"; + @jakarta.annotation.Nullable + private JsonNullable endMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ROUTE = "route"; + @jakarta.annotation.Nullable + private JsonNullable route = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PURPOSE = "purpose"; + @jakarta.annotation.Nullable + private JsonNullable purpose = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_VISITED = "visited"; + @jakarta.annotation.Nullable + private JsonNullable visited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID = "drive_log_category_id"; + @jakarta.annotation.Nonnull + private String driveLogCategoryId; + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private DriveLogStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_USER_ID = "user_id"; + @jakarta.annotation.Nonnull + private String userId; + + public static final String JSON_PROPERTY_CAR_ID = "car_id"; + @jakarta.annotation.Nonnull + private String carId; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + @jakarta.annotation.Nullable + private JsonNullable startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + @jakarta.annotation.Nullable + private JsonNullable endLocation = JsonNullable.undefined(); + + public DriveLogCreate() { + } + + public DriveLogCreate start(@jakarta.annotation.Nonnull OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nonnull OffsetDateTime start) { + this.start = start; + } + + + public DriveLogCreate end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public DriveLogCreate changed(@jakarta.annotation.Nonnull Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(@jakarta.annotation.Nonnull Boolean changed) { + this.changed = changed; + } + + + public DriveLogCreate startMileage(@jakarta.annotation.Nonnull Long startMileage) { + + this.startMileage = startMileage; + return this; + } + + /** + * Get startMileage + * @return startMileage + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getStartMileage() { + return startMileage; + } + + + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartMileage(@jakarta.annotation.Nonnull Long startMileage) { + this.startMileage = startMileage; + } + + + public DriveLogCreate endMileage(@jakarta.annotation.Nullable Long endMileage) { + this.endMileage = JsonNullable.of(endMileage); + + return this; + } + + /** + * Get endMileage + * @return endMileage + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndMileage() { + return endMileage; + } + + @JsonProperty(JSON_PROPERTY_END_MILEAGE) + public void setEndMileage(JsonNullable endMileage) { + this.endMileage = endMileage; + } + + + + public DriveLogCreate route(@jakarta.annotation.Nullable String route) { + this.route = JsonNullable.of(route); + + return this; + } + + /** + * Get route + * @return route + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getRoute() { + return route; + } + + @JsonProperty(JSON_PROPERTY_ROUTE) + public void setRoute(JsonNullable route) { + this.route = route; + } + + + + public DriveLogCreate purpose(@jakarta.annotation.Nullable String purpose) { + this.purpose = JsonNullable.of(purpose); + + return this; + } + + /** + * Get purpose + * @return purpose + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getPurpose() { + return purpose; + } + + @JsonProperty(JSON_PROPERTY_PURPOSE) + public void setPurpose(JsonNullable purpose) { + this.purpose = purpose; + } + + + + public DriveLogCreate visited(@jakarta.annotation.Nullable String visited) { + this.visited = JsonNullable.of(visited); + + return this; + } + + /** + * Get visited + * @return visited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getVisited() { + return visited; + } + + @JsonProperty(JSON_PROPERTY_VISITED) + public void setVisited(JsonNullable visited) { + this.visited = visited; + } + + + + public DriveLogCreate driveLogCategoryId(@jakarta.annotation.Nonnull String driveLogCategoryId) { + + this.driveLogCategoryId = driveLogCategoryId; + return this; + } + + /** + * Get driveLogCategoryId + * @return driveLogCategoryId + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDriveLogCategoryId() { + return driveLogCategoryId; + } + + + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDriveLogCategoryId(@jakarta.annotation.Nonnull String driveLogCategoryId) { + this.driveLogCategoryId = driveLogCategoryId; + } + + + public DriveLogCreate status(@jakarta.annotation.Nonnull DriveLogStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DriveLogStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull DriveLogStatus status) { + this.status = status; + } + + + public DriveLogCreate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DriveLogCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public DriveLogCreate userId(@jakarta.annotation.Nonnull String userId) { + + this.userId = userId; + return this; + } + + /** + * Get userId + * @return userId + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getUserId() { + return userId; + } + + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUserId(@jakarta.annotation.Nonnull String userId) { + this.userId = userId; + } + + + public DriveLogCreate carId(@jakarta.annotation.Nonnull String carId) { + + this.carId = carId; + return this; + } + + /** + * Get carId + * @return carId + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CAR_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCarId() { + return carId; + } + + + @JsonProperty(value = JSON_PROPERTY_CAR_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCarId(@jakarta.annotation.Nonnull String carId) { + this.carId = carId; + } + + + public DriveLogCreate startLocation(@jakarta.annotation.Nullable LocationCreate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public DriveLogCreate endLocation(@jakarta.annotation.Nullable LocationCreate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogCreate driveLogCreate = (DriveLogCreate) o; + return Objects.equals(this.start, driveLogCreate.start) && + equalsNullable(this.end, driveLogCreate.end) && + Objects.equals(this.changed, driveLogCreate.changed) && + Objects.equals(this.startMileage, driveLogCreate.startMileage) && + equalsNullable(this.endMileage, driveLogCreate.endMileage) && + equalsNullable(this.route, driveLogCreate.route) && + equalsNullable(this.purpose, driveLogCreate.purpose) && + equalsNullable(this.visited, driveLogCreate.visited) && + Objects.equals(this.driveLogCategoryId, driveLogCreate.driveLogCategoryId) && + Objects.equals(this.status, driveLogCreate.status) && + equalsNullable(this.metadata, driveLogCreate.metadata) && + Objects.equals(this.userId, driveLogCreate.userId) && + Objects.equals(this.carId, driveLogCreate.carId) && + equalsNullable(this.startLocation, driveLogCreate.startLocation) && + equalsNullable(this.endLocation, driveLogCreate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, hashCodeNullable(end), changed, startMileage, hashCodeNullable(endMileage), hashCodeNullable(route), hashCodeNullable(purpose), hashCodeNullable(visited), driveLogCategoryId, status, hashCodeNullable(metadata), userId, carId, hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogCreate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" driveLogCategoryId: ").append(toIndentedString(driveLogCategoryId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); + sb.append(" carId: ").append(toIndentedString(carId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogStatus.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogStatus.java new file mode 100644 index 0000000..0ca7e9c --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogStatus.java @@ -0,0 +1,70 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Processing state of a Drive Log. `running` means the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + */ +public enum DriveLogStatus { + + CHANGEABLE("changeable"), + + LOCKED("locked"), + + APPROVED("approved"), + + CLEARED("cleared"), + + CLOSED("closed"), + + ARCHIVED("archived"), + + RUNNING("running"); + + private String value; + + DriveLogStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DriveLogStatus fromValue(String value) { + for (DriveLogStatus b : DriveLogStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogUpdate.java new file mode 100644 index 0000000..3babff3 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogUpdate.java @@ -0,0 +1,499 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLogStatus; +import com.timr.api.models.LocationUpdate; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogUpdate + */ +@JsonPropertyOrder({ + DriveLogUpdate.JSON_PROPERTY_START, + DriveLogUpdate.JSON_PROPERTY_END, + DriveLogUpdate.JSON_PROPERTY_CHANGED, + DriveLogUpdate.JSON_PROPERTY_START_MILEAGE, + DriveLogUpdate.JSON_PROPERTY_END_MILEAGE, + DriveLogUpdate.JSON_PROPERTY_ROUTE, + DriveLogUpdate.JSON_PROPERTY_PURPOSE, + DriveLogUpdate.JSON_PROPERTY_VISITED, + DriveLogUpdate.JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, + DriveLogUpdate.JSON_PROPERTY_STATUS, + DriveLogUpdate.JSON_PROPERTY_METADATA, + DriveLogUpdate.JSON_PROPERTY_START_LOCATION, + DriveLogUpdate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogUpdate { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private JsonNullable start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nullable + private JsonNullable changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_MILEAGE = "start_mileage"; + @jakarta.annotation.Nullable + private JsonNullable startMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_MILEAGE = "end_mileage"; + @jakarta.annotation.Nullable + private JsonNullable endMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ROUTE = "route"; + @jakarta.annotation.Nullable + private JsonNullable route = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PURPOSE = "purpose"; + @jakarta.annotation.Nullable + private JsonNullable purpose = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_VISITED = "visited"; + @jakarta.annotation.Nullable + private JsonNullable visited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID = "drive_log_category_id"; + @jakarta.annotation.Nullable + private JsonNullable driveLogCategoryId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nullable + private JsonNullable status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + @jakarta.annotation.Nullable + private JsonNullable startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + @jakarta.annotation.Nullable + private JsonNullable endLocation = JsonNullable.undefined(); + + public DriveLogUpdate() { + } + + public DriveLogUpdate start(@jakarta.annotation.Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public DriveLogUpdate end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public DriveLogUpdate changed(@jakarta.annotation.Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public DriveLogUpdate startMileage(@jakarta.annotation.Nullable Long startMileage) { + this.startMileage = JsonNullable.of(startMileage); + + return this; + } + + /** + * Get startMileage + * @return startMileage + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartMileage() { + return startMileage; + } + + @JsonProperty(JSON_PROPERTY_START_MILEAGE) + public void setStartMileage(JsonNullable startMileage) { + this.startMileage = startMileage; + } + + + + public DriveLogUpdate endMileage(@jakarta.annotation.Nullable Long endMileage) { + this.endMileage = JsonNullable.of(endMileage); + + return this; + } + + /** + * Get endMileage + * @return endMileage + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndMileage() { + return endMileage; + } + + @JsonProperty(JSON_PROPERTY_END_MILEAGE) + public void setEndMileage(JsonNullable endMileage) { + this.endMileage = endMileage; + } + + + + public DriveLogUpdate route(@jakarta.annotation.Nullable String route) { + this.route = JsonNullable.of(route); + + return this; + } + + /** + * Get route + * @return route + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getRoute() { + return route; + } + + @JsonProperty(JSON_PROPERTY_ROUTE) + public void setRoute(JsonNullable route) { + this.route = route; + } + + + + public DriveLogUpdate purpose(@jakarta.annotation.Nullable String purpose) { + this.purpose = JsonNullable.of(purpose); + + return this; + } + + /** + * Get purpose + * @return purpose + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getPurpose() { + return purpose; + } + + @JsonProperty(JSON_PROPERTY_PURPOSE) + public void setPurpose(JsonNullable purpose) { + this.purpose = purpose; + } + + + + public DriveLogUpdate visited(@jakarta.annotation.Nullable String visited) { + this.visited = JsonNullable.of(visited); + + return this; + } + + /** + * Get visited + * @return visited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getVisited() { + return visited; + } + + @JsonProperty(JSON_PROPERTY_VISITED) + public void setVisited(JsonNullable visited) { + this.visited = visited; + } + + + + public DriveLogUpdate driveLogCategoryId(@jakarta.annotation.Nullable String driveLogCategoryId) { + this.driveLogCategoryId = JsonNullable.of(driveLogCategoryId); + + return this; + } + + /** + * Get driveLogCategoryId + * @return driveLogCategoryId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDriveLogCategoryId() { + return driveLogCategoryId; + } + + @JsonProperty(JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID) + public void setDriveLogCategoryId(JsonNullable driveLogCategoryId) { + this.driveLogCategoryId = driveLogCategoryId; + } + + + + public DriveLogUpdate status(@jakarta.annotation.Nullable DriveLogStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public DriveLogUpdate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DriveLogUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public DriveLogUpdate startLocation(@jakarta.annotation.Nullable LocationUpdate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public DriveLogUpdate endLocation(@jakarta.annotation.Nullable LocationUpdate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogUpdate driveLogUpdate = (DriveLogUpdate) o; + return equalsNullable(this.start, driveLogUpdate.start) && + equalsNullable(this.end, driveLogUpdate.end) && + equalsNullable(this.changed, driveLogUpdate.changed) && + equalsNullable(this.startMileage, driveLogUpdate.startMileage) && + equalsNullable(this.endMileage, driveLogUpdate.endMileage) && + equalsNullable(this.route, driveLogUpdate.route) && + equalsNullable(this.purpose, driveLogUpdate.purpose) && + equalsNullable(this.visited, driveLogUpdate.visited) && + equalsNullable(this.driveLogCategoryId, driveLogUpdate.driveLogCategoryId) && + equalsNullable(this.status, driveLogUpdate.status) && + equalsNullable(this.metadata, driveLogUpdate.metadata) && + equalsNullable(this.startLocation, driveLogUpdate.startLocation) && + equalsNullable(this.endLocation, driveLogUpdate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(changed), hashCodeNullable(startMileage), hashCodeNullable(endMileage), hashCodeNullable(route), hashCodeNullable(purpose), hashCodeNullable(visited), hashCodeNullable(driveLogCategoryId), hashCodeNullable(status), hashCodeNullable(metadata), hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogUpdate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" driveLogCategoryId: ").append(toIndentedString(driveLogCategoryId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogUpsert.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogUpsert.java new file mode 100644 index 0000000..1d40b61 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogUpsert.java @@ -0,0 +1,438 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLogStatus; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogUpsert + */ +@JsonPropertyOrder({ + DriveLogUpsert.JSON_PROPERTY_START, + DriveLogUpsert.JSON_PROPERTY_END, + DriveLogUpsert.JSON_PROPERTY_CHANGED, + DriveLogUpsert.JSON_PROPERTY_START_MILEAGE, + DriveLogUpsert.JSON_PROPERTY_END_MILEAGE, + DriveLogUpsert.JSON_PROPERTY_ROUTE, + DriveLogUpsert.JSON_PROPERTY_PURPOSE, + DriveLogUpsert.JSON_PROPERTY_VISITED, + DriveLogUpsert.JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, + DriveLogUpsert.JSON_PROPERTY_STATUS, + DriveLogUpsert.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogUpsert { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private JsonNullable start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nullable + private JsonNullable changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_MILEAGE = "start_mileage"; + @jakarta.annotation.Nullable + private JsonNullable startMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_MILEAGE = "end_mileage"; + @jakarta.annotation.Nullable + private JsonNullable endMileage = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ROUTE = "route"; + @jakarta.annotation.Nullable + private JsonNullable route = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PURPOSE = "purpose"; + @jakarta.annotation.Nullable + private JsonNullable purpose = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_VISITED = "visited"; + @jakarta.annotation.Nullable + private JsonNullable visited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID = "drive_log_category_id"; + @jakarta.annotation.Nullable + private JsonNullable driveLogCategoryId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nullable + private JsonNullable status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public DriveLogUpsert() { + } + + public DriveLogUpsert start(@jakarta.annotation.Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public DriveLogUpsert end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public DriveLogUpsert changed(@jakarta.annotation.Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public DriveLogUpsert startMileage(@jakarta.annotation.Nullable Long startMileage) { + this.startMileage = JsonNullable.of(startMileage); + + return this; + } + + /** + * Get startMileage + * @return startMileage + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartMileage() { + return startMileage; + } + + @JsonProperty(JSON_PROPERTY_START_MILEAGE) + public void setStartMileage(JsonNullable startMileage) { + this.startMileage = startMileage; + } + + + + public DriveLogUpsert endMileage(@jakarta.annotation.Nullable Long endMileage) { + this.endMileage = JsonNullable.of(endMileage); + + return this; + } + + /** + * Get endMileage + * @return endMileage + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_MILEAGE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndMileage() { + return endMileage; + } + + @JsonProperty(JSON_PROPERTY_END_MILEAGE) + public void setEndMileage(JsonNullable endMileage) { + this.endMileage = endMileage; + } + + + + public DriveLogUpsert route(@jakarta.annotation.Nullable String route) { + this.route = JsonNullable.of(route); + + return this; + } + + /** + * Get route + * @return route + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ROUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getRoute() { + return route; + } + + @JsonProperty(JSON_PROPERTY_ROUTE) + public void setRoute(JsonNullable route) { + this.route = route; + } + + + + public DriveLogUpsert purpose(@jakarta.annotation.Nullable String purpose) { + this.purpose = JsonNullable.of(purpose); + + return this; + } + + /** + * Get purpose + * @return purpose + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PURPOSE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getPurpose() { + return purpose; + } + + @JsonProperty(JSON_PROPERTY_PURPOSE) + public void setPurpose(JsonNullable purpose) { + this.purpose = purpose; + } + + + + public DriveLogUpsert visited(@jakarta.annotation.Nullable String visited) { + this.visited = JsonNullable.of(visited); + + return this; + } + + /** + * Get visited + * @return visited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_VISITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getVisited() { + return visited; + } + + @JsonProperty(JSON_PROPERTY_VISITED) + public void setVisited(JsonNullable visited) { + this.visited = visited; + } + + + + public DriveLogUpsert driveLogCategoryId(@jakarta.annotation.Nullable String driveLogCategoryId) { + this.driveLogCategoryId = JsonNullable.of(driveLogCategoryId); + + return this; + } + + /** + * Get driveLogCategoryId + * @return driveLogCategoryId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDriveLogCategoryId() { + return driveLogCategoryId; + } + + @JsonProperty(JSON_PROPERTY_DRIVE_LOG_CATEGORY_ID) + public void setDriveLogCategoryId(JsonNullable driveLogCategoryId) { + this.driveLogCategoryId = driveLogCategoryId; + } + + + + public DriveLogUpsert status(@jakarta.annotation.Nullable DriveLogStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public DriveLogUpsert metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public DriveLogUpsert putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogUpsert driveLogUpsert = (DriveLogUpsert) o; + return equalsNullable(this.start, driveLogUpsert.start) && + equalsNullable(this.end, driveLogUpsert.end) && + equalsNullable(this.changed, driveLogUpsert.changed) && + equalsNullable(this.startMileage, driveLogUpsert.startMileage) && + equalsNullable(this.endMileage, driveLogUpsert.endMileage) && + equalsNullable(this.route, driveLogUpsert.route) && + equalsNullable(this.purpose, driveLogUpsert.purpose) && + equalsNullable(this.visited, driveLogUpsert.visited) && + equalsNullable(this.driveLogCategoryId, driveLogUpsert.driveLogCategoryId) && + equalsNullable(this.status, driveLogUpsert.status) && + equalsNullable(this.metadata, driveLogUpsert.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(changed), hashCodeNullable(startMileage), hashCodeNullable(endMileage), hashCodeNullable(route), hashCodeNullable(purpose), hashCodeNullable(visited), hashCodeNullable(driveLogCategoryId), hashCodeNullable(status), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogUpsert {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" driveLogCategoryId: ").append(toIndentedString(driveLogCategoryId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogsPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogsPage.java new file mode 100644 index 0000000..0d3633f --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogsPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DriveLog; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * DriveLogsPage + */ +@JsonPropertyOrder({ + DriveLogsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + DriveLogsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class DriveLogsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public DriveLogsPage() { + } + + public DriveLogsPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public DriveLogsPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public DriveLogsPage addDataItem(DriveLog dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DriveLogsPage driveLogsPage = (DriveLogsPage) o; + return Objects.equals(this.nextPageToken, driveLogsPage.nextPageToken) && + Objects.equals(this.data, driveLogsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DriveLogsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogsSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogsSortColumn.java new file mode 100644 index 0000000..d5a645e --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DriveLogsSortColumn.java @@ -0,0 +1,60 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Drive Logs. + */ +public enum DriveLogsSortColumn { + + START("start"), + + LAST_MODIFIED("last_modified"); + + private String value; + + DriveLogsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DriveLogsSortColumn fromValue(String value) { + for (DriveLogsSortColumn b : DriveLogsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Duration.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Duration.java new file mode 100644 index 0000000..f7dfe22 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Duration.java @@ -0,0 +1,183 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DurationType; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Duration + */ +@JsonPropertyOrder({ + Duration.JSON_PROPERTY_TYPE, + Duration.JSON_PROPERTY_MINUTES, + Duration.JSON_PROPERTY_MINUTES_ROUNDED +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Duration { + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private DurationType type; + + public static final String JSON_PROPERTY_MINUTES = "minutes"; + @jakarta.annotation.Nonnull + private Long minutes; + + public static final String JSON_PROPERTY_MINUTES_ROUNDED = "minutes_rounded"; + @jakarta.annotation.Nonnull + private Long minutesRounded; + + public Duration() { + } + + public Duration type(@jakarta.annotation.Nonnull DurationType type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DurationType getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull DurationType type) { + this.type = type; + } + + + public Duration minutes(@jakarta.annotation.Nonnull Long minutes) { + + this.minutes = minutes; + return this; + } + + /** + * Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + * @return minutes + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getMinutes() { + return minutes; + } + + + @JsonProperty(value = JSON_PROPERTY_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setMinutes(@jakarta.annotation.Nonnull Long minutes) { + this.minutes = minutes; + } + + + public Duration minutesRounded(@jakarta.annotation.Nonnull Long minutesRounded) { + + this.minutesRounded = minutesRounded; + return this; + } + + /** + * Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + * @return minutesRounded + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_MINUTES_ROUNDED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getMinutesRounded() { + return minutesRounded; + } + + + @JsonProperty(value = JSON_PROPERTY_MINUTES_ROUNDED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setMinutesRounded(@jakarta.annotation.Nonnull Long minutesRounded) { + this.minutesRounded = minutesRounded; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Duration duration = (Duration) o; + return Objects.equals(this.type, duration.type) && + Objects.equals(this.minutes, duration.minutes) && + Objects.equals(this.minutesRounded, duration.minutesRounded); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type, minutes, minutesRounded); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Duration {\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" minutes: ").append(toIndentedString(minutes)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DurationType.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DurationType.java new file mode 100644 index 0000000..fd685e8 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DurationType.java @@ -0,0 +1,62 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * How the duration of a single recording is expressed. Not to be confused with `DurationUnit`, which states the unit a Working Time Type is recorded in. + */ +public enum DurationType { + + MINUTES("minutes"), + + FULL_DAY("full_day"), + + HALF_DAY("half_day"); + + private String value; + + DurationType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DurationType fromValue(String value) { + for (DurationType b : DurationType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/DurationUnit.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DurationUnit.java new file mode 100644 index 0000000..9220899 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/DurationUnit.java @@ -0,0 +1,62 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Unit a Working Time Type is recorded in. Not to be confused with `DurationType`, which states how an individual recording's duration is expressed. + */ +public enum DurationUnit { + + MINUTES("minutes"), + + HALF_DAYS("half_days"), + + DAYS("days"); + + private String value; + + DurationUnit(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static DurationUnit fromValue(String value) { + for (DurationUnit b : DurationUnit.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Error.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Error.java new file mode 100644 index 0000000..749dc55 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Error.java @@ -0,0 +1,354 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.ErrorEntry; +import java.net.URI; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TIMR error response body, extending the Problem Details base with `timestamp`, `trace_id` and per-field `errors[]` for validation, binding, constraint, request-body deserialization, and reference-not-found errors. The semantic identifier is encoded in the `type` URI (e.g. `https://errors.timr.com/conflict/resource-outdated`). Slugs in the `type` URI are lowercase kebab-case: a top-level category (`validation`, `reference-not-found`, `conflict`, `forbidden`, `internal`) optionally followed by a specific sub-slug (`conflict/resource-outdated`, `validation/end-time-required`, `reference-not-found/user`). + */ +@JsonPropertyOrder({ + Error.JSON_PROPERTY_TYPE, + Error.JSON_PROPERTY_TITLE, + Error.JSON_PROPERTY_STATUS, + Error.JSON_PROPERTY_DETAIL, + Error.JSON_PROPERTY_INSTANCE, + Error.JSON_PROPERTY_TIMESTAMP, + Error.JSON_PROPERTY_TRACE_ID, + Error.JSON_PROPERTY_ERRORS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Error { + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private URI type; + + public static final String JSON_PROPERTY_TITLE = "title"; + @jakarta.annotation.Nonnull + private String title; + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private Integer status; + + public static final String JSON_PROPERTY_DETAIL = "detail"; + @jakarta.annotation.Nullable + private JsonNullable detail = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_INSTANCE = "instance"; + @jakarta.annotation.Nullable + private JsonNullable instance = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TIMESTAMP = "timestamp"; + @jakarta.annotation.Nonnull + private OffsetDateTime timestamp; + + public static final String JSON_PROPERTY_TRACE_ID = "trace_id"; + @jakarta.annotation.Nullable + private JsonNullable traceId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ERRORS = "errors"; + @jakarta.annotation.Nullable + private JsonNullable> errors = JsonNullable.>undefined(); + + public Error() { + } + + public Error type(@jakarta.annotation.Nonnull URI type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public URI getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull URI type) { + this.type = type; + } + + + public Error title(@jakarta.annotation.Nonnull String title) { + + this.title = title; + return this; + } + + /** + * Get title + * @return title + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TITLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getTitle() { + return title; + } + + + @JsonProperty(value = JSON_PROPERTY_TITLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTitle(@jakarta.annotation.Nonnull String title) { + this.title = title; + } + + + public Error status(@jakarta.annotation.Nonnull Integer status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull Integer status) { + this.status = status; + } + + + public Error detail(@jakarta.annotation.Nullable String detail) { + this.detail = JsonNullable.of(detail); + + return this; + } + + /** + * Get detail + * @return detail + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DETAIL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDetail() { + return detail; + } + + @JsonProperty(JSON_PROPERTY_DETAIL) + public void setDetail(JsonNullable detail) { + this.detail = detail; + } + + + + public Error instance(@jakarta.annotation.Nullable String instance) { + this.instance = JsonNullable.of(instance); + + return this; + } + + /** + * Get instance + * @return instance + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_INSTANCE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getInstance() { + return instance; + } + + @JsonProperty(JSON_PROPERTY_INSTANCE) + public void setInstance(JsonNullable instance) { + this.instance = instance; + } + + + + public Error timestamp(@jakarta.annotation.Nonnull OffsetDateTime timestamp) { + + this.timestamp = timestamp; + return this; + } + + /** + * Get timestamp + * @return timestamp + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getTimestamp() { + return timestamp; + } + + + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTimestamp(@jakarta.annotation.Nonnull OffsetDateTime timestamp) { + this.timestamp = timestamp; + } + + + public Error traceId(@jakarta.annotation.Nullable String traceId) { + this.traceId = JsonNullable.of(traceId); + + return this; + } + + /** + * Get traceId + * @return traceId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_TRACE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getTraceId() { + return traceId; + } + + @JsonProperty(JSON_PROPERTY_TRACE_ID) + public void setTraceId(JsonNullable traceId) { + this.traceId = traceId; + } + + + + public Error errors(@jakarta.annotation.Nullable List errors) { + this.errors = JsonNullable.>of(errors); + + return this; + } + + public Error addErrorsItem(ErrorEntry errorsItem) { + if (this.errors == null || !this.errors.isPresent()) { + this.errors = JsonNullable.>of(new ArrayList<>()); + } + try { + this.errors.get().add(errorsItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get errors + * @return errors + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ERRORS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getErrors() { + return errors; + } + + @JsonProperty(JSON_PROPERTY_ERRORS) + public void setErrors(JsonNullable> errors) { + this.errors = errors; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Error error = (Error) o; + return Objects.equals(this.type, error.type) && + Objects.equals(this.title, error.title) && + Objects.equals(this.status, error.status) && + equalsNullable(this.detail, error.detail) && + equalsNullable(this.instance, error.instance) && + Objects.equals(this.timestamp, error.timestamp) && + equalsNullable(this.traceId, error.traceId) && + equalsNullable(this.errors, error.errors); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type, title, status, hashCodeNullable(detail), hashCodeNullable(instance), timestamp, hashCodeNullable(traceId), hashCodeNullable(errors)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Error {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/ErrorEntry.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ErrorEntry.java new file mode 100644 index 0000000..9e999f0 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ErrorEntry.java @@ -0,0 +1,183 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.net.URI; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Field-level or sub-error entry, shaped like a sub-ProblemDetail. The `type` URI identifies the specific constraint or sub-error category (e.g. `validation/not-null` for a Bean Validation `@NotNull`, `validation/paused-working-time` for a TIMR custom validator code, `validation/type-mismatch` for a value that does not fit its target type, `validation/unknown-property` for a property the resource does not declare, `reference-not-found/user` for a `MappingException`). `field` is the JSONPath of the offending property in the request body, rooted at `$` — array elements included. An error about a query parameter names it plainly instead, without the `$.` prefix. + */ +@JsonPropertyOrder({ + ErrorEntry.JSON_PROPERTY_TYPE, + ErrorEntry.JSON_PROPERTY_FIELD, + ErrorEntry.JSON_PROPERTY_DETAIL +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ErrorEntry { + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private URI type; + + public static final String JSON_PROPERTY_FIELD = "field"; + @jakarta.annotation.Nullable + private JsonNullable field = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DETAIL = "detail"; + @jakarta.annotation.Nonnull + private String detail; + + public ErrorEntry() { + } + + public ErrorEntry type(@jakarta.annotation.Nonnull URI type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public URI getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull URI type) { + this.type = type; + } + + + public ErrorEntry field(@jakarta.annotation.Nullable String field) { + this.field = JsonNullable.of(field); + + return this; + } + + /** + * Get field + * @return field + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FIELD, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getField() { + return field; + } + + @JsonProperty(JSON_PROPERTY_FIELD) + public void setField(JsonNullable field) { + this.field = field; + } + + + + public ErrorEntry detail(@jakarta.annotation.Nonnull String detail) { + + this.detail = detail; + return this; + } + + /** + * Get detail + * @return detail + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DETAIL, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDetail() { + return detail; + } + + + @JsonProperty(value = JSON_PROPERTY_DETAIL, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDetail(@jakarta.annotation.Nonnull String detail) { + this.detail = detail; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ErrorEntry errorEntry = (ErrorEntry) o; + return Objects.equals(this.type, errorEntry.type) && + equalsNullable(this.field, errorEntry.field) && + Objects.equals(this.detail, errorEntry.detail); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type, hashCodeNullable(field), detail); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ErrorEntry {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/FlexTimeIndicator.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/FlexTimeIndicator.java new file mode 100644 index 0000000..974a589 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/FlexTimeIndicator.java @@ -0,0 +1,62 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Traffic-light rating of the flex time balance. The thresholds are an account setting and are not part of this contract. + */ +public enum FlexTimeIndicator { + + GREEN("green"), + + YELLOW("yellow"), + + RED("red"); + + private String value; + + FlexTimeIndicator(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static FlexTimeIndicator fromValue(String value) { + for (FlexTimeIndicator b : FlexTimeIndicator.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Holiday.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Holiday.java new file mode 100644 index 0000000..817863b --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Holiday.java @@ -0,0 +1,182 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Holiday + */ +@JsonPropertyOrder({ + Holiday.JSON_PROPERTY_DATE, + Holiday.JSON_PROPERTY_DESCRIPTION, + Holiday.JSON_PROPERTY_HALF_DAY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Holiday { + public static final String JSON_PROPERTY_DATE = "date"; + @jakarta.annotation.Nonnull + private LocalDate date; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nonnull + private String description; + + public static final String JSON_PROPERTY_HALF_DAY = "half_day"; + @jakarta.annotation.Nonnull + private Boolean halfDay; + + public Holiday() { + } + + public Holiday date(@jakarta.annotation.Nonnull LocalDate date) { + + this.date = date; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return date + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getDate() { + return date; + } + + + @JsonProperty(value = JSON_PROPERTY_DATE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDate(@jakarta.annotation.Nonnull LocalDate date) { + this.date = date; + } + + + public Holiday description(@jakarta.annotation.Nonnull String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@jakarta.annotation.Nonnull String description) { + this.description = description; + } + + + public Holiday halfDay(@jakarta.annotation.Nonnull Boolean halfDay) { + + this.halfDay = halfDay; + return this; + } + + /** + * Get halfDay + * @return halfDay + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getHalfDay() { + return halfDay; + } + + + @JsonProperty(value = JSON_PROPERTY_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setHalfDay(@jakarta.annotation.Nonnull Boolean halfDay) { + this.halfDay = halfDay; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Holiday holiday = (Holiday) o; + return Objects.equals(this.date, holiday.date) && + Objects.equals(this.description, holiday.description) && + Objects.equals(this.halfDay, holiday.halfDay); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(date, description, halfDay); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Holiday {\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidayCalendarPartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidayCalendarPartial.java new file mode 100644 index 0000000..0e91692 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidayCalendarPartial.java @@ -0,0 +1,149 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A holiday calendar. Its holidays are either generated automatically or maintained manually. + */ +@JsonPropertyOrder({ + HolidayCalendarPartial.JSON_PROPERTY_ID, + HolidayCalendarPartial.JSON_PROPERTY_DESCRIPTION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HolidayCalendarPartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nonnull + private String description; + + public HolidayCalendarPartial() { + } + + public HolidayCalendarPartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public HolidayCalendarPartial description(@jakarta.annotation.Nonnull String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@jakarta.annotation.Nonnull String description) { + this.description = description; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HolidayCalendarPartial holidayCalendarPartial = (HolidayCalendarPartial) o; + return Objects.equals(this.id, holidayCalendarPartial.id) && + Objects.equals(this.description, holidayCalendarPartial.description); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, description); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HolidayCalendarPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidayCalendarsPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidayCalendarsPage.java new file mode 100644 index 0000000..4cb8dd7 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidayCalendarsPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.HolidayCalendarPartial; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * HolidayCalendarsPage + */ +@JsonPropertyOrder({ + HolidayCalendarsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + HolidayCalendarsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HolidayCalendarsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public HolidayCalendarsPage() { + } + + public HolidayCalendarsPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public HolidayCalendarsPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public HolidayCalendarsPage addDataItem(HolidayCalendarPartial dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HolidayCalendarsPage holidayCalendarsPage = (HolidayCalendarsPage) o; + return Objects.equals(this.nextPageToken, holidayCalendarsPage.nextPageToken) && + Objects.equals(this.data, holidayCalendarsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HolidayCalendarsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidayCalendarsSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidayCalendarsSortColumn.java new file mode 100644 index 0000000..14600f5 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidayCalendarsSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Holiday Calendars. + */ +public enum HolidayCalendarsSortColumn { + + DESCRIPTION("description"); + + private String value; + + HolidayCalendarsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static HolidayCalendarsSortColumn fromValue(String value) { + for (HolidayCalendarsSortColumn b : HolidayCalendarsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidaysPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidaysPage.java new file mode 100644 index 0000000..cfc0ed9 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidaysPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.Holiday; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * HolidaysPage + */ +@JsonPropertyOrder({ + HolidaysPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + HolidaysPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class HolidaysPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public HolidaysPage() { + } + + public HolidaysPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public HolidaysPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public HolidaysPage addDataItem(Holiday dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HolidaysPage holidaysPage = (HolidaysPage) o; + return Objects.equals(this.nextPageToken, holidaysPage.nextPageToken) && + Objects.equals(this.data, holidaysPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HolidaysPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidaysSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidaysSortColumn.java new file mode 100644 index 0000000..2a1afd8 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/HolidaysSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Holidays. + */ +public enum HolidaysSortColumn { + + DATE("date"); + + private String value; + + HolidaysSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static HolidaysSortColumn fromValue(String value) { + for (HolidaysSortColumn b : HolidaysSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Location.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Location.java new file mode 100644 index 0000000..2dc9861 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Location.java @@ -0,0 +1,245 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Location + */ +@JsonPropertyOrder({ + Location.JSON_PROPERTY_LAT, + Location.JSON_PROPERTY_LON, + Location.JSON_PROPERTY_TIMESTAMP, + Location.JSON_PROPERTY_FORMATTED_ADDRESS, + Location.JSON_PROPERTY_ACCURACY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Location { + public static final String JSON_PROPERTY_LAT = "lat"; + @jakarta.annotation.Nullable + private Float lat; + + public static final String JSON_PROPERTY_LON = "lon"; + @jakarta.annotation.Nullable + private Float lon; + + public static final String JSON_PROPERTY_TIMESTAMP = "timestamp"; + @jakarta.annotation.Nullable + private JsonNullable timestamp = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_FORMATTED_ADDRESS = "formatted_address"; + @jakarta.annotation.Nullable + private JsonNullable formattedAddress = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACCURACY = "accuracy"; + @jakarta.annotation.Nullable + private Float accuracy; + + public Location() { + } + + public Location lat(@jakarta.annotation.Nullable Float lat) { + + this.lat = lat; + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Float getLat() { + return lat; + } + + + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLat(@jakarta.annotation.Nullable Float lat) { + this.lat = lat; + } + + + public Location lon(@jakarta.annotation.Nullable Float lon) { + + this.lon = lon; + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Float getLon() { + return lon; + } + + + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLon(@jakarta.annotation.Nullable Float lon) { + this.lon = lon; + } + + + public Location timestamp(@jakarta.annotation.Nullable OffsetDateTime timestamp) { + this.timestamp = JsonNullable.of(timestamp); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return timestamp + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getTimestamp() { + return timestamp; + } + + @JsonProperty(JSON_PROPERTY_TIMESTAMP) + public void setTimestamp(JsonNullable timestamp) { + this.timestamp = timestamp; + } + + + + public Location formattedAddress(@jakarta.annotation.Nullable String formattedAddress) { + this.formattedAddress = JsonNullable.of(formattedAddress); + + return this; + } + + /** + * Get formattedAddress + * @return formattedAddress + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FORMATTED_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getFormattedAddress() { + return formattedAddress; + } + + @JsonProperty(JSON_PROPERTY_FORMATTED_ADDRESS) + public void setFormattedAddress(JsonNullable formattedAddress) { + this.formattedAddress = formattedAddress; + } + + + + public Location accuracy(@jakarta.annotation.Nullable Float accuracy) { + + this.accuracy = accuracy; + return this; + } + + /** + * Horizontal GPS accuracy in meters. + * @return accuracy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ACCURACY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Float getAccuracy() { + return accuracy; + } + + + @JsonProperty(value = JSON_PROPERTY_ACCURACY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAccuracy(@jakarta.annotation.Nullable Float accuracy) { + this.accuracy = accuracy; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Location location = (Location) o; + return Objects.equals(this.lat, location.lat) && + Objects.equals(this.lon, location.lon) && + equalsNullable(this.timestamp, location.timestamp) && + equalsNullable(this.formattedAddress, location.formattedAddress) && + Objects.equals(this.accuracy, location.accuracy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lat, lon, hashCodeNullable(timestamp), hashCodeNullable(formattedAddress), accuracy); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Location {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/LocationCreate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/LocationCreate.java new file mode 100644 index 0000000..b413710 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/LocationCreate.java @@ -0,0 +1,243 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * LocationCreate + */ +@JsonPropertyOrder({ + LocationCreate.JSON_PROPERTY_LAT, + LocationCreate.JSON_PROPERTY_LON, + LocationCreate.JSON_PROPERTY_TIMESTAMP, + LocationCreate.JSON_PROPERTY_FORMATTED_ADDRESS, + LocationCreate.JSON_PROPERTY_ACCURACY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class LocationCreate { + public static final String JSON_PROPERTY_LAT = "lat"; + @jakarta.annotation.Nonnull + private Float lat; + + public static final String JSON_PROPERTY_LON = "lon"; + @jakarta.annotation.Nonnull + private Float lon; + + public static final String JSON_PROPERTY_TIMESTAMP = "timestamp"; + @jakarta.annotation.Nullable + private JsonNullable timestamp = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_FORMATTED_ADDRESS = "formatted_address"; + @jakarta.annotation.Nullable + private JsonNullable formattedAddress = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACCURACY = "accuracy"; + @jakarta.annotation.Nullable + private JsonNullable accuracy = JsonNullable.undefined(); + + public LocationCreate() { + } + + public LocationCreate lat(@jakarta.annotation.Nonnull Float lat) { + + this.lat = lat; + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LAT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Float getLat() { + return lat; + } + + + @JsonProperty(value = JSON_PROPERTY_LAT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLat(@jakarta.annotation.Nonnull Float lat) { + this.lat = lat; + } + + + public LocationCreate lon(@jakarta.annotation.Nonnull Float lon) { + + this.lon = lon; + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LON, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Float getLon() { + return lon; + } + + + @JsonProperty(value = JSON_PROPERTY_LON, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLon(@jakarta.annotation.Nonnull Float lon) { + this.lon = lon; + } + + + public LocationCreate timestamp(@jakarta.annotation.Nullable OffsetDateTime timestamp) { + this.timestamp = JsonNullable.of(timestamp); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return timestamp + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getTimestamp() { + return timestamp; + } + + @JsonProperty(JSON_PROPERTY_TIMESTAMP) + public void setTimestamp(JsonNullable timestamp) { + this.timestamp = timestamp; + } + + + + public LocationCreate formattedAddress(@jakarta.annotation.Nullable String formattedAddress) { + this.formattedAddress = JsonNullable.of(formattedAddress); + + return this; + } + + /** + * Get formattedAddress + * @return formattedAddress + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FORMATTED_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getFormattedAddress() { + return formattedAddress; + } + + @JsonProperty(JSON_PROPERTY_FORMATTED_ADDRESS) + public void setFormattedAddress(JsonNullable formattedAddress) { + this.formattedAddress = formattedAddress; + } + + + + public LocationCreate accuracy(@jakarta.annotation.Nullable Float accuracy) { + this.accuracy = JsonNullable.of(accuracy); + + return this; + } + + /** + * Horizontal GPS accuracy in meters. + * @return accuracy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ACCURACY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getAccuracy() { + return accuracy; + } + + @JsonProperty(JSON_PROPERTY_ACCURACY) + public void setAccuracy(JsonNullable accuracy) { + this.accuracy = accuracy; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LocationCreate locationCreate = (LocationCreate) o; + return Objects.equals(this.lat, locationCreate.lat) && + Objects.equals(this.lon, locationCreate.lon) && + equalsNullable(this.timestamp, locationCreate.timestamp) && + equalsNullable(this.formattedAddress, locationCreate.formattedAddress) && + equalsNullable(this.accuracy, locationCreate.accuracy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lat, lon, hashCodeNullable(timestamp), hashCodeNullable(formattedAddress), hashCodeNullable(accuracy)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class LocationCreate {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/LocationUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/LocationUpdate.java new file mode 100644 index 0000000..1a08ae7 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/LocationUpdate.java @@ -0,0 +1,239 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * LocationUpdate + */ +@JsonPropertyOrder({ + LocationUpdate.JSON_PROPERTY_LAT, + LocationUpdate.JSON_PROPERTY_LON, + LocationUpdate.JSON_PROPERTY_TIMESTAMP, + LocationUpdate.JSON_PROPERTY_FORMATTED_ADDRESS, + LocationUpdate.JSON_PROPERTY_ACCURACY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class LocationUpdate { + public static final String JSON_PROPERTY_LAT = "lat"; + @jakarta.annotation.Nullable + private JsonNullable lat = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LON = "lon"; + @jakarta.annotation.Nullable + private JsonNullable lon = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TIMESTAMP = "timestamp"; + @jakarta.annotation.Nullable + private JsonNullable timestamp = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_FORMATTED_ADDRESS = "formatted_address"; + @jakarta.annotation.Nullable + private JsonNullable formattedAddress = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACCURACY = "accuracy"; + @jakarta.annotation.Nullable + private JsonNullable accuracy = JsonNullable.undefined(); + + public LocationUpdate() { + } + + public LocationUpdate lat(@jakarta.annotation.Nullable Float lat) { + this.lat = JsonNullable.of(lat); + + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLat() { + return lat; + } + + @JsonProperty(JSON_PROPERTY_LAT) + public void setLat(JsonNullable lat) { + this.lat = lat; + } + + + + public LocationUpdate lon(@jakarta.annotation.Nullable Float lon) { + this.lon = JsonNullable.of(lon); + + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLon() { + return lon; + } + + @JsonProperty(JSON_PROPERTY_LON) + public void setLon(JsonNullable lon) { + this.lon = lon; + } + + + + public LocationUpdate timestamp(@jakarta.annotation.Nullable OffsetDateTime timestamp) { + this.timestamp = JsonNullable.of(timestamp); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return timestamp + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_TIMESTAMP, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getTimestamp() { + return timestamp; + } + + @JsonProperty(JSON_PROPERTY_TIMESTAMP) + public void setTimestamp(JsonNullable timestamp) { + this.timestamp = timestamp; + } + + + + public LocationUpdate formattedAddress(@jakarta.annotation.Nullable String formattedAddress) { + this.formattedAddress = JsonNullable.of(formattedAddress); + + return this; + } + + /** + * Get formattedAddress + * @return formattedAddress + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FORMATTED_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getFormattedAddress() { + return formattedAddress; + } + + @JsonProperty(JSON_PROPERTY_FORMATTED_ADDRESS) + public void setFormattedAddress(JsonNullable formattedAddress) { + this.formattedAddress = formattedAddress; + } + + + + public LocationUpdate accuracy(@jakarta.annotation.Nullable Float accuracy) { + this.accuracy = JsonNullable.of(accuracy); + + return this; + } + + /** + * Horizontal GPS accuracy in meters. + * @return accuracy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ACCURACY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getAccuracy() { + return accuracy; + } + + @JsonProperty(JSON_PROPERTY_ACCURACY) + public void setAccuracy(JsonNullable accuracy) { + this.accuracy = accuracy; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + LocationUpdate locationUpdate = (LocationUpdate) o; + return equalsNullable(this.lat, locationUpdate.lat) && + equalsNullable(this.lon, locationUpdate.lon) && + equalsNullable(this.timestamp, locationUpdate.timestamp) && + equalsNullable(this.formattedAddress, locationUpdate.formattedAddress) && + equalsNullable(this.accuracy, locationUpdate.accuracy); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(lat), hashCodeNullable(lon), hashCodeNullable(timestamp), hashCodeNullable(formattedAddress), hashCodeNullable(accuracy)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class LocationUpdate {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/NormalWorkingTimes.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/NormalWorkingTimes.java new file mode 100644 index 0000000..c4017be --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/NormalWorkingTimes.java @@ -0,0 +1,150 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * NormalWorkingTimes + */ +@JsonPropertyOrder({ + NormalWorkingTimes.JSON_PROPERTY_START, + NormalWorkingTimes.JSON_PROPERTY_END +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class NormalWorkingTimes { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private JsonNullable start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public NormalWorkingTimes() { + } + + public NormalWorkingTimes start(@jakarta.annotation.Nullable String start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * Get start + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public NormalWorkingTimes end(@jakarta.annotation.Nullable String end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * Get end + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NormalWorkingTimes normalWorkingTimes = (NormalWorkingTimes) o; + return equalsNullable(this.start, normalWorkingTimes.start) && + equalsNullable(this.end, normalWorkingTimes.end); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NormalWorkingTimes {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/OvertimeSurchargeAccount.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/OvertimeSurchargeAccount.java new file mode 100644 index 0000000..ff4fdd4 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/OvertimeSurchargeAccount.java @@ -0,0 +1,180 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * OvertimeSurchargeAccount + */ +@JsonPropertyOrder({ + OvertimeSurchargeAccount.JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, + OvertimeSurchargeAccount.JSON_PROPERTY_NEW_MINUTES, + OvertimeSurchargeAccount.JSON_PROPERTY_BALANCE_TOTAL_MINUTES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class OvertimeSurchargeAccount { + public static final String JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES = "balance_last_period_minutes"; + @jakarta.annotation.Nullable + private Integer balanceLastPeriodMinutes; + + public static final String JSON_PROPERTY_NEW_MINUTES = "new_minutes"; + @jakarta.annotation.Nullable + private Integer newMinutes; + + public static final String JSON_PROPERTY_BALANCE_TOTAL_MINUTES = "balance_total_minutes"; + @jakarta.annotation.Nullable + private Integer balanceTotalMinutes; + + public OvertimeSurchargeAccount() { + } + + public OvertimeSurchargeAccount balanceLastPeriodMinutes(@jakarta.annotation.Nullable Integer balanceLastPeriodMinutes) { + + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + return this; + } + + /** + * Get balanceLastPeriodMinutes + * @return balanceLastPeriodMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getBalanceLastPeriodMinutes() { + return balanceLastPeriodMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceLastPeriodMinutes(@jakarta.annotation.Nullable Integer balanceLastPeriodMinutes) { + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + } + + + public OvertimeSurchargeAccount newMinutes(@jakarta.annotation.Nullable Integer newMinutes) { + + this.newMinutes = newMinutes; + return this; + } + + /** + * Get newMinutes + * @return newMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEW_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getNewMinutes() { + return newMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_NEW_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNewMinutes(@jakarta.annotation.Nullable Integer newMinutes) { + this.newMinutes = newMinutes; + } + + + public OvertimeSurchargeAccount balanceTotalMinutes(@jakarta.annotation.Nullable Integer balanceTotalMinutes) { + + this.balanceTotalMinutes = balanceTotalMinutes; + return this; + } + + /** + * Get balanceTotalMinutes + * @return balanceTotalMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getBalanceTotalMinutes() { + return balanceTotalMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceTotalMinutes(@jakarta.annotation.Nullable Integer balanceTotalMinutes) { + this.balanceTotalMinutes = balanceTotalMinutes; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OvertimeSurchargeAccount overtimeSurchargeAccount = (OvertimeSurchargeAccount) o; + return Objects.equals(this.balanceLastPeriodMinutes, overtimeSurchargeAccount.balanceLastPeriodMinutes) && + Objects.equals(this.newMinutes, overtimeSurchargeAccount.newMinutes) && + Objects.equals(this.balanceTotalMinutes, overtimeSurchargeAccount.balanceTotalMinutes); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(balanceLastPeriodMinutes, newMinutes, balanceTotalMinutes); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OvertimeSurchargeAccount {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/OvertimeSurchargeAccounts.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/OvertimeSurchargeAccounts.java new file mode 100644 index 0000000..fa4df62 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/OvertimeSurchargeAccounts.java @@ -0,0 +1,215 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.OvertimeSurchargeAccount; +import com.timr.api.models.OvertimeSurchargeRule; +import java.math.BigDecimal; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * OvertimeSurchargeAccounts + */ +@JsonPropertyOrder({ + OvertimeSurchargeAccounts.JSON_PROPERTY_RULE, + OvertimeSurchargeAccounts.JSON_PROPERTY_PERCENTAGE, + OvertimeSurchargeAccounts.JSON_PROPERTY_OVERTIME, + OvertimeSurchargeAccounts.JSON_PROPERTY_SURCHARGE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class OvertimeSurchargeAccounts { + public static final String JSON_PROPERTY_RULE = "rule"; + @jakarta.annotation.Nonnull + private OvertimeSurchargeRule rule; + + public static final String JSON_PROPERTY_PERCENTAGE = "percentage"; + @jakarta.annotation.Nullable + private BigDecimal percentage; + + public static final String JSON_PROPERTY_OVERTIME = "overtime"; + @jakarta.annotation.Nonnull + private OvertimeSurchargeAccount overtime; + + public static final String JSON_PROPERTY_SURCHARGE = "surcharge"; + @jakarta.annotation.Nonnull + private OvertimeSurchargeAccount surcharge; + + public OvertimeSurchargeAccounts() { + } + + public OvertimeSurchargeAccounts rule(@jakarta.annotation.Nonnull OvertimeSurchargeRule rule) { + + this.rule = rule; + return this; + } + + /** + * Get rule + * @return rule + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_RULE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OvertimeSurchargeRule getRule() { + return rule; + } + + + @JsonProperty(value = JSON_PROPERTY_RULE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRule(@jakarta.annotation.Nonnull OvertimeSurchargeRule rule) { + this.rule = rule; + } + + + public OvertimeSurchargeAccounts percentage(@jakarta.annotation.Nullable BigDecimal percentage) { + + this.percentage = percentage; + return this; + } + + /** + * Get percentage + * @return percentage + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PERCENTAGE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public BigDecimal getPercentage() { + return percentage; + } + + + @JsonProperty(value = JSON_PROPERTY_PERCENTAGE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPercentage(@jakarta.annotation.Nullable BigDecimal percentage) { + this.percentage = percentage; + } + + + public OvertimeSurchargeAccounts overtime(@jakarta.annotation.Nonnull OvertimeSurchargeAccount overtime) { + + this.overtime = overtime; + return this; + } + + /** + * Get overtime + * @return overtime + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_OVERTIME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OvertimeSurchargeAccount getOvertime() { + return overtime; + } + + + @JsonProperty(value = JSON_PROPERTY_OVERTIME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setOvertime(@jakarta.annotation.Nonnull OvertimeSurchargeAccount overtime) { + this.overtime = overtime; + } + + + public OvertimeSurchargeAccounts surcharge(@jakarta.annotation.Nonnull OvertimeSurchargeAccount surcharge) { + + this.surcharge = surcharge; + return this; + } + + /** + * Get surcharge + * @return surcharge + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_SURCHARGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OvertimeSurchargeAccount getSurcharge() { + return surcharge; + } + + + @JsonProperty(value = JSON_PROPERTY_SURCHARGE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSurcharge(@jakarta.annotation.Nonnull OvertimeSurchargeAccount surcharge) { + this.surcharge = surcharge; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OvertimeSurchargeAccounts overtimeSurchargeAccounts = (OvertimeSurchargeAccounts) o; + return Objects.equals(this.rule, overtimeSurchargeAccounts.rule) && + Objects.equals(this.percentage, overtimeSurchargeAccounts.percentage) && + Objects.equals(this.overtime, overtimeSurchargeAccounts.overtime) && + Objects.equals(this.surcharge, overtimeSurchargeAccounts.surcharge); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(rule, percentage, overtime, surcharge); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OvertimeSurchargeAccounts {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/OvertimeSurchargeRule.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/OvertimeSurchargeRule.java new file mode 100644 index 0000000..f3f6477 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/OvertimeSurchargeRule.java @@ -0,0 +1,181 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.UUID; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * OvertimeSurchargeRule + */ +@JsonPropertyOrder({ + OvertimeSurchargeRule.JSON_PROPERTY_ID, + OvertimeSurchargeRule.JSON_PROPERTY_NAME, + OvertimeSurchargeRule.JSON_PROPERTY_SHORT_NAME +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class OvertimeSurchargeRule { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private UUID id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_SHORT_NAME = "short_name"; + @jakarta.annotation.Nonnull + private String shortName; + + public OvertimeSurchargeRule() { + } + + public OvertimeSurchargeRule id(@jakarta.annotation.Nonnull UUID id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UUID getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull UUID id) { + this.id = id; + } + + + public OvertimeSurchargeRule name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public OvertimeSurchargeRule shortName(@jakarta.annotation.Nonnull String shortName) { + + this.shortName = shortName; + return this; + } + + /** + * Get shortName + * @return shortName + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_SHORT_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getShortName() { + return shortName; + } + + + @JsonProperty(value = JSON_PROPERTY_SHORT_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setShortName(@jakarta.annotation.Nonnull String shortName) { + this.shortName = shortName; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OvertimeSurchargeRule overtimeSurchargeRule = (OvertimeSurchargeRule) o; + return Objects.equals(this.id, overtimeSurchargeRule.id) && + Objects.equals(this.name, overtimeSurchargeRule.name) && + Objects.equals(this.shortName, overtimeSurchargeRule.shortName); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, shortName); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OvertimeSurchargeRule {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/PagingInformation.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/PagingInformation.java new file mode 100644 index 0000000..c2382f5 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/PagingInformation.java @@ -0,0 +1,116 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * PagingInformation + */ +@JsonPropertyOrder({ + PagingInformation.JSON_PROPERTY_NEXT_PAGE_TOKEN +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class PagingInformation { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public PagingInformation() { + } + + public PagingInformation nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PagingInformation pagingInformation = (PagingInformation) o; + return Objects.equals(this.nextPageToken, pagingInformation.nextPageToken); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PagingInformation {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Platform.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Platform.java new file mode 100644 index 0000000..b7d8e6b --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Platform.java @@ -0,0 +1,68 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Platform the entry was recorded on. + */ +public enum Platform { + + TIMR_WEB("timr_web"), + + TIMR_MOBILE("timr_mobile"), + + TOUR_MOBILE("tour_mobile"), + + TIMR_TERMINAL("timr_terminal"), + + SYNC_API("sync_api"), + + TIMR_API("timr_api"); + + private String value; + + Platform(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static Platform fromValue(String value) { + for (Platform b : Platform.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProblemDetail.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProblemDetail.java new file mode 100644 index 0000000..32973f9 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProblemDetail.java @@ -0,0 +1,241 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.net.URI; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * RFC 9457 Problem Details base members (`type`, `title`, `status`, `detail`, `instance`) — the common shape of all error response bodies. + */ +@JsonPropertyOrder({ + ProblemDetail.JSON_PROPERTY_TYPE, + ProblemDetail.JSON_PROPERTY_TITLE, + ProblemDetail.JSON_PROPERTY_STATUS, + ProblemDetail.JSON_PROPERTY_DETAIL, + ProblemDetail.JSON_PROPERTY_INSTANCE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProblemDetail { + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private URI type; + + public static final String JSON_PROPERTY_TITLE = "title"; + @jakarta.annotation.Nonnull + private String title; + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private Integer status; + + public static final String JSON_PROPERTY_DETAIL = "detail"; + @jakarta.annotation.Nullable + private JsonNullable detail = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_INSTANCE = "instance"; + @jakarta.annotation.Nullable + private JsonNullable instance = JsonNullable.undefined(); + + public ProblemDetail() { + } + + public ProblemDetail type(@jakarta.annotation.Nonnull URI type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public URI getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull URI type) { + this.type = type; + } + + + public ProblemDetail title(@jakarta.annotation.Nonnull String title) { + + this.title = title; + return this; + } + + /** + * Get title + * @return title + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TITLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getTitle() { + return title; + } + + + @JsonProperty(value = JSON_PROPERTY_TITLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTitle(@jakarta.annotation.Nonnull String title) { + this.title = title; + } + + + public ProblemDetail status(@jakarta.annotation.Nonnull Integer status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull Integer status) { + this.status = status; + } + + + public ProblemDetail detail(@jakarta.annotation.Nullable String detail) { + this.detail = JsonNullable.of(detail); + + return this; + } + + /** + * Get detail + * @return detail + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DETAIL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDetail() { + return detail; + } + + @JsonProperty(JSON_PROPERTY_DETAIL) + public void setDetail(JsonNullable detail) { + this.detail = detail; + } + + + + public ProblemDetail instance(@jakarta.annotation.Nullable String instance) { + this.instance = JsonNullable.of(instance); + + return this; + } + + /** + * Get instance + * @return instance + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_INSTANCE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getInstance() { + return instance; + } + + @JsonProperty(JSON_PROPERTY_INSTANCE) + public void setInstance(JsonNullable instance) { + this.instance = instance; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProblemDetail problemDetail = (ProblemDetail) o; + return Objects.equals(this.type, problemDetail.type) && + Objects.equals(this.title, problemDetail.title) && + Objects.equals(this.status, problemDetail.status) && + equalsNullable(this.detail, problemDetail.detail) && + equalsNullable(this.instance, problemDetail.instance); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(type, title, status, hashCodeNullable(detail), hashCodeNullable(instance)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProblemDetail {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTime.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTime.java new file mode 100644 index 0000000..bb79f19 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTime.java @@ -0,0 +1,734 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTime; +import com.timr.api.models.Duration; +import com.timr.api.models.Location; +import com.timr.api.models.Platform; +import com.timr.api.models.ProjectTimeStatus; +import com.timr.api.models.TaskPartial; +import com.timr.api.models.UserPartial; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * One booking on a `task`, from `start` to `end`, optionally `billable`, with `break_times`, notes and locations. + */ +@JsonPropertyOrder({ + ProjectTime.JSON_PROPERTY_ID, + ProjectTime.JSON_PROPERTY_START, + ProjectTime.JSON_PROPERTY_END, + ProjectTime.JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, + ProjectTime.JSON_PROPERTY_BREAK_TIMES, + ProjectTime.JSON_PROPERTY_DURATION, + ProjectTime.JSON_PROPERTY_CHANGED, + ProjectTime.JSON_PROPERTY_NOTES, + ProjectTime.JSON_PROPERTY_USER, + ProjectTime.JSON_PROPERTY_TASK, + ProjectTime.JSON_PROPERTY_BILLABLE, + ProjectTime.JSON_PROPERTY_START_LOCATION, + ProjectTime.JSON_PROPERTY_END_LOCATION, + ProjectTime.JSON_PROPERTY_START_PLATFORM, + ProjectTime.JSON_PROPERTY_END_PLATFORM, + ProjectTime.JSON_PROPERTY_LAST_MODIFIED, + ProjectTime.JSON_PROPERTY_LAST_MODIFIED_BY, + ProjectTime.JSON_PROPERTY_STATUS, + ProjectTime.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTime { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nonnull + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private OffsetDateTime end; + + public static final String JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES = "break_time_total_minutes"; + @jakarta.annotation.Nonnull + private Integer breakTimeTotalMinutes; + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + @jakarta.annotation.Nonnull + private List breakTimes; + + public static final String JSON_PROPERTY_DURATION = "duration"; + @jakarta.annotation.Nullable + private Duration duration; + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nonnull + private Boolean changed; + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private String notes; + + public static final String JSON_PROPERTY_USER = "user"; + @jakarta.annotation.Nonnull + private UserPartial user; + + public static final String JSON_PROPERTY_TASK = "task"; + @jakarta.annotation.Nonnull + private TaskPartial task; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + @jakarta.annotation.Nonnull + private Boolean billable; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + @jakarta.annotation.Nullable + private Location startLocation; + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + @jakarta.annotation.Nullable + private Location endLocation; + + public static final String JSON_PROPERTY_START_PLATFORM = "start_platform"; + @jakarta.annotation.Nullable + private Platform startPlatform; + + public static final String JSON_PROPERTY_END_PLATFORM = "end_platform"; + @jakarta.annotation.Nullable + private Platform endPlatform; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + @jakarta.annotation.Nonnull + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + @jakarta.annotation.Nullable + private UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private ProjectTimeStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public ProjectTime() { + } + + public ProjectTime id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public ProjectTime start(@jakarta.annotation.Nonnull OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nonnull OffsetDateTime start) { + this.start = start; + } + + + public ProjectTime end(@jakarta.annotation.Nullable OffsetDateTime end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = end; + } + + + public ProjectTime breakTimeTotalMinutes(@jakarta.annotation.Nonnull Integer breakTimeTotalMinutes) { + + this.breakTimeTotalMinutes = breakTimeTotalMinutes; + return this; + } + + /** + * Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + * @return breakTimeTotalMinutes + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getBreakTimeTotalMinutes() { + return breakTimeTotalMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreakTimeTotalMinutes(@jakarta.annotation.Nonnull Integer breakTimeTotalMinutes) { + this.breakTimeTotalMinutes = breakTimeTotalMinutes; + } + + + public ProjectTime breakTimes(@jakarta.annotation.Nonnull List breakTimes) { + + this.breakTimes = breakTimes; + return this; + } + + public ProjectTime addBreakTimesItem(BreakTime breakTimesItem) { + if (this.breakTimes == null) { + this.breakTimes = new ArrayList<>(); + } + this.breakTimes.add(breakTimesItem); + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getBreakTimes() { + return breakTimes; + } + + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreakTimes(@jakarta.annotation.Nonnull List breakTimes) { + this.breakTimes = breakTimes; + } + + + public ProjectTime duration(@jakarta.annotation.Nullable Duration duration) { + + this.duration = duration; + return this; + } + + /** + * Get duration + * @return duration + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Duration getDuration() { + return duration; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDuration(@jakarta.annotation.Nullable Duration duration) { + this.duration = duration; + } + + + public ProjectTime changed(@jakarta.annotation.Nonnull Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(@jakarta.annotation.Nonnull Boolean changed) { + this.changed = changed; + } + + + public ProjectTime notes(@jakarta.annotation.Nullable String notes) { + + this.notes = notes; + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNotes() { + return notes; + } + + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNotes(@jakarta.annotation.Nullable String notes) { + this.notes = notes; + } + + + public ProjectTime user(@jakarta.annotation.Nonnull UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(@jakarta.annotation.Nonnull UserPartial user) { + this.user = user; + } + + + public ProjectTime task(@jakarta.annotation.Nonnull TaskPartial task) { + + this.task = task; + return this; + } + + /** + * Get task + * @return task + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TASK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public TaskPartial getTask() { + return task; + } + + + @JsonProperty(value = JSON_PROPERTY_TASK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTask(@jakarta.annotation.Nonnull TaskPartial task) { + this.task = task; + } + + + public ProjectTime billable(@jakarta.annotation.Nonnull Boolean billable) { + + this.billable = billable; + return this; + } + + /** + * Get billable + * @return billable + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBillable() { + return billable; + } + + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBillable(@jakarta.annotation.Nonnull Boolean billable) { + this.billable = billable; + } + + + public ProjectTime startLocation(@jakarta.annotation.Nullable Location startLocation) { + + this.startLocation = startLocation; + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Location getStartLocation() { + return startLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartLocation(@jakarta.annotation.Nullable Location startLocation) { + this.startLocation = startLocation; + } + + + public ProjectTime endLocation(@jakarta.annotation.Nullable Location endLocation) { + + this.endLocation = endLocation; + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Location getEndLocation() { + return endLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndLocation(@jakarta.annotation.Nullable Location endLocation) { + this.endLocation = endLocation; + } + + + public ProjectTime startPlatform(@jakarta.annotation.Nullable Platform startPlatform) { + + this.startPlatform = startPlatform; + return this; + } + + /** + * Get startPlatform + * @return startPlatform + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Platform getStartPlatform() { + return startPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartPlatform(@jakarta.annotation.Nullable Platform startPlatform) { + this.startPlatform = startPlatform; + } + + + public ProjectTime endPlatform(@jakarta.annotation.Nullable Platform endPlatform) { + + this.endPlatform = endPlatform; + return this; + } + + /** + * Get endPlatform + * @return endPlatform + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Platform getEndPlatform() { + return endPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndPlatform(@jakarta.annotation.Nullable Platform endPlatform) { + this.endPlatform = endPlatform; + } + + + public ProjectTime lastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public ProjectTime lastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public ProjectTime status(@jakarta.annotation.Nonnull ProjectTimeStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public ProjectTimeStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull ProjectTimeStatus status) { + this.status = status; + } + + + public ProjectTime metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public ProjectTime putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTime projectTime = (ProjectTime) o; + return Objects.equals(this.id, projectTime.id) && + Objects.equals(this.start, projectTime.start) && + Objects.equals(this.end, projectTime.end) && + Objects.equals(this.breakTimeTotalMinutes, projectTime.breakTimeTotalMinutes) && + Objects.equals(this.breakTimes, projectTime.breakTimes) && + Objects.equals(this.duration, projectTime.duration) && + Objects.equals(this.changed, projectTime.changed) && + Objects.equals(this.notes, projectTime.notes) && + Objects.equals(this.user, projectTime.user) && + Objects.equals(this.task, projectTime.task) && + Objects.equals(this.billable, projectTime.billable) && + Objects.equals(this.startLocation, projectTime.startLocation) && + Objects.equals(this.endLocation, projectTime.endLocation) && + Objects.equals(this.startPlatform, projectTime.startPlatform) && + Objects.equals(this.endPlatform, projectTime.endPlatform) && + Objects.equals(this.lastModified, projectTime.lastModified) && + Objects.equals(this.lastModifiedBy, projectTime.lastModifiedBy) && + Objects.equals(this.status, projectTime.status) && + equalsNullable(this.metadata, projectTime.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, start, end, breakTimeTotalMinutes, breakTimes, duration, changed, notes, user, task, billable, startLocation, endLocation, startPlatform, endPlatform, lastModified, lastModifiedBy, status, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTime {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" task: ").append(toIndentedString(task)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeCreate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeCreate.java new file mode 100644 index 0000000..f70a1b9 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeCreate.java @@ -0,0 +1,497 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.LocationCreate; +import com.timr.api.models.ProjectTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * ProjectTimeCreate + */ +@JsonPropertyOrder({ + ProjectTimeCreate.JSON_PROPERTY_START, + ProjectTimeCreate.JSON_PROPERTY_END, + ProjectTimeCreate.JSON_PROPERTY_BREAK_TIMES, + ProjectTimeCreate.JSON_PROPERTY_CHANGED, + ProjectTimeCreate.JSON_PROPERTY_NOTES, + ProjectTimeCreate.JSON_PROPERTY_TASK_ID, + ProjectTimeCreate.JSON_PROPERTY_BILLABLE, + ProjectTimeCreate.JSON_PROPERTY_STATUS, + ProjectTimeCreate.JSON_PROPERTY_METADATA, + ProjectTimeCreate.JSON_PROPERTY_USER_ID, + ProjectTimeCreate.JSON_PROPERTY_START_LOCATION, + ProjectTimeCreate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTimeCreate { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nonnull + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + @jakarta.annotation.Nullable + private JsonNullable> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nonnull + private Boolean changed; + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private JsonNullable notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TASK_ID = "task_id"; + @jakarta.annotation.Nonnull + private String taskId; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + @jakarta.annotation.Nullable + private JsonNullable billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private ProjectTimeStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_USER_ID = "user_id"; + @jakarta.annotation.Nonnull + private String userId; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + @jakarta.annotation.Nullable + private JsonNullable startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + @jakarta.annotation.Nullable + private JsonNullable endLocation = JsonNullable.undefined(); + + public ProjectTimeCreate() { + } + + public ProjectTimeCreate start(@jakarta.annotation.Nonnull OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nonnull OffsetDateTime start) { + this.start = start; + } + + + public ProjectTimeCreate end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public ProjectTimeCreate breakTimes(@jakarta.annotation.Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public ProjectTimeCreate addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public ProjectTimeCreate changed(@jakarta.annotation.Nonnull Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(@jakarta.annotation.Nonnull Boolean changed) { + this.changed = changed; + } + + + public ProjectTimeCreate notes(@jakarta.annotation.Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public ProjectTimeCreate taskId(@jakarta.annotation.Nonnull String taskId) { + + this.taskId = taskId; + return this; + } + + /** + * Get taskId + * @return taskId + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TASK_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getTaskId() { + return taskId; + } + + + @JsonProperty(value = JSON_PROPERTY_TASK_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTaskId(@jakarta.annotation.Nonnull String taskId) { + this.taskId = taskId; + } + + + public ProjectTimeCreate billable(@jakarta.annotation.Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public ProjectTimeCreate status(@jakarta.annotation.Nonnull ProjectTimeStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public ProjectTimeStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull ProjectTimeStatus status) { + this.status = status; + } + + + public ProjectTimeCreate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public ProjectTimeCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public ProjectTimeCreate userId(@jakarta.annotation.Nonnull String userId) { + + this.userId = userId; + return this; + } + + /** + * Get userId + * @return userId + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getUserId() { + return userId; + } + + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUserId(@jakarta.annotation.Nonnull String userId) { + this.userId = userId; + } + + + public ProjectTimeCreate startLocation(@jakarta.annotation.Nullable LocationCreate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public ProjectTimeCreate endLocation(@jakarta.annotation.Nullable LocationCreate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTimeCreate projectTimeCreate = (ProjectTimeCreate) o; + return Objects.equals(this.start, projectTimeCreate.start) && + equalsNullable(this.end, projectTimeCreate.end) && + equalsNullable(this.breakTimes, projectTimeCreate.breakTimes) && + Objects.equals(this.changed, projectTimeCreate.changed) && + equalsNullable(this.notes, projectTimeCreate.notes) && + Objects.equals(this.taskId, projectTimeCreate.taskId) && + equalsNullable(this.billable, projectTimeCreate.billable) && + Objects.equals(this.status, projectTimeCreate.status) && + equalsNullable(this.metadata, projectTimeCreate.metadata) && + Objects.equals(this.userId, projectTimeCreate.userId) && + equalsNullable(this.startLocation, projectTimeCreate.startLocation) && + equalsNullable(this.endLocation, projectTimeCreate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, hashCodeNullable(end), hashCodeNullable(breakTimes), changed, hashCodeNullable(notes), taskId, hashCodeNullable(billable), status, hashCodeNullable(metadata), userId, hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTimeCreate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" taskId: ").append(toIndentedString(taskId)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeStatus.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeStatus.java new file mode 100644 index 0000000..8276301 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeStatus.java @@ -0,0 +1,72 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Processing state of a Project Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + */ +public enum ProjectTimeStatus { + + RUNNING("running"), + + PAUSED("paused"), + + CHANGEABLE("changeable"), + + LOCKED("locked"), + + APPROVED("approved"), + + CLEARED("cleared"), + + CLOSED("closed"), + + ARCHIVED("archived"); + + private String value; + + ProjectTimeStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ProjectTimeStatus fromValue(String value) { + for (ProjectTimeStatus b : ProjectTimeStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeUpdate.java new file mode 100644 index 0000000..7b536af --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeUpdate.java @@ -0,0 +1,456 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.LocationUpdate; +import com.timr.api.models.ProjectTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * ProjectTimeUpdate + */ +@JsonPropertyOrder({ + ProjectTimeUpdate.JSON_PROPERTY_START, + ProjectTimeUpdate.JSON_PROPERTY_END, + ProjectTimeUpdate.JSON_PROPERTY_BREAK_TIMES, + ProjectTimeUpdate.JSON_PROPERTY_CHANGED, + ProjectTimeUpdate.JSON_PROPERTY_NOTES, + ProjectTimeUpdate.JSON_PROPERTY_TASK_ID, + ProjectTimeUpdate.JSON_PROPERTY_BILLABLE, + ProjectTimeUpdate.JSON_PROPERTY_STATUS, + ProjectTimeUpdate.JSON_PROPERTY_METADATA, + ProjectTimeUpdate.JSON_PROPERTY_START_LOCATION, + ProjectTimeUpdate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTimeUpdate { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private JsonNullable start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + @jakarta.annotation.Nullable + private JsonNullable> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nullable + private JsonNullable changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private JsonNullable notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TASK_ID = "task_id"; + @jakarta.annotation.Nullable + private JsonNullable taskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + @jakarta.annotation.Nullable + private JsonNullable billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nullable + private JsonNullable status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + @jakarta.annotation.Nullable + private JsonNullable startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + @jakarta.annotation.Nullable + private JsonNullable endLocation = JsonNullable.undefined(); + + public ProjectTimeUpdate() { + } + + public ProjectTimeUpdate start(@jakarta.annotation.Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public ProjectTimeUpdate end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public ProjectTimeUpdate breakTimes(@jakarta.annotation.Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public ProjectTimeUpdate addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public ProjectTimeUpdate changed(@jakarta.annotation.Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public ProjectTimeUpdate notes(@jakarta.annotation.Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public ProjectTimeUpdate taskId(@jakarta.annotation.Nullable String taskId) { + this.taskId = JsonNullable.of(taskId); + + return this; + } + + /** + * Get taskId + * @return taskId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getTaskId() { + return taskId; + } + + @JsonProperty(JSON_PROPERTY_TASK_ID) + public void setTaskId(JsonNullable taskId) { + this.taskId = taskId; + } + + + + public ProjectTimeUpdate billable(@jakarta.annotation.Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public ProjectTimeUpdate status(@jakarta.annotation.Nullable ProjectTimeStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public ProjectTimeUpdate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public ProjectTimeUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public ProjectTimeUpdate startLocation(@jakarta.annotation.Nullable LocationUpdate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public ProjectTimeUpdate endLocation(@jakarta.annotation.Nullable LocationUpdate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTimeUpdate projectTimeUpdate = (ProjectTimeUpdate) o; + return equalsNullable(this.start, projectTimeUpdate.start) && + equalsNullable(this.end, projectTimeUpdate.end) && + equalsNullable(this.breakTimes, projectTimeUpdate.breakTimes) && + equalsNullable(this.changed, projectTimeUpdate.changed) && + equalsNullable(this.notes, projectTimeUpdate.notes) && + equalsNullable(this.taskId, projectTimeUpdate.taskId) && + equalsNullable(this.billable, projectTimeUpdate.billable) && + equalsNullable(this.status, projectTimeUpdate.status) && + equalsNullable(this.metadata, projectTimeUpdate.metadata) && + equalsNullable(this.startLocation, projectTimeUpdate.startLocation) && + equalsNullable(this.endLocation, projectTimeUpdate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(changed), hashCodeNullable(notes), hashCodeNullable(taskId), hashCodeNullable(billable), hashCodeNullable(status), hashCodeNullable(metadata), hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTimeUpdate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" taskId: ").append(toIndentedString(taskId)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeUpsert.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeUpsert.java new file mode 100644 index 0000000..ef6a649 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimeUpsert.java @@ -0,0 +1,395 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.ProjectTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * ProjectTimeUpsert + */ +@JsonPropertyOrder({ + ProjectTimeUpsert.JSON_PROPERTY_START, + ProjectTimeUpsert.JSON_PROPERTY_END, + ProjectTimeUpsert.JSON_PROPERTY_BREAK_TIMES, + ProjectTimeUpsert.JSON_PROPERTY_CHANGED, + ProjectTimeUpsert.JSON_PROPERTY_NOTES, + ProjectTimeUpsert.JSON_PROPERTY_TASK_ID, + ProjectTimeUpsert.JSON_PROPERTY_BILLABLE, + ProjectTimeUpsert.JSON_PROPERTY_STATUS, + ProjectTimeUpsert.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTimeUpsert { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private JsonNullable start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + @jakarta.annotation.Nullable + private JsonNullable> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nullable + private JsonNullable changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private JsonNullable notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TASK_ID = "task_id"; + @jakarta.annotation.Nullable + private JsonNullable taskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + @jakarta.annotation.Nullable + private JsonNullable billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nullable + private JsonNullable status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public ProjectTimeUpsert() { + } + + public ProjectTimeUpsert start(@jakarta.annotation.Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public ProjectTimeUpsert end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public ProjectTimeUpsert breakTimes(@jakarta.annotation.Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public ProjectTimeUpsert addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public ProjectTimeUpsert changed(@jakarta.annotation.Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public ProjectTimeUpsert notes(@jakarta.annotation.Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public ProjectTimeUpsert taskId(@jakarta.annotation.Nullable String taskId) { + this.taskId = JsonNullable.of(taskId); + + return this; + } + + /** + * Get taskId + * @return taskId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getTaskId() { + return taskId; + } + + @JsonProperty(JSON_PROPERTY_TASK_ID) + public void setTaskId(JsonNullable taskId) { + this.taskId = taskId; + } + + + + public ProjectTimeUpsert billable(@jakarta.annotation.Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public ProjectTimeUpsert status(@jakarta.annotation.Nullable ProjectTimeStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public ProjectTimeUpsert metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public ProjectTimeUpsert putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTimeUpsert projectTimeUpsert = (ProjectTimeUpsert) o; + return equalsNullable(this.start, projectTimeUpsert.start) && + equalsNullable(this.end, projectTimeUpsert.end) && + equalsNullable(this.breakTimes, projectTimeUpsert.breakTimes) && + equalsNullable(this.changed, projectTimeUpsert.changed) && + equalsNullable(this.notes, projectTimeUpsert.notes) && + equalsNullable(this.taskId, projectTimeUpsert.taskId) && + equalsNullable(this.billable, projectTimeUpsert.billable) && + equalsNullable(this.status, projectTimeUpsert.status) && + equalsNullable(this.metadata, projectTimeUpsert.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(changed), hashCodeNullable(notes), hashCodeNullable(taskId), hashCodeNullable(billable), hashCodeNullable(status), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTimeUpsert {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" taskId: ").append(toIndentedString(taskId)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimesPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimesPage.java new file mode 100644 index 0000000..82b7e1b --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimesPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.ProjectTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * ProjectTimesPage + */ +@JsonPropertyOrder({ + ProjectTimesPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + ProjectTimesPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class ProjectTimesPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public ProjectTimesPage() { + } + + public ProjectTimesPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public ProjectTimesPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public ProjectTimesPage addDataItem(ProjectTime dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProjectTimesPage projectTimesPage = (ProjectTimesPage) o; + return Objects.equals(this.nextPageToken, projectTimesPage.nextPageToken) && + Objects.equals(this.data, projectTimesPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProjectTimesPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimesSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimesSortColumn.java new file mode 100644 index 0000000..d12df07 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/ProjectTimesSortColumn.java @@ -0,0 +1,60 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Project Times. + */ +public enum ProjectTimesSortColumn { + + START("start"), + + LAST_MODIFIED("last_modified"); + + private String value; + + ProjectTimesSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ProjectTimesSortColumn fromValue(String value) { + for (ProjectTimesSortColumn b : ProjectTimesSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/RecordingLockType.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/RecordingLockType.java new file mode 100644 index 0000000..12bef94 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/RecordingLockType.java @@ -0,0 +1,64 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Whether the assigned User may record on the Task, and where the lock comes from. `recordable` allows recording; `locked_automatically` follows the Task's lock date; `locked_manually` and `unlocked_manually` are explicit overrides for this assignment. + */ +public enum RecordingLockType { + + RECORDABLE("recordable"), + + LOCKED_AUTOMATICALLY("locked_automatically"), + + LOCKED_MANUALLY("locked_manually"), + + UNLOCKED_MANUALLY("unlocked_manually"); + + private String value; + + RecordingLockType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static RecordingLockType fromValue(String value) { + for (RecordingLockType b : RecordingLockType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/RecordingModeUser.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/RecordingModeUser.java new file mode 100644 index 0000000..2b139cf --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/RecordingModeUser.java @@ -0,0 +1,62 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Whether a User may record this Working Time Type themselves. Only meaningful for day-based types. + */ +public enum RecordingModeUser { + + NOT_ALLOWED("not_allowed"), + + ALLOWED("allowed"), + + BY_REQUEST("by_request"); + + private String value; + + RecordingModeUser(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static RecordingModeUser fromValue(String value) { + for (RecordingModeUser b : RecordingModeUser.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/SortDirection.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/SortDirection.java new file mode 100644 index 0000000..cdf57b0 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/SortDirection.java @@ -0,0 +1,60 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort direction — `asc` for ascending, `dsc` for descending. + */ +public enum SortDirection { + + ASC("asc"), + + DSC("dsc"); + + private String value; + + SortDirection(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static SortDirection fromValue(String value) { + for (SortDirection b : SortDirection.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Task.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Task.java new file mode 100644 index 0000000..1f12465 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Task.java @@ -0,0 +1,1049 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningType; +import com.timr.api.models.TaskLocation; +import com.timr.api.models.TaskPartial; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A task, placed in the tree by `parent_task`, with the full path from the root in `breadcrumbs`. `bookable` and `billable` control recording and invoicing; `lock_date`, time windows and location constrain what may be recorded. + */ +@JsonPropertyOrder({ + Task.JSON_PROPERTY_ID, + Task.JSON_PROPERTY_NAME, + Task.JSON_PROPERTY_BREADCRUMBS, + Task.JSON_PROPERTY_EXTERNAL_ID, + Task.JSON_PROPERTY_PARENT_TASK, + Task.JSON_PROPERTY_DESCRIPTION, + Task.JSON_PROPERTY_DESCRIPTION_EXTERNAL, + Task.JSON_PROPERTY_BOOKABLE, + Task.JSON_PROPERTY_BILLABLE, + Task.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + Task.JSON_PROPERTY_START_DATE, + Task.JSON_PROPERTY_END_DATE, + Task.JSON_PROPERTY_LOCK_DATE, + Task.JSON_PROPERTY_EARLIEST_START_TIME, + Task.JSON_PROPERTY_LATEST_END_TIME, + Task.JSON_PROPERTY_ACTIVE_FROM, + Task.JSON_PROPERTY_ACTIVE_TO, + Task.JSON_PROPERTY_BUDGET_INHERITED, + Task.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + Task.JSON_PROPERTY_BUDGET_HOURS_PLANNED, + Task.JSON_PROPERTY_BUDGET_HOURLY_RATE, + Task.JSON_PROPERTY_BUDGET_PLANNED, + Task.JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, + Task.JSON_PROPERTY_LOCATION_INHERITED, + Task.JSON_PROPERTY_LOCATION, + Task.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + Task.JSON_PROPERTY_CUSTOM_FIELD1, + Task.JSON_PROPERTY_CUSTOM_FIELD2, + Task.JSON_PROPERTY_CUSTOM_FIELD3, + Task.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Task { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + @jakarta.annotation.Nonnull + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public static final String JSON_PROPERTY_PARENT_TASK = "parent_task"; + @jakarta.annotation.Nullable + private TaskPartial parentTask; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nullable + private String description; + + public static final String JSON_PROPERTY_DESCRIPTION_EXTERNAL = "description_external"; + @jakarta.annotation.Nullable + private String descriptionExternal; + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + @jakarta.annotation.Nonnull + private Boolean bookable; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + @jakarta.annotation.Nonnull + private Boolean billable; + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + @jakarta.annotation.Nonnull + private Boolean projectTimeNotesRequired; + + public static final String JSON_PROPERTY_START_DATE = "start_date"; + @jakarta.annotation.Nullable + private LocalDate startDate; + + public static final String JSON_PROPERTY_END_DATE = "end_date"; + @jakarta.annotation.Nullable + private LocalDate endDate; + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + @jakarta.annotation.Nullable + private JsonNullable lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + @jakarta.annotation.Nullable + private JsonNullable earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + @jakarta.annotation.Nullable + private JsonNullable latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACTIVE_FROM = "active_from"; + @jakarta.annotation.Nullable + private LocalDate activeFrom; + + public static final String JSON_PROPERTY_ACTIVE_TO = "active_to"; + @jakarta.annotation.Nullable + private LocalDate activeTo; + + public static final String JSON_PROPERTY_BUDGET_INHERITED = "budget_inherited"; + @jakarta.annotation.Nullable + private JsonNullable budgetInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + @jakarta.annotation.Nullable + private JsonNullable budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURS_PLANNED = "budget_hours_planned"; + @jakarta.annotation.Nullable + private JsonNullable budgetHoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURLY_RATE = "budget_hourly_rate"; + @jakarta.annotation.Nullable + private JsonNullable budgetHourlyRate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNED = "budget_planned"; + @jakarta.annotation.Nullable + private JsonNullable budgetPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES = "budget_include_non_billable_project_times"; + @jakarta.annotation.Nullable + private JsonNullable budgetIncludeNonBillableProjectTimes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + @jakarta.annotation.Nullable + private JsonNullable locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + @jakarta.annotation.Nullable + private JsonNullable location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + @jakarta.annotation.Nullable + private JsonNullable locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + @jakarta.annotation.Nullable + private String customField1; + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + @jakarta.annotation.Nullable + private String customField2; + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + @jakarta.annotation.Nullable + private String customField3; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public Task() { + } + + public Task id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public Task name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public Task breadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public Task externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + public Task parentTask(@jakarta.annotation.Nullable TaskPartial parentTask) { + + this.parentTask = parentTask; + return this; + } + + /** + * Get parentTask + * @return parentTask + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public TaskPartial getParentTask() { + return parentTask; + } + + + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setParentTask(@jakarta.annotation.Nullable TaskPartial parentTask) { + this.parentTask = parentTask; + } + + + public Task description(@jakarta.annotation.Nullable String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@jakarta.annotation.Nullable String description) { + this.description = description; + } + + + public Task descriptionExternal(@jakarta.annotation.Nullable String descriptionExternal) { + + this.descriptionExternal = descriptionExternal; + return this; + } + + /** + * Get descriptionExternal + * @return descriptionExternal + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDescriptionExternal() { + return descriptionExternal; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescriptionExternal(@jakarta.annotation.Nullable String descriptionExternal) { + this.descriptionExternal = descriptionExternal; + } + + + public Task bookable(@jakarta.annotation.Nonnull Boolean bookable) { + + this.bookable = bookable; + return this; + } + + /** + * Get bookable + * @return bookable + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBookable() { + return bookable; + } + + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBookable(@jakarta.annotation.Nonnull Boolean bookable) { + this.bookable = bookable; + } + + + public Task billable(@jakarta.annotation.Nonnull Boolean billable) { + + this.billable = billable; + return this; + } + + /** + * Get billable + * @return billable + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBillable() { + return billable; + } + + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBillable(@jakarta.annotation.Nonnull Boolean billable) { + this.billable = billable; + } + + + public Task projectTimeNotesRequired(@jakarta.annotation.Nonnull Boolean projectTimeNotesRequired) { + + this.projectTimeNotesRequired = projectTimeNotesRequired; + return this; + } + + /** + * Get projectTimeNotesRequired + * @return projectTimeNotesRequired + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setProjectTimeNotesRequired(@jakarta.annotation.Nonnull Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + public Task startDate(@jakarta.annotation.Nullable LocalDate startDate) { + + this.startDate = startDate; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return startDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getStartDate() { + return startDate; + } + + + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartDate(@jakarta.annotation.Nullable LocalDate startDate) { + this.startDate = startDate; + } + + + public Task endDate(@jakarta.annotation.Nullable LocalDate endDate) { + + this.endDate = endDate; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return endDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getEndDate() { + return endDate; + } + + + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndDate(@jakarta.annotation.Nullable LocalDate endDate) { + this.endDate = endDate; + } + + + public Task lockDate(@jakarta.annotation.Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return lockDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public Task earliestStartTime(@jakarta.annotation.Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * time of day (ISO-8601) + * @return earliestStartTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public Task latestEndTime(@jakarta.annotation.Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * time of day (ISO-8601) + * @return latestEndTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public Task activeFrom(@jakarta.annotation.Nullable LocalDate activeFrom) { + + this.activeFrom = activeFrom; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return activeFrom + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ACTIVE_FROM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getActiveFrom() { + return activeFrom; + } + + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_FROM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActiveFrom(@jakarta.annotation.Nullable LocalDate activeFrom) { + this.activeFrom = activeFrom; + } + + + public Task activeTo(@jakarta.annotation.Nullable LocalDate activeTo) { + + this.activeTo = activeTo; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return activeTo + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ACTIVE_TO, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getActiveTo() { + return activeTo; + } + + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_TO, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActiveTo(@jakarta.annotation.Nullable LocalDate activeTo) { + this.activeTo = activeTo; + } + + + public Task budgetInherited(@jakarta.annotation.Nullable Boolean budgetInherited) { + this.budgetInherited = JsonNullable.of(budgetInherited); + + return this; + } + + /** + * Get budgetInherited + * @return budgetInherited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetInherited() { + return budgetInherited; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INHERITED) + public void setBudgetInherited(JsonNullable budgetInherited) { + this.budgetInherited = budgetInherited; + } + + + + public Task budgetPlanningType(@jakarta.annotation.Nullable BudgetPlanningType budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * Get budgetPlanningType + * @return budgetPlanningType + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public Task budgetHoursPlanned(@jakarta.annotation.Nullable BigDecimal budgetHoursPlanned) { + this.budgetHoursPlanned = JsonNullable.of(budgetHoursPlanned); + + return this; + } + + /** + * Get budgetHoursPlanned + * @return budgetHoursPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetHoursPlanned() { + return budgetHoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURS_PLANNED) + public void setBudgetHoursPlanned(JsonNullable budgetHoursPlanned) { + this.budgetHoursPlanned = budgetHoursPlanned; + } + + + + public Task budgetHourlyRate(@jakarta.annotation.Nullable BigDecimal budgetHourlyRate) { + this.budgetHourlyRate = JsonNullable.of(budgetHourlyRate); + + return this; + } + + /** + * Get budgetHourlyRate + * @return budgetHourlyRate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURLY_RATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetHourlyRate() { + return budgetHourlyRate; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURLY_RATE) + public void setBudgetHourlyRate(JsonNullable budgetHourlyRate) { + this.budgetHourlyRate = budgetHourlyRate; + } + + + + public Task budgetPlanned(@jakarta.annotation.Nullable BigDecimal budgetPlanned) { + this.budgetPlanned = JsonNullable.of(budgetPlanned); + + return this; + } + + /** + * Get budgetPlanned + * @return budgetPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetPlanned() { + return budgetPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNED) + public void setBudgetPlanned(JsonNullable budgetPlanned) { + this.budgetPlanned = budgetPlanned; + } + + + + public Task budgetIncludeNonBillableProjectTimes(@jakarta.annotation.Nullable Boolean budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = JsonNullable.of(budgetIncludeNonBillableProjectTimes); + + return this; + } + + /** + * Get budgetIncludeNonBillableProjectTimes + * @return budgetIncludeNonBillableProjectTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetIncludeNonBillableProjectTimes() { + return budgetIncludeNonBillableProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES) + public void setBudgetIncludeNonBillableProjectTimes(JsonNullable budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes; + } + + + + public Task locationInherited(@jakarta.annotation.Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * Get locationInherited + * @return locationInherited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public Task location(@jakarta.annotation.Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public Task locationRestrictionRadiusMeters(@jakarta.annotation.Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * Get locationRestrictionRadiusMeters + * @return locationRestrictionRadiusMeters + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public Task customField1(@jakarta.annotation.Nullable String customField1) { + + this.customField1 = customField1; + return this; + } + + /** + * Get customField1 + * @return customField1 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCustomField1() { + return customField1; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField1(@jakarta.annotation.Nullable String customField1) { + this.customField1 = customField1; + } + + + public Task customField2(@jakarta.annotation.Nullable String customField2) { + + this.customField2 = customField2; + return this; + } + + /** + * Get customField2 + * @return customField2 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCustomField2() { + return customField2; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField2(@jakarta.annotation.Nullable String customField2) { + this.customField2 = customField2; + } + + + public Task customField3(@jakarta.annotation.Nullable String customField3) { + + this.customField3 = customField3; + return this; + } + + /** + * Get customField3 + * @return customField3 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCustomField3() { + return customField3; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField3(@jakarta.annotation.Nullable String customField3) { + this.customField3 = customField3; + } + + + public Task metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public Task putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Task task = (Task) o; + return Objects.equals(this.id, task.id) && + Objects.equals(this.name, task.name) && + Objects.equals(this.breadcrumbs, task.breadcrumbs) && + Objects.equals(this.externalId, task.externalId) && + Objects.equals(this.parentTask, task.parentTask) && + Objects.equals(this.description, task.description) && + Objects.equals(this.descriptionExternal, task.descriptionExternal) && + Objects.equals(this.bookable, task.bookable) && + Objects.equals(this.billable, task.billable) && + Objects.equals(this.projectTimeNotesRequired, task.projectTimeNotesRequired) && + Objects.equals(this.startDate, task.startDate) && + Objects.equals(this.endDate, task.endDate) && + equalsNullable(this.lockDate, task.lockDate) && + equalsNullable(this.earliestStartTime, task.earliestStartTime) && + equalsNullable(this.latestEndTime, task.latestEndTime) && + Objects.equals(this.activeFrom, task.activeFrom) && + Objects.equals(this.activeTo, task.activeTo) && + equalsNullable(this.budgetInherited, task.budgetInherited) && + equalsNullable(this.budgetPlanningType, task.budgetPlanningType) && + equalsNullable(this.budgetHoursPlanned, task.budgetHoursPlanned) && + equalsNullable(this.budgetHourlyRate, task.budgetHourlyRate) && + equalsNullable(this.budgetPlanned, task.budgetPlanned) && + equalsNullable(this.budgetIncludeNonBillableProjectTimes, task.budgetIncludeNonBillableProjectTimes) && + equalsNullable(this.locationInherited, task.locationInherited) && + equalsNullable(this.location, task.location) && + equalsNullable(this.locationRestrictionRadiusMeters, task.locationRestrictionRadiusMeters) && + Objects.equals(this.customField1, task.customField1) && + Objects.equals(this.customField2, task.customField2) && + Objects.equals(this.customField3, task.customField3) && + equalsNullable(this.metadata, task.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId, parentTask, description, descriptionExternal, bookable, billable, projectTimeNotesRequired, startDate, endDate, hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), activeFrom, activeTo, hashCodeNullable(budgetInherited), hashCodeNullable(budgetPlanningType), hashCodeNullable(budgetHoursPlanned), hashCodeNullable(budgetHourlyRate), hashCodeNullable(budgetPlanned), hashCodeNullable(budgetIncludeNonBillableProjectTimes), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), customField1, customField2, customField3, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Task {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" parentTask: ").append(toIndentedString(parentTask)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" activeFrom: ").append(toIndentedString(activeFrom)).append("\n"); + sb.append(" activeTo: ").append(toIndentedString(activeTo)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskBase.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskBase.java new file mode 100644 index 0000000..f4fcb76 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskBase.java @@ -0,0 +1,863 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningTypeRequest; +import com.timr.api.models.TaskLocation; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskBase + */ +@JsonPropertyOrder({ + TaskBase.JSON_PROPERTY_NAME, + TaskBase.JSON_PROPERTY_PARENT_TASK_ID, + TaskBase.JSON_PROPERTY_EXTERNAL_ID, + TaskBase.JSON_PROPERTY_DESCRIPTION, + TaskBase.JSON_PROPERTY_DESCRIPTION_EXTERNAL, + TaskBase.JSON_PROPERTY_BOOKABLE, + TaskBase.JSON_PROPERTY_BILLABLE, + TaskBase.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + TaskBase.JSON_PROPERTY_START_DATE, + TaskBase.JSON_PROPERTY_END_DATE, + TaskBase.JSON_PROPERTY_LOCK_DATE, + TaskBase.JSON_PROPERTY_EARLIEST_START_TIME, + TaskBase.JSON_PROPERTY_LATEST_END_TIME, + TaskBase.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + TaskBase.JSON_PROPERTY_BUDGET_HOURS_PLANNED, + TaskBase.JSON_PROPERTY_BUDGET_HOURLY_RATE, + TaskBase.JSON_PROPERTY_BUDGET_PLANNED, + TaskBase.JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, + TaskBase.JSON_PROPERTY_LOCATION_INHERITED, + TaskBase.JSON_PROPERTY_LOCATION, + TaskBase.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + TaskBase.JSON_PROPERTY_CUSTOM_FIELD1, + TaskBase.JSON_PROPERTY_CUSTOM_FIELD2, + TaskBase.JSON_PROPERTY_CUSTOM_FIELD3, + TaskBase.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskBase { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private JsonNullable name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PARENT_TASK_ID = "parent_task_id"; + @jakarta.annotation.Nullable + private JsonNullable parentTaskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private JsonNullable externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nullable + private JsonNullable description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION_EXTERNAL = "description_external"; + @jakarta.annotation.Nullable + private JsonNullable descriptionExternal = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + @jakarta.annotation.Nullable + private JsonNullable bookable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + @jakarta.annotation.Nullable + private JsonNullable billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + @jakarta.annotation.Nullable + private JsonNullable projectTimeNotesRequired = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_DATE = "start_date"; + @jakarta.annotation.Nullable + private JsonNullable startDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_DATE = "end_date"; + @jakarta.annotation.Nullable + private JsonNullable endDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + @jakarta.annotation.Nullable + private JsonNullable lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + @jakarta.annotation.Nullable + private JsonNullable earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + @jakarta.annotation.Nullable + private JsonNullable latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + @jakarta.annotation.Nullable + private JsonNullable budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURS_PLANNED = "budget_hours_planned"; + @jakarta.annotation.Nullable + private JsonNullable budgetHoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURLY_RATE = "budget_hourly_rate"; + @jakarta.annotation.Nullable + private JsonNullable budgetHourlyRate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNED = "budget_planned"; + @jakarta.annotation.Nullable + private JsonNullable budgetPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES = "budget_include_non_billable_project_times"; + @jakarta.annotation.Nullable + private JsonNullable budgetIncludeNonBillableProjectTimes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + @jakarta.annotation.Nullable + private JsonNullable locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + @jakarta.annotation.Nullable + private JsonNullable location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + @jakarta.annotation.Nullable + private JsonNullable locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + @jakarta.annotation.Nullable + private JsonNullable customField1 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + @jakarta.annotation.Nullable + private JsonNullable customField2 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + @jakarta.annotation.Nullable + private JsonNullable customField3 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public TaskBase() { + } + + public TaskBase name(@jakarta.annotation.Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public TaskBase parentTaskId(@jakarta.annotation.Nullable String parentTaskId) { + this.parentTaskId = JsonNullable.of(parentTaskId); + + return this; + } + + /** + * returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @return parentTaskId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getParentTaskId() { + return parentTaskId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TASK_ID) + public void setParentTaskId(JsonNullable parentTaskId) { + this.parentTaskId = parentTaskId; + } + + + + public TaskBase externalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public TaskBase description(@jakarta.annotation.Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TaskBase descriptionExternal(@jakarta.annotation.Nullable String descriptionExternal) { + this.descriptionExternal = JsonNullable.of(descriptionExternal); + + return this; + } + + /** + * Get descriptionExternal + * @return descriptionExternal + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDescriptionExternal() { + return descriptionExternal; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION_EXTERNAL) + public void setDescriptionExternal(JsonNullable descriptionExternal) { + this.descriptionExternal = descriptionExternal; + } + + + + public TaskBase bookable(@jakarta.annotation.Nullable Boolean bookable) { + this.bookable = JsonNullable.of(bookable); + + return this; + } + + /** + * when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @return bookable + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBookable() { + return bookable; + } + + @JsonProperty(JSON_PROPERTY_BOOKABLE) + public void setBookable(JsonNullable bookable) { + this.bookable = bookable; + } + + + + public TaskBase billable(@jakarta.annotation.Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public TaskBase projectTimeNotesRequired(@jakarta.annotation.Nullable Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = JsonNullable.of(projectTimeNotesRequired); + + return this; + } + + /** + * depending on this property project times booked on this task have to include notes or not + * @return projectTimeNotesRequired + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + @JsonProperty(JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED) + public void setProjectTimeNotesRequired(JsonNullable projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + + public TaskBase startDate(@jakarta.annotation.Nullable LocalDate startDate) { + this.startDate = JsonNullable.of(startDate); + + return this; + } + + /** + * the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return startDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartDate() { + return startDate; + } + + @JsonProperty(JSON_PROPERTY_START_DATE) + public void setStartDate(JsonNullable startDate) { + this.startDate = startDate; + } + + + + public TaskBase endDate(@jakarta.annotation.Nullable LocalDate endDate) { + this.endDate = JsonNullable.of(endDate); + + return this; + } + + /** + * the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return endDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndDate() { + return endDate; + } + + @JsonProperty(JSON_PROPERTY_END_DATE) + public void setEndDate(JsonNullable endDate) { + this.endDate = endDate; + } + + + + public TaskBase lockDate(@jakarta.annotation.Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + * @return lockDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public TaskBase earliestStartTime(@jakarta.annotation.Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked before this time + * @return earliestStartTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public TaskBase latestEndTime(@jakarta.annotation.Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked after this time + * @return latestEndTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public TaskBase budgetPlanningType(@jakarta.annotation.Nullable BudgetPlanningTypeRequest budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * @return budgetPlanningType + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public TaskBase budgetHoursPlanned(@jakarta.annotation.Nullable BigDecimal budgetHoursPlanned) { + this.budgetHoursPlanned = JsonNullable.of(budgetHoursPlanned); + + return this; + } + + /** + * how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetHoursPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetHoursPlanned() { + return budgetHoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURS_PLANNED) + public void setBudgetHoursPlanned(JsonNullable budgetHoursPlanned) { + this.budgetHoursPlanned = budgetHoursPlanned; + } + + + + public TaskBase budgetHourlyRate(@jakarta.annotation.Nullable BigDecimal budgetHourlyRate) { + this.budgetHourlyRate = JsonNullable.of(budgetHourlyRate); + + return this; + } + + /** + * depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * @return budgetHourlyRate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURLY_RATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetHourlyRate() { + return budgetHourlyRate; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURLY_RATE) + public void setBudgetHourlyRate(JsonNullable budgetHourlyRate) { + this.budgetHourlyRate = budgetHourlyRate; + } + + + + public TaskBase budgetPlanned(@jakarta.annotation.Nullable BigDecimal budgetPlanned) { + this.budgetPlanned = JsonNullable.of(budgetPlanned); + + return this; + } + + /** + * the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetPlanned() { + return budgetPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNED) + public void setBudgetPlanned(JsonNullable budgetPlanned) { + this.budgetPlanned = budgetPlanned; + } + + + + public TaskBase budgetIncludeNonBillableProjectTimes(@jakarta.annotation.Nullable Boolean budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = JsonNullable.of(budgetIncludeNonBillableProjectTimes); + + return this; + } + + /** + * set this property to true, if you want to include not billable hours for all project times booked on this task + * @return budgetIncludeNonBillableProjectTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetIncludeNonBillableProjectTimes() { + return budgetIncludeNonBillableProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES) + public void setBudgetIncludeNonBillableProjectTimes(JsonNullable budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes; + } + + + + public TaskBase locationInherited(@jakarta.annotation.Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @return locationInherited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public TaskBase location(@jakarta.annotation.Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public TaskBase locationRestrictionRadiusMeters(@jakarta.annotation.Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @return locationRestrictionRadiusMeters + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public TaskBase customField1(@jakarta.annotation.Nullable String customField1) { + this.customField1 = JsonNullable.of(customField1); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField1 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getCustomField1() { + return customField1; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD1) + public void setCustomField1(JsonNullable customField1) { + this.customField1 = customField1; + } + + + + public TaskBase customField2(@jakarta.annotation.Nullable String customField2) { + this.customField2 = JsonNullable.of(customField2); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField2 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getCustomField2() { + return customField2; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD2) + public void setCustomField2(JsonNullable customField2) { + this.customField2 = customField2; + } + + + + public TaskBase customField3(@jakarta.annotation.Nullable String customField3) { + this.customField3 = JsonNullable.of(customField3); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField3 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getCustomField3() { + return customField3; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD3) + public void setCustomField3(JsonNullable customField3) { + this.customField3 = customField3; + } + + + + public TaskBase metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public TaskBase putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskBase taskBase = (TaskBase) o; + return equalsNullable(this.name, taskBase.name) && + equalsNullable(this.parentTaskId, taskBase.parentTaskId) && + equalsNullable(this.externalId, taskBase.externalId) && + equalsNullable(this.description, taskBase.description) && + equalsNullable(this.descriptionExternal, taskBase.descriptionExternal) && + equalsNullable(this.bookable, taskBase.bookable) && + equalsNullable(this.billable, taskBase.billable) && + equalsNullable(this.projectTimeNotesRequired, taskBase.projectTimeNotesRequired) && + equalsNullable(this.startDate, taskBase.startDate) && + equalsNullable(this.endDate, taskBase.endDate) && + equalsNullable(this.lockDate, taskBase.lockDate) && + equalsNullable(this.earliestStartTime, taskBase.earliestStartTime) && + equalsNullable(this.latestEndTime, taskBase.latestEndTime) && + equalsNullable(this.budgetPlanningType, taskBase.budgetPlanningType) && + equalsNullable(this.budgetHoursPlanned, taskBase.budgetHoursPlanned) && + equalsNullable(this.budgetHourlyRate, taskBase.budgetHourlyRate) && + equalsNullable(this.budgetPlanned, taskBase.budgetPlanned) && + equalsNullable(this.budgetIncludeNonBillableProjectTimes, taskBase.budgetIncludeNonBillableProjectTimes) && + equalsNullable(this.locationInherited, taskBase.locationInherited) && + equalsNullable(this.location, taskBase.location) && + equalsNullable(this.locationRestrictionRadiusMeters, taskBase.locationRestrictionRadiusMeters) && + equalsNullable(this.customField1, taskBase.customField1) && + equalsNullable(this.customField2, taskBase.customField2) && + equalsNullable(this.customField3, taskBase.customField3) && + equalsNullable(this.metadata, taskBase.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(name), hashCodeNullable(parentTaskId), hashCodeNullable(externalId), hashCodeNullable(description), hashCodeNullable(descriptionExternal), hashCodeNullable(bookable), hashCodeNullable(billable), hashCodeNullable(projectTimeNotesRequired), hashCodeNullable(startDate), hashCodeNullable(endDate), hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), hashCodeNullable(budgetPlanningType), hashCodeNullable(budgetHoursPlanned), hashCodeNullable(budgetHourlyRate), hashCodeNullable(budgetPlanned), hashCodeNullable(budgetIncludeNonBillableProjectTimes), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), hashCodeNullable(customField1), hashCodeNullable(customField2), hashCodeNullable(customField3), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskBase {\n"); + sb.append(" parentTaskId: ").append(toIndentedString(parentTaskId)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n"); + sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskCreate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskCreate.java new file mode 100644 index 0000000..0273603 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskCreate.java @@ -0,0 +1,869 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningTypeRequest; +import com.timr.api.models.TaskLocation; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskCreate + */ +@JsonPropertyOrder({ + TaskCreate.JSON_PROPERTY_NAME, + TaskCreate.JSON_PROPERTY_PARENT_TASK_ID, + TaskCreate.JSON_PROPERTY_EXTERNAL_ID, + TaskCreate.JSON_PROPERTY_DESCRIPTION, + TaskCreate.JSON_PROPERTY_DESCRIPTION_EXTERNAL, + TaskCreate.JSON_PROPERTY_BOOKABLE, + TaskCreate.JSON_PROPERTY_BILLABLE, + TaskCreate.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + TaskCreate.JSON_PROPERTY_START_DATE, + TaskCreate.JSON_PROPERTY_END_DATE, + TaskCreate.JSON_PROPERTY_LOCK_DATE, + TaskCreate.JSON_PROPERTY_EARLIEST_START_TIME, + TaskCreate.JSON_PROPERTY_LATEST_END_TIME, + TaskCreate.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + TaskCreate.JSON_PROPERTY_BUDGET_HOURS_PLANNED, + TaskCreate.JSON_PROPERTY_BUDGET_HOURLY_RATE, + TaskCreate.JSON_PROPERTY_BUDGET_PLANNED, + TaskCreate.JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, + TaskCreate.JSON_PROPERTY_LOCATION_INHERITED, + TaskCreate.JSON_PROPERTY_LOCATION, + TaskCreate.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + TaskCreate.JSON_PROPERTY_CUSTOM_FIELD1, + TaskCreate.JSON_PROPERTY_CUSTOM_FIELD2, + TaskCreate.JSON_PROPERTY_CUSTOM_FIELD3, + TaskCreate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskCreate { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_PARENT_TASK_ID = "parent_task_id"; + @jakarta.annotation.Nullable + private JsonNullable parentTaskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private JsonNullable externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nullable + private JsonNullable description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION_EXTERNAL = "description_external"; + @jakarta.annotation.Nullable + private JsonNullable descriptionExternal = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + @jakarta.annotation.Nonnull + private Boolean bookable; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + @jakarta.annotation.Nonnull + private Boolean billable; + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + @jakarta.annotation.Nullable + private JsonNullable projectTimeNotesRequired = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_DATE = "start_date"; + @jakarta.annotation.Nullable + private JsonNullable startDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_DATE = "end_date"; + @jakarta.annotation.Nullable + private JsonNullable endDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + @jakarta.annotation.Nullable + private JsonNullable lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + @jakarta.annotation.Nullable + private JsonNullable earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + @jakarta.annotation.Nullable + private JsonNullable latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + @jakarta.annotation.Nullable + private JsonNullable budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURS_PLANNED = "budget_hours_planned"; + @jakarta.annotation.Nullable + private JsonNullable budgetHoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURLY_RATE = "budget_hourly_rate"; + @jakarta.annotation.Nullable + private JsonNullable budgetHourlyRate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNED = "budget_planned"; + @jakarta.annotation.Nullable + private JsonNullable budgetPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES = "budget_include_non_billable_project_times"; + @jakarta.annotation.Nullable + private JsonNullable budgetIncludeNonBillableProjectTimes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + @jakarta.annotation.Nullable + private JsonNullable locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + @jakarta.annotation.Nullable + private JsonNullable location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + @jakarta.annotation.Nullable + private JsonNullable locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + @jakarta.annotation.Nullable + private JsonNullable customField1 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + @jakarta.annotation.Nullable + private JsonNullable customField2 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + @jakarta.annotation.Nullable + private JsonNullable customField3 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public TaskCreate() { + } + + public TaskCreate name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public TaskCreate parentTaskId(@jakarta.annotation.Nullable String parentTaskId) { + this.parentTaskId = JsonNullable.of(parentTaskId); + + return this; + } + + /** + * returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @return parentTaskId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getParentTaskId() { + return parentTaskId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TASK_ID) + public void setParentTaskId(JsonNullable parentTaskId) { + this.parentTaskId = parentTaskId; + } + + + + public TaskCreate externalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public TaskCreate description(@jakarta.annotation.Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TaskCreate descriptionExternal(@jakarta.annotation.Nullable String descriptionExternal) { + this.descriptionExternal = JsonNullable.of(descriptionExternal); + + return this; + } + + /** + * Get descriptionExternal + * @return descriptionExternal + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDescriptionExternal() { + return descriptionExternal; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION_EXTERNAL) + public void setDescriptionExternal(JsonNullable descriptionExternal) { + this.descriptionExternal = descriptionExternal; + } + + + + public TaskCreate bookable(@jakarta.annotation.Nonnull Boolean bookable) { + + this.bookable = bookable; + return this; + } + + /** + * when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @return bookable + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBookable() { + return bookable; + } + + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBookable(@jakarta.annotation.Nonnull Boolean bookable) { + this.bookable = bookable; + } + + + public TaskCreate billable(@jakarta.annotation.Nonnull Boolean billable) { + + this.billable = billable; + return this; + } + + /** + * Get billable + * @return billable + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBillable() { + return billable; + } + + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBillable(@jakarta.annotation.Nonnull Boolean billable) { + this.billable = billable; + } + + + public TaskCreate projectTimeNotesRequired(@jakarta.annotation.Nullable Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = JsonNullable.of(projectTimeNotesRequired); + + return this; + } + + /** + * depending on this property project times booked on this task have to include notes or not + * @return projectTimeNotesRequired + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + @JsonProperty(JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED) + public void setProjectTimeNotesRequired(JsonNullable projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + + public TaskCreate startDate(@jakarta.annotation.Nullable LocalDate startDate) { + this.startDate = JsonNullable.of(startDate); + + return this; + } + + /** + * the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return startDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartDate() { + return startDate; + } + + @JsonProperty(JSON_PROPERTY_START_DATE) + public void setStartDate(JsonNullable startDate) { + this.startDate = startDate; + } + + + + public TaskCreate endDate(@jakarta.annotation.Nullable LocalDate endDate) { + this.endDate = JsonNullable.of(endDate); + + return this; + } + + /** + * the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return endDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndDate() { + return endDate; + } + + @JsonProperty(JSON_PROPERTY_END_DATE) + public void setEndDate(JsonNullable endDate) { + this.endDate = endDate; + } + + + + public TaskCreate lockDate(@jakarta.annotation.Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + * @return lockDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public TaskCreate earliestStartTime(@jakarta.annotation.Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked before this time + * @return earliestStartTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public TaskCreate latestEndTime(@jakarta.annotation.Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked after this time + * @return latestEndTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public TaskCreate budgetPlanningType(@jakarta.annotation.Nullable BudgetPlanningTypeRequest budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * @return budgetPlanningType + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public TaskCreate budgetHoursPlanned(@jakarta.annotation.Nullable BigDecimal budgetHoursPlanned) { + this.budgetHoursPlanned = JsonNullable.of(budgetHoursPlanned); + + return this; + } + + /** + * how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetHoursPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetHoursPlanned() { + return budgetHoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURS_PLANNED) + public void setBudgetHoursPlanned(JsonNullable budgetHoursPlanned) { + this.budgetHoursPlanned = budgetHoursPlanned; + } + + + + public TaskCreate budgetHourlyRate(@jakarta.annotation.Nullable BigDecimal budgetHourlyRate) { + this.budgetHourlyRate = JsonNullable.of(budgetHourlyRate); + + return this; + } + + /** + * depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * @return budgetHourlyRate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURLY_RATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetHourlyRate() { + return budgetHourlyRate; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURLY_RATE) + public void setBudgetHourlyRate(JsonNullable budgetHourlyRate) { + this.budgetHourlyRate = budgetHourlyRate; + } + + + + public TaskCreate budgetPlanned(@jakarta.annotation.Nullable BigDecimal budgetPlanned) { + this.budgetPlanned = JsonNullable.of(budgetPlanned); + + return this; + } + + /** + * the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetPlanned() { + return budgetPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNED) + public void setBudgetPlanned(JsonNullable budgetPlanned) { + this.budgetPlanned = budgetPlanned; + } + + + + public TaskCreate budgetIncludeNonBillableProjectTimes(@jakarta.annotation.Nullable Boolean budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = JsonNullable.of(budgetIncludeNonBillableProjectTimes); + + return this; + } + + /** + * set this property to true, if you want to include not billable hours for all project times booked on this task + * @return budgetIncludeNonBillableProjectTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetIncludeNonBillableProjectTimes() { + return budgetIncludeNonBillableProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES) + public void setBudgetIncludeNonBillableProjectTimes(JsonNullable budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes; + } + + + + public TaskCreate locationInherited(@jakarta.annotation.Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @return locationInherited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public TaskCreate location(@jakarta.annotation.Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public TaskCreate locationRestrictionRadiusMeters(@jakarta.annotation.Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @return locationRestrictionRadiusMeters + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public TaskCreate customField1(@jakarta.annotation.Nullable String customField1) { + this.customField1 = JsonNullable.of(customField1); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField1 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getCustomField1() { + return customField1; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD1) + public void setCustomField1(JsonNullable customField1) { + this.customField1 = customField1; + } + + + + public TaskCreate customField2(@jakarta.annotation.Nullable String customField2) { + this.customField2 = JsonNullable.of(customField2); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField2 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getCustomField2() { + return customField2; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD2) + public void setCustomField2(JsonNullable customField2) { + this.customField2 = customField2; + } + + + + public TaskCreate customField3(@jakarta.annotation.Nullable String customField3) { + this.customField3 = JsonNullable.of(customField3); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField3 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getCustomField3() { + return customField3; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD3) + public void setCustomField3(JsonNullable customField3) { + this.customField3 = customField3; + } + + + + public TaskCreate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public TaskCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskCreate taskCreate = (TaskCreate) o; + return Objects.equals(this.name, taskCreate.name) && + equalsNullable(this.parentTaskId, taskCreate.parentTaskId) && + equalsNullable(this.externalId, taskCreate.externalId) && + equalsNullable(this.description, taskCreate.description) && + equalsNullable(this.descriptionExternal, taskCreate.descriptionExternal) && + Objects.equals(this.bookable, taskCreate.bookable) && + Objects.equals(this.billable, taskCreate.billable) && + equalsNullable(this.projectTimeNotesRequired, taskCreate.projectTimeNotesRequired) && + equalsNullable(this.startDate, taskCreate.startDate) && + equalsNullable(this.endDate, taskCreate.endDate) && + equalsNullable(this.lockDate, taskCreate.lockDate) && + equalsNullable(this.earliestStartTime, taskCreate.earliestStartTime) && + equalsNullable(this.latestEndTime, taskCreate.latestEndTime) && + equalsNullable(this.budgetPlanningType, taskCreate.budgetPlanningType) && + equalsNullable(this.budgetHoursPlanned, taskCreate.budgetHoursPlanned) && + equalsNullable(this.budgetHourlyRate, taskCreate.budgetHourlyRate) && + equalsNullable(this.budgetPlanned, taskCreate.budgetPlanned) && + equalsNullable(this.budgetIncludeNonBillableProjectTimes, taskCreate.budgetIncludeNonBillableProjectTimes) && + equalsNullable(this.locationInherited, taskCreate.locationInherited) && + equalsNullable(this.location, taskCreate.location) && + equalsNullable(this.locationRestrictionRadiusMeters, taskCreate.locationRestrictionRadiusMeters) && + equalsNullable(this.customField1, taskCreate.customField1) && + equalsNullable(this.customField2, taskCreate.customField2) && + equalsNullable(this.customField3, taskCreate.customField3) && + equalsNullable(this.metadata, taskCreate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(name, hashCodeNullable(parentTaskId), hashCodeNullable(externalId), hashCodeNullable(description), hashCodeNullable(descriptionExternal), bookable, billable, hashCodeNullable(projectTimeNotesRequired), hashCodeNullable(startDate), hashCodeNullable(endDate), hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), hashCodeNullable(budgetPlanningType), hashCodeNullable(budgetHoursPlanned), hashCodeNullable(budgetHourlyRate), hashCodeNullable(budgetPlanned), hashCodeNullable(budgetIncludeNonBillableProjectTimes), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), hashCodeNullable(customField1), hashCodeNullable(customField2), hashCodeNullable(customField3), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskCreate {\n"); + sb.append(" parentTaskId: ").append(toIndentedString(parentTaskId)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n"); + sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskLocation.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskLocation.java new file mode 100644 index 0000000..15a9103 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskLocation.java @@ -0,0 +1,308 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * You can define the location of a task by setting this property. If the task has a parent task, the location is inherited if nothing else is explicitly defined. If you set this property to null, the location will be deleted. + */ +@JsonPropertyOrder({ + TaskLocation.JSON_PROPERTY_LAT, + TaskLocation.JSON_PROPERTY_LON, + TaskLocation.JSON_PROPERTY_ADDRESS, + TaskLocation.JSON_PROPERTY_CITY, + TaskLocation.JSON_PROPERTY_ZIP_CODE, + TaskLocation.JSON_PROPERTY_STATE, + TaskLocation.JSON_PROPERTY_COUNTRY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskLocation { + public static final String JSON_PROPERTY_LAT = "lat"; + @jakarta.annotation.Nullable + private Float lat; + + public static final String JSON_PROPERTY_LON = "lon"; + @jakarta.annotation.Nullable + private Float lon; + + public static final String JSON_PROPERTY_ADDRESS = "address"; + @jakarta.annotation.Nullable + private String address; + + public static final String JSON_PROPERTY_CITY = "city"; + @jakarta.annotation.Nullable + private String city; + + public static final String JSON_PROPERTY_ZIP_CODE = "zip_code"; + @jakarta.annotation.Nullable + private String zipCode; + + public static final String JSON_PROPERTY_STATE = "state"; + @jakarta.annotation.Nullable + private String state; + + public static final String JSON_PROPERTY_COUNTRY = "country"; + @jakarta.annotation.Nullable + private String country; + + public TaskLocation() { + } + + public TaskLocation lat(@jakarta.annotation.Nullable Float lat) { + + this.lat = lat; + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Float getLat() { + return lat; + } + + + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLat(@jakarta.annotation.Nullable Float lat) { + this.lat = lat; + } + + + public TaskLocation lon(@jakarta.annotation.Nullable Float lon) { + + this.lon = lon; + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Float getLon() { + return lon; + } + + + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLon(@jakarta.annotation.Nullable Float lon) { + this.lon = lon; + } + + + public TaskLocation address(@jakarta.annotation.Nullable String address) { + + this.address = address; + return this; + } + + /** + * Get address + * @return address + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getAddress() { + return address; + } + + + @JsonProperty(value = JSON_PROPERTY_ADDRESS, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAddress(@jakarta.annotation.Nullable String address) { + this.address = address; + } + + + public TaskLocation city(@jakarta.annotation.Nullable String city) { + + this.city = city; + return this; + } + + /** + * Get city + * @return city + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CITY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCity() { + return city; + } + + + @JsonProperty(value = JSON_PROPERTY_CITY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCity(@jakarta.annotation.Nullable String city) { + this.city = city; + } + + + public TaskLocation zipCode(@jakarta.annotation.Nullable String zipCode) { + + this.zipCode = zipCode; + return this; + } + + /** + * Get zipCode + * @return zipCode + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ZIP_CODE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getZipCode() { + return zipCode; + } + + + @JsonProperty(value = JSON_PROPERTY_ZIP_CODE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setZipCode(@jakarta.annotation.Nullable String zipCode) { + this.zipCode = zipCode; + } + + + public TaskLocation state(@jakarta.annotation.Nullable String state) { + + this.state = state; + return this; + } + + /** + * Get state + * @return state + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_STATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getState() { + return state; + } + + + @JsonProperty(value = JSON_PROPERTY_STATE, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setState(@jakarta.annotation.Nullable String state) { + this.state = state; + } + + + public TaskLocation country(@jakarta.annotation.Nullable String country) { + + this.country = country; + return this; + } + + /** + * the country's international country code + * @return country + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_COUNTRY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCountry() { + return country; + } + + + @JsonProperty(value = JSON_PROPERTY_COUNTRY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCountry(@jakarta.annotation.Nullable String country) { + this.country = country; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskLocation taskLocation = (TaskLocation) o; + return Objects.equals(this.lat, taskLocation.lat) && + Objects.equals(this.lon, taskLocation.lon) && + Objects.equals(this.address, taskLocation.address) && + Objects.equals(this.city, taskLocation.city) && + Objects.equals(this.zipCode, taskLocation.zipCode) && + Objects.equals(this.state, taskLocation.state) && + Objects.equals(this.country, taskLocation.country); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lat, lon, address, city, zipCode, state, country); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskLocation {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskPartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskPartial.java new file mode 100644 index 0000000..d733d86 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskPartial.java @@ -0,0 +1,213 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskPartial + */ +@JsonPropertyOrder({ + TaskPartial.JSON_PROPERTY_ID, + TaskPartial.JSON_PROPERTY_NAME, + TaskPartial.JSON_PROPERTY_BREADCRUMBS, + TaskPartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskPartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + @jakarta.annotation.Nonnull + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public TaskPartial() { + } + + public TaskPartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public TaskPartial name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public TaskPartial breadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public TaskPartial externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskPartial taskPartial = (TaskPartial) o; + return Objects.equals(this.id, taskPartial.id) && + Objects.equals(this.name, taskPartial.name) && + Objects.equals(this.breadcrumbs, taskPartial.breadcrumbs) && + Objects.equals(this.externalId, taskPartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskReduced.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskReduced.java new file mode 100644 index 0000000..cb6bed1 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskReduced.java @@ -0,0 +1,758 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningType; +import com.timr.api.models.TaskLocation; +import com.timr.api.models.TaskPartial; +import java.time.LocalDate; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskReduced + */ +@JsonPropertyOrder({ + TaskReduced.JSON_PROPERTY_ID, + TaskReduced.JSON_PROPERTY_NAME, + TaskReduced.JSON_PROPERTY_BREADCRUMBS, + TaskReduced.JSON_PROPERTY_EXTERNAL_ID, + TaskReduced.JSON_PROPERTY_PARENT_TASK, + TaskReduced.JSON_PROPERTY_DESCRIPTION, + TaskReduced.JSON_PROPERTY_BOOKABLE, + TaskReduced.JSON_PROPERTY_BILLABLE, + TaskReduced.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + TaskReduced.JSON_PROPERTY_LOCK_DATE, + TaskReduced.JSON_PROPERTY_EARLIEST_START_TIME, + TaskReduced.JSON_PROPERTY_LATEST_END_TIME, + TaskReduced.JSON_PROPERTY_ACTIVE_FROM, + TaskReduced.JSON_PROPERTY_ACTIVE_TO, + TaskReduced.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + TaskReduced.JSON_PROPERTY_LOCATION_INHERITED, + TaskReduced.JSON_PROPERTY_LOCATION, + TaskReduced.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + TaskReduced.JSON_PROPERTY_CUSTOM_FIELD1, + TaskReduced.JSON_PROPERTY_CUSTOM_FIELD2, + TaskReduced.JSON_PROPERTY_CUSTOM_FIELD3 +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskReduced { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + @jakarta.annotation.Nonnull + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public static final String JSON_PROPERTY_PARENT_TASK = "parent_task"; + @jakarta.annotation.Nullable + private TaskPartial parentTask; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nullable + private String description; + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + @jakarta.annotation.Nonnull + private Boolean bookable; + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + @jakarta.annotation.Nonnull + private Boolean billable; + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + @jakarta.annotation.Nonnull + private Boolean projectTimeNotesRequired; + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + @jakarta.annotation.Nullable + private JsonNullable lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + @jakarta.annotation.Nullable + private JsonNullable earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + @jakarta.annotation.Nullable + private JsonNullable latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ACTIVE_FROM = "active_from"; + @jakarta.annotation.Nullable + private LocalDate activeFrom; + + public static final String JSON_PROPERTY_ACTIVE_TO = "active_to"; + @jakarta.annotation.Nullable + private LocalDate activeTo; + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + @jakarta.annotation.Nullable + private JsonNullable budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + @jakarta.annotation.Nullable + private JsonNullable locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + @jakarta.annotation.Nullable + private JsonNullable location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + @jakarta.annotation.Nullable + private JsonNullable locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + @jakarta.annotation.Nullable + private String customField1; + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + @jakarta.annotation.Nullable + private String customField2; + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + @jakarta.annotation.Nullable + private String customField3; + + public TaskReduced() { + } + + public TaskReduced id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public TaskReduced name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public TaskReduced breadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public TaskReduced externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + public TaskReduced parentTask(@jakarta.annotation.Nullable TaskPartial parentTask) { + + this.parentTask = parentTask; + return this; + } + + /** + * Get parentTask + * @return parentTask + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public TaskPartial getParentTask() { + return parentTask; + } + + + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setParentTask(@jakarta.annotation.Nullable TaskPartial parentTask) { + this.parentTask = parentTask; + } + + + public TaskReduced description(@jakarta.annotation.Nullable String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@jakarta.annotation.Nullable String description) { + this.description = description; + } + + + public TaskReduced bookable(@jakarta.annotation.Nonnull Boolean bookable) { + + this.bookable = bookable; + return this; + } + + /** + * Get bookable + * @return bookable + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBookable() { + return bookable; + } + + + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBookable(@jakarta.annotation.Nonnull Boolean bookable) { + this.bookable = bookable; + } + + + public TaskReduced billable(@jakarta.annotation.Nonnull Boolean billable) { + + this.billable = billable; + return this; + } + + /** + * Get billable + * @return billable + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getBillable() { + return billable; + } + + + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBillable(@jakarta.annotation.Nonnull Boolean billable) { + this.billable = billable; + } + + + public TaskReduced projectTimeNotesRequired(@jakarta.annotation.Nonnull Boolean projectTimeNotesRequired) { + + this.projectTimeNotesRequired = projectTimeNotesRequired; + return this; + } + + /** + * Get projectTimeNotesRequired + * @return projectTimeNotesRequired + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setProjectTimeNotesRequired(@jakarta.annotation.Nonnull Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + public TaskReduced lockDate(@jakarta.annotation.Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return lockDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public TaskReduced earliestStartTime(@jakarta.annotation.Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * time of day (ISO-8601) + * @return earliestStartTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public TaskReduced latestEndTime(@jakarta.annotation.Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * time of day (ISO-8601) + * @return latestEndTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public TaskReduced activeFrom(@jakarta.annotation.Nullable LocalDate activeFrom) { + + this.activeFrom = activeFrom; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return activeFrom + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ACTIVE_FROM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getActiveFrom() { + return activeFrom; + } + + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_FROM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActiveFrom(@jakarta.annotation.Nullable LocalDate activeFrom) { + this.activeFrom = activeFrom; + } + + + public TaskReduced activeTo(@jakarta.annotation.Nullable LocalDate activeTo) { + + this.activeTo = activeTo; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return activeTo + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ACTIVE_TO, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getActiveTo() { + return activeTo; + } + + + @JsonProperty(value = JSON_PROPERTY_ACTIVE_TO, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setActiveTo(@jakarta.annotation.Nullable LocalDate activeTo) { + this.activeTo = activeTo; + } + + + public TaskReduced budgetPlanningType(@jakarta.annotation.Nullable BudgetPlanningType budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * Get budgetPlanningType + * @return budgetPlanningType + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public TaskReduced locationInherited(@jakarta.annotation.Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * Get locationInherited + * @return locationInherited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public TaskReduced location(@jakarta.annotation.Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public TaskReduced locationRestrictionRadiusMeters(@jakarta.annotation.Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * Get locationRestrictionRadiusMeters + * @return locationRestrictionRadiusMeters + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public TaskReduced customField1(@jakarta.annotation.Nullable String customField1) { + + this.customField1 = customField1; + return this; + } + + /** + * Get customField1 + * @return customField1 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCustomField1() { + return customField1; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField1(@jakarta.annotation.Nullable String customField1) { + this.customField1 = customField1; + } + + + public TaskReduced customField2(@jakarta.annotation.Nullable String customField2) { + + this.customField2 = customField2; + return this; + } + + /** + * Get customField2 + * @return customField2 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCustomField2() { + return customField2; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField2(@jakarta.annotation.Nullable String customField2) { + this.customField2 = customField2; + } + + + public TaskReduced customField3(@jakarta.annotation.Nullable String customField3) { + + this.customField3 = customField3; + return this; + } + + /** + * Get customField3 + * @return customField3 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCustomField3() { + return customField3; + } + + + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCustomField3(@jakarta.annotation.Nullable String customField3) { + this.customField3 = customField3; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskReduced taskReduced = (TaskReduced) o; + return Objects.equals(this.id, taskReduced.id) && + Objects.equals(this.name, taskReduced.name) && + Objects.equals(this.breadcrumbs, taskReduced.breadcrumbs) && + Objects.equals(this.externalId, taskReduced.externalId) && + Objects.equals(this.parentTask, taskReduced.parentTask) && + Objects.equals(this.description, taskReduced.description) && + Objects.equals(this.bookable, taskReduced.bookable) && + Objects.equals(this.billable, taskReduced.billable) && + Objects.equals(this.projectTimeNotesRequired, taskReduced.projectTimeNotesRequired) && + equalsNullable(this.lockDate, taskReduced.lockDate) && + equalsNullable(this.earliestStartTime, taskReduced.earliestStartTime) && + equalsNullable(this.latestEndTime, taskReduced.latestEndTime) && + Objects.equals(this.activeFrom, taskReduced.activeFrom) && + Objects.equals(this.activeTo, taskReduced.activeTo) && + equalsNullable(this.budgetPlanningType, taskReduced.budgetPlanningType) && + equalsNullable(this.locationInherited, taskReduced.locationInherited) && + equalsNullable(this.location, taskReduced.location) && + equalsNullable(this.locationRestrictionRadiusMeters, taskReduced.locationRestrictionRadiusMeters) && + Objects.equals(this.customField1, taskReduced.customField1) && + Objects.equals(this.customField2, taskReduced.customField2) && + Objects.equals(this.customField3, taskReduced.customField3); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId, parentTask, description, bookable, billable, projectTimeNotesRequired, hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), activeFrom, activeTo, hashCodeNullable(budgetPlanningType), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), customField1, customField2, customField3); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskReduced {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" parentTask: ").append(toIndentedString(parentTask)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" activeFrom: ").append(toIndentedString(activeFrom)).append("\n"); + sb.append(" activeTo: ").append(toIndentedString(activeTo)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToLeaderAssignment.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToLeaderAssignment.java new file mode 100644 index 0000000..3f79bf8 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToLeaderAssignment.java @@ -0,0 +1,151 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToLeaderAssignment + */ +@JsonPropertyOrder({ + TaskToLeaderAssignment.JSON_PROPERTY_USER, + TaskToLeaderAssignment.JSON_PROPERTY_AUTOMATICALLY_ASSIGNED +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToLeaderAssignment { + public static final String JSON_PROPERTY_USER = "user"; + @jakarta.annotation.Nonnull + private UserPartial user; + + public static final String JSON_PROPERTY_AUTOMATICALLY_ASSIGNED = "automatically_assigned"; + @jakarta.annotation.Nonnull + private Boolean automaticallyAssigned; + + public TaskToLeaderAssignment() { + } + + public TaskToLeaderAssignment user(@jakarta.annotation.Nonnull UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(@jakarta.annotation.Nonnull UserPartial user) { + this.user = user; + } + + + public TaskToLeaderAssignment automaticallyAssigned(@jakarta.annotation.Nonnull Boolean automaticallyAssigned) { + + this.automaticallyAssigned = automaticallyAssigned; + return this; + } + + /** + * Get automaticallyAssigned + * @return automaticallyAssigned + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getAutomaticallyAssigned() { + return automaticallyAssigned; + } + + + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAutomaticallyAssigned(@jakarta.annotation.Nonnull Boolean automaticallyAssigned) { + this.automaticallyAssigned = automaticallyAssigned; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToLeaderAssignment taskToLeaderAssignment = (TaskToLeaderAssignment) o; + return Objects.equals(this.user, taskToLeaderAssignment.user) && + Objects.equals(this.automaticallyAssigned, taskToLeaderAssignment.automaticallyAssigned); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(user, automaticallyAssigned); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToLeaderAssignment {\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" automaticallyAssigned: ").append(toIndentedString(automaticallyAssigned)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsPage.java new file mode 100644 index 0000000..f8436ee --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TaskToLeaderAssignment; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToLeaderAssignmentsPage + */ +@JsonPropertyOrder({ + TaskToLeaderAssignmentsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TaskToLeaderAssignmentsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToLeaderAssignmentsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public TaskToLeaderAssignmentsPage() { + } + + public TaskToLeaderAssignmentsPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TaskToLeaderAssignmentsPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public TaskToLeaderAssignmentsPage addDataItem(TaskToLeaderAssignment dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToLeaderAssignmentsPage taskToLeaderAssignmentsPage = (TaskToLeaderAssignmentsPage) o; + return Objects.equals(this.nextPageToken, taskToLeaderAssignmentsPage.nextPageToken) && + Objects.equals(this.data, taskToLeaderAssignmentsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToLeaderAssignmentsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsSortColumn.java new file mode 100644 index 0000000..c33d954 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToLeaderAssignmentsSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Task to Leader Assignments. `user_name` orders by the assigned User's last name, then first name. + */ +public enum TaskToLeaderAssignmentsSortColumn { + + USER_NAME("user_name"); + + private String value; + + TaskToLeaderAssignmentsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TaskToLeaderAssignmentsSortColumn fromValue(String value) { + for (TaskToLeaderAssignmentsSortColumn b : TaskToLeaderAssignmentsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToTeamAssignment.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToTeamAssignment.java new file mode 100644 index 0000000..d5002c8 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToTeamAssignment.java @@ -0,0 +1,151 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TeamPartial; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToTeamAssignment + */ +@JsonPropertyOrder({ + TaskToTeamAssignment.JSON_PROPERTY_TEAM, + TaskToTeamAssignment.JSON_PROPERTY_AUTOMATICALLY_ASSIGNED +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToTeamAssignment { + public static final String JSON_PROPERTY_TEAM = "team"; + @jakarta.annotation.Nonnull + private TeamPartial team; + + public static final String JSON_PROPERTY_AUTOMATICALLY_ASSIGNED = "automatically_assigned"; + @jakarta.annotation.Nonnull + private Boolean automaticallyAssigned; + + public TaskToTeamAssignment() { + } + + public TaskToTeamAssignment team(@jakarta.annotation.Nonnull TeamPartial team) { + + this.team = team; + return this; + } + + /** + * Get team + * @return team + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TEAM, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public TeamPartial getTeam() { + return team; + } + + + @JsonProperty(value = JSON_PROPERTY_TEAM, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTeam(@jakarta.annotation.Nonnull TeamPartial team) { + this.team = team; + } + + + public TaskToTeamAssignment automaticallyAssigned(@jakarta.annotation.Nonnull Boolean automaticallyAssigned) { + + this.automaticallyAssigned = automaticallyAssigned; + return this; + } + + /** + * Get automaticallyAssigned + * @return automaticallyAssigned + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getAutomaticallyAssigned() { + return automaticallyAssigned; + } + + + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAutomaticallyAssigned(@jakarta.annotation.Nonnull Boolean automaticallyAssigned) { + this.automaticallyAssigned = automaticallyAssigned; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToTeamAssignment taskToTeamAssignment = (TaskToTeamAssignment) o; + return Objects.equals(this.team, taskToTeamAssignment.team) && + Objects.equals(this.automaticallyAssigned, taskToTeamAssignment.automaticallyAssigned); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(team, automaticallyAssigned); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToTeamAssignment {\n"); + sb.append(" team: ").append(toIndentedString(team)).append("\n"); + sb.append(" automaticallyAssigned: ").append(toIndentedString(automaticallyAssigned)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToTeamAssignmentsPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToTeamAssignmentsPage.java new file mode 100644 index 0000000..b2732d2 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToTeamAssignmentsPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TaskToTeamAssignment; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToTeamAssignmentsPage + */ +@JsonPropertyOrder({ + TaskToTeamAssignmentsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TaskToTeamAssignmentsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToTeamAssignmentsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public TaskToTeamAssignmentsPage() { + } + + public TaskToTeamAssignmentsPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TaskToTeamAssignmentsPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public TaskToTeamAssignmentsPage addDataItem(TaskToTeamAssignment dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToTeamAssignmentsPage taskToTeamAssignmentsPage = (TaskToTeamAssignmentsPage) o; + return Objects.equals(this.nextPageToken, taskToTeamAssignmentsPage.nextPageToken) && + Objects.equals(this.data, taskToTeamAssignmentsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToTeamAssignmentsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToTeamAssignmentsSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToTeamAssignmentsSortColumn.java new file mode 100644 index 0000000..8fa7b9e --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToTeamAssignmentsSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Task to Team Assignments. `team_name` orders by the assigned Team's name. + */ +public enum TaskToTeamAssignmentsSortColumn { + + TEAM_NAME("team_name"); + + private String value; + + TaskToTeamAssignmentsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TaskToTeamAssignmentsSortColumn fromValue(String value) { + for (TaskToTeamAssignmentsSortColumn b : TaskToTeamAssignmentsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignment.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignment.java new file mode 100644 index 0000000..399926a --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignment.java @@ -0,0 +1,220 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.RecordingLockType; +import com.timr.api.models.UserPartial; +import java.math.BigDecimal; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToUserAssignment + */ +@JsonPropertyOrder({ + TaskToUserAssignment.JSON_PROPERTY_USER, + TaskToUserAssignment.JSON_PROPERTY_HOURS_PLANNED, + TaskToUserAssignment.JSON_PROPERTY_RECORDING_LOCK, + TaskToUserAssignment.JSON_PROPERTY_AUTOMATICALLY_ASSIGNED +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToUserAssignment { + public static final String JSON_PROPERTY_USER = "user"; + @jakarta.annotation.Nonnull + private UserPartial user; + + public static final String JSON_PROPERTY_HOURS_PLANNED = "hours_planned"; + @jakarta.annotation.Nullable + private JsonNullable hoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RECORDING_LOCK = "recording_lock"; + @jakarta.annotation.Nonnull + private RecordingLockType recordingLock; + + public static final String JSON_PROPERTY_AUTOMATICALLY_ASSIGNED = "automatically_assigned"; + @jakarta.annotation.Nonnull + private Boolean automaticallyAssigned; + + public TaskToUserAssignment() { + } + + public TaskToUserAssignment user(@jakarta.annotation.Nonnull UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(@jakarta.annotation.Nonnull UserPartial user) { + this.user = user; + } + + + public TaskToUserAssignment hoursPlanned(@jakarta.annotation.Nullable BigDecimal hoursPlanned) { + this.hoursPlanned = JsonNullable.of(hoursPlanned); + + return this; + } + + /** + * Get hoursPlanned + * @return hoursPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getHoursPlanned() { + return hoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_HOURS_PLANNED) + public void setHoursPlanned(JsonNullable hoursPlanned) { + this.hoursPlanned = hoursPlanned; + } + + + + public TaskToUserAssignment recordingLock(@jakarta.annotation.Nonnull RecordingLockType recordingLock) { + + this.recordingLock = recordingLock; + return this; + } + + /** + * Get recordingLock + * @return recordingLock + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_RECORDING_LOCK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public RecordingLockType getRecordingLock() { + return recordingLock; + } + + + @JsonProperty(value = JSON_PROPERTY_RECORDING_LOCK, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRecordingLock(@jakarta.annotation.Nonnull RecordingLockType recordingLock) { + this.recordingLock = recordingLock; + } + + + public TaskToUserAssignment automaticallyAssigned(@jakarta.annotation.Nonnull Boolean automaticallyAssigned) { + + this.automaticallyAssigned = automaticallyAssigned; + return this; + } + + /** + * Get automaticallyAssigned + * @return automaticallyAssigned + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getAutomaticallyAssigned() { + return automaticallyAssigned; + } + + + @JsonProperty(value = JSON_PROPERTY_AUTOMATICALLY_ASSIGNED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setAutomaticallyAssigned(@jakarta.annotation.Nonnull Boolean automaticallyAssigned) { + this.automaticallyAssigned = automaticallyAssigned; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToUserAssignment taskToUserAssignment = (TaskToUserAssignment) o; + return Objects.equals(this.user, taskToUserAssignment.user) && + equalsNullable(this.hoursPlanned, taskToUserAssignment.hoursPlanned) && + Objects.equals(this.recordingLock, taskToUserAssignment.recordingLock) && + Objects.equals(this.automaticallyAssigned, taskToUserAssignment.automaticallyAssigned); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(user, hashCodeNullable(hoursPlanned), recordingLock, automaticallyAssigned); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToUserAssignment {\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" recordingLock: ").append(toIndentedString(recordingLock)).append("\n"); + sb.append(" automaticallyAssigned: ").append(toIndentedString(automaticallyAssigned)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignmentUpsert.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignmentUpsert.java new file mode 100644 index 0000000..48ff5e9 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignmentUpsert.java @@ -0,0 +1,151 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.RecordingLockType; +import java.math.BigDecimal; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToUserAssignmentUpsert + */ +@JsonPropertyOrder({ + TaskToUserAssignmentUpsert.JSON_PROPERTY_HOURS_PLANNED, + TaskToUserAssignmentUpsert.JSON_PROPERTY_RECORDING_LOCK +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToUserAssignmentUpsert { + public static final String JSON_PROPERTY_HOURS_PLANNED = "hours_planned"; + @jakarta.annotation.Nullable + private JsonNullable hoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RECORDING_LOCK = "recording_lock"; + @jakarta.annotation.Nullable + private JsonNullable recordingLock = JsonNullable.undefined(); + + public TaskToUserAssignmentUpsert() { + } + + public TaskToUserAssignmentUpsert hoursPlanned(@jakarta.annotation.Nullable BigDecimal hoursPlanned) { + this.hoursPlanned = JsonNullable.of(hoursPlanned); + + return this; + } + + /** + * Get hoursPlanned + * @return hoursPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getHoursPlanned() { + return hoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_HOURS_PLANNED) + public void setHoursPlanned(JsonNullable hoursPlanned) { + this.hoursPlanned = hoursPlanned; + } + + + + public TaskToUserAssignmentUpsert recordingLock(@jakarta.annotation.Nullable RecordingLockType recordingLock) { + this.recordingLock = JsonNullable.of(recordingLock); + + return this; + } + + /** + * Get recordingLock + * @return recordingLock + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_RECORDING_LOCK, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getRecordingLock() { + return recordingLock; + } + + @JsonProperty(JSON_PROPERTY_RECORDING_LOCK) + public void setRecordingLock(JsonNullable recordingLock) { + this.recordingLock = recordingLock; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToUserAssignmentUpsert taskToUserAssignmentUpsert = (TaskToUserAssignmentUpsert) o; + return equalsNullable(this.hoursPlanned, taskToUserAssignmentUpsert.hoursPlanned) && + equalsNullable(this.recordingLock, taskToUserAssignmentUpsert.recordingLock); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(hoursPlanned), hashCodeNullable(recordingLock)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToUserAssignmentUpsert {\n"); + sb.append(" recordingLock: ").append(toIndentedString(recordingLock)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignmentsPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignmentsPage.java new file mode 100644 index 0000000..b5e1376 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignmentsPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TaskToUserAssignment; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskToUserAssignmentsPage + */ +@JsonPropertyOrder({ + TaskToUserAssignmentsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TaskToUserAssignmentsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskToUserAssignmentsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public TaskToUserAssignmentsPage() { + } + + public TaskToUserAssignmentsPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TaskToUserAssignmentsPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public TaskToUserAssignmentsPage addDataItem(TaskToUserAssignment dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskToUserAssignmentsPage taskToUserAssignmentsPage = (TaskToUserAssignmentsPage) o; + return Objects.equals(this.nextPageToken, taskToUserAssignmentsPage.nextPageToken) && + Objects.equals(this.data, taskToUserAssignmentsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskToUserAssignmentsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignmentsSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignmentsSortColumn.java new file mode 100644 index 0000000..d0711d0 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskToUserAssignmentsSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Task to User Assignments. `user_name` orders by the assigned User's last name, then first name. + */ +public enum TaskToUserAssignmentsSortColumn { + + USER_NAME("user_name"); + + private String value; + + TaskToUserAssignmentsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TaskToUserAssignmentsSortColumn fromValue(String value) { + for (TaskToUserAssignmentsSortColumn b : TaskToUserAssignmentsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskUpdate.java new file mode 100644 index 0000000..af34823 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TaskUpdate.java @@ -0,0 +1,893 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BudgetPlanningTypeRequest; +import com.timr.api.models.TaskLocation; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TaskUpdate + */ +@JsonPropertyOrder({ + TaskUpdate.JSON_PROPERTY_NAME, + TaskUpdate.JSON_PROPERTY_PARENT_TASK_ID, + TaskUpdate.JSON_PROPERTY_EXTERNAL_ID, + TaskUpdate.JSON_PROPERTY_DESCRIPTION, + TaskUpdate.JSON_PROPERTY_DESCRIPTION_EXTERNAL, + TaskUpdate.JSON_PROPERTY_BOOKABLE, + TaskUpdate.JSON_PROPERTY_BILLABLE, + TaskUpdate.JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, + TaskUpdate.JSON_PROPERTY_START_DATE, + TaskUpdate.JSON_PROPERTY_END_DATE, + TaskUpdate.JSON_PROPERTY_LOCK_DATE, + TaskUpdate.JSON_PROPERTY_EARLIEST_START_TIME, + TaskUpdate.JSON_PROPERTY_LATEST_END_TIME, + TaskUpdate.JSON_PROPERTY_BUDGET_PLANNING_TYPE, + TaskUpdate.JSON_PROPERTY_BUDGET_HOURS_PLANNED, + TaskUpdate.JSON_PROPERTY_BUDGET_HOURLY_RATE, + TaskUpdate.JSON_PROPERTY_BUDGET_PLANNED, + TaskUpdate.JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, + TaskUpdate.JSON_PROPERTY_LOCATION_INHERITED, + TaskUpdate.JSON_PROPERTY_LOCATION, + TaskUpdate.JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, + TaskUpdate.JSON_PROPERTY_CUSTOM_FIELD1, + TaskUpdate.JSON_PROPERTY_CUSTOM_FIELD2, + TaskUpdate.JSON_PROPERTY_CUSTOM_FIELD3, + TaskUpdate.JSON_PROPERTY_METADATA, + TaskUpdate.JSON_PROPERTY_BUDGET_UPDATE_PROJECT_TIMES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TaskUpdate { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private JsonNullable name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PARENT_TASK_ID = "parent_task_id"; + @jakarta.annotation.Nullable + private JsonNullable parentTaskId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private JsonNullable externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nullable + private JsonNullable description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION_EXTERNAL = "description_external"; + @jakarta.annotation.Nullable + private JsonNullable descriptionExternal = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BOOKABLE = "bookable"; + @jakarta.annotation.Nullable + private JsonNullable bookable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BILLABLE = "billable"; + @jakarta.annotation.Nullable + private JsonNullable billable = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED = "project_time_notes_required"; + @jakarta.annotation.Nullable + private JsonNullable projectTimeNotesRequired = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_DATE = "start_date"; + @jakarta.annotation.Nullable + private JsonNullable startDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_DATE = "end_date"; + @jakarta.annotation.Nullable + private JsonNullable endDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCK_DATE = "lock_date"; + @jakarta.annotation.Nullable + private JsonNullable lockDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EARLIEST_START_TIME = "earliest_start_time"; + @jakarta.annotation.Nullable + private JsonNullable earliestStartTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LATEST_END_TIME = "latest_end_time"; + @jakarta.annotation.Nullable + private JsonNullable latestEndTime = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNING_TYPE = "budget_planning_type"; + @jakarta.annotation.Nullable + private JsonNullable budgetPlanningType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURS_PLANNED = "budget_hours_planned"; + @jakarta.annotation.Nullable + private JsonNullable budgetHoursPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_HOURLY_RATE = "budget_hourly_rate"; + @jakarta.annotation.Nullable + private JsonNullable budgetHourlyRate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_PLANNED = "budget_planned"; + @jakarta.annotation.Nullable + private JsonNullable budgetPlanned = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES = "budget_include_non_billable_project_times"; + @jakarta.annotation.Nullable + private JsonNullable budgetIncludeNonBillableProjectTimes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_INHERITED = "location_inherited"; + @jakarta.annotation.Nullable + private JsonNullable locationInherited = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION = "location"; + @jakarta.annotation.Nullable + private JsonNullable location = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS = "location_restriction_radius_meters"; + @jakarta.annotation.Nullable + private JsonNullable locationRestrictionRadiusMeters = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD1 = "custom_field_1"; + @jakarta.annotation.Nullable + private JsonNullable customField1 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD2 = "custom_field_2"; + @jakarta.annotation.Nullable + private JsonNullable customField2 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CUSTOM_FIELD3 = "custom_field_3"; + @jakarta.annotation.Nullable + private JsonNullable customField3 = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_BUDGET_UPDATE_PROJECT_TIMES = "budget_update_project_times"; + @jakarta.annotation.Nullable + private JsonNullable budgetUpdateProjectTimes = JsonNullable.undefined(); + + public TaskUpdate() { + } + + public TaskUpdate name(@jakarta.annotation.Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public TaskUpdate parentTaskId(@jakarta.annotation.Nullable String parentTaskId) { + this.parentTaskId = JsonNullable.of(parentTaskId); + + return this; + } + + /** + * returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @return parentTaskId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PARENT_TASK_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getParentTaskId() { + return parentTaskId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TASK_ID) + public void setParentTaskId(JsonNullable parentTaskId) { + this.parentTaskId = parentTaskId; + } + + + + public TaskUpdate externalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public TaskUpdate description(@jakarta.annotation.Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TaskUpdate descriptionExternal(@jakarta.annotation.Nullable String descriptionExternal) { + this.descriptionExternal = JsonNullable.of(descriptionExternal); + + return this; + } + + /** + * Get descriptionExternal + * @return descriptionExternal + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION_EXTERNAL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDescriptionExternal() { + return descriptionExternal; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION_EXTERNAL) + public void setDescriptionExternal(JsonNullable descriptionExternal) { + this.descriptionExternal = descriptionExternal; + } + + + + public TaskUpdate bookable(@jakarta.annotation.Nullable Boolean bookable) { + this.bookable = JsonNullable.of(bookable); + + return this; + } + + /** + * when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @return bookable + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BOOKABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBookable() { + return bookable; + } + + @JsonProperty(JSON_PROPERTY_BOOKABLE) + public void setBookable(JsonNullable bookable) { + this.bookable = bookable; + } + + + + public TaskUpdate billable(@jakarta.annotation.Nullable Boolean billable) { + this.billable = JsonNullable.of(billable); + + return this; + } + + /** + * Get billable + * @return billable + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BILLABLE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBillable() { + return billable; + } + + @JsonProperty(JSON_PROPERTY_BILLABLE) + public void setBillable(JsonNullable billable) { + this.billable = billable; + } + + + + public TaskUpdate projectTimeNotesRequired(@jakarta.annotation.Nullable Boolean projectTimeNotesRequired) { + this.projectTimeNotesRequired = JsonNullable.of(projectTimeNotesRequired); + + return this; + } + + /** + * depending on this property project times booked on this task have to include notes or not + * @return projectTimeNotesRequired + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getProjectTimeNotesRequired() { + return projectTimeNotesRequired; + } + + @JsonProperty(JSON_PROPERTY_PROJECT_TIME_NOTES_REQUIRED) + public void setProjectTimeNotesRequired(JsonNullable projectTimeNotesRequired) { + this.projectTimeNotesRequired = projectTimeNotesRequired; + } + + + + public TaskUpdate startDate(@jakarta.annotation.Nullable LocalDate startDate) { + this.startDate = JsonNullable.of(startDate); + + return this; + } + + /** + * the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return startDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartDate() { + return startDate; + } + + @JsonProperty(JSON_PROPERTY_START_DATE) + public void setStartDate(JsonNullable startDate) { + this.startDate = startDate; + } + + + + public TaskUpdate endDate(@jakarta.annotation.Nullable LocalDate endDate) { + this.endDate = JsonNullable.of(endDate); + + return this; + } + + /** + * the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @return endDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndDate() { + return endDate; + } + + @JsonProperty(JSON_PROPERTY_END_DATE) + public void setEndDate(JsonNullable endDate) { + this.endDate = endDate; + } + + + + public TaskUpdate lockDate(@jakarta.annotation.Nullable LocalDate lockDate) { + this.lockDate = JsonNullable.of(lockDate); + + return this; + } + + /** + * with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + * @return lockDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCK_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLockDate() { + return lockDate; + } + + @JsonProperty(JSON_PROPERTY_LOCK_DATE) + public void setLockDate(JsonNullable lockDate) { + this.lockDate = lockDate; + } + + + + public TaskUpdate earliestStartTime(@jakarta.annotation.Nullable String earliestStartTime) { + this.earliestStartTime = JsonNullable.of(earliestStartTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked before this time + * @return earliestStartTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EARLIEST_START_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEarliestStartTime() { + return earliestStartTime; + } + + @JsonProperty(JSON_PROPERTY_EARLIEST_START_TIME) + public void setEarliestStartTime(JsonNullable earliestStartTime) { + this.earliestStartTime = earliestStartTime; + } + + + + public TaskUpdate latestEndTime(@jakarta.annotation.Nullable String latestEndTime) { + this.latestEndTime = JsonNullable.of(latestEndTime); + + return this; + } + + /** + * set this property to limit the task so that it cannot be booked after this time + * @return latestEndTime + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LATEST_END_TIME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLatestEndTime() { + return latestEndTime; + } + + @JsonProperty(JSON_PROPERTY_LATEST_END_TIME) + public void setLatestEndTime(JsonNullable latestEndTime) { + this.latestEndTime = latestEndTime; + } + + + + public TaskUpdate budgetPlanningType(@jakarta.annotation.Nullable BudgetPlanningTypeRequest budgetPlanningType) { + this.budgetPlanningType = JsonNullable.of(budgetPlanningType); + + return this; + } + + /** + * when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * @return budgetPlanningType + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNING_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetPlanningType() { + return budgetPlanningType; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNING_TYPE) + public void setBudgetPlanningType(JsonNullable budgetPlanningType) { + this.budgetPlanningType = budgetPlanningType; + } + + + + public TaskUpdate budgetHoursPlanned(@jakarta.annotation.Nullable BigDecimal budgetHoursPlanned) { + this.budgetHoursPlanned = JsonNullable.of(budgetHoursPlanned); + + return this; + } + + /** + * how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetHoursPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURS_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetHoursPlanned() { + return budgetHoursPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURS_PLANNED) + public void setBudgetHoursPlanned(JsonNullable budgetHoursPlanned) { + this.budgetHoursPlanned = budgetHoursPlanned; + } + + + + public TaskUpdate budgetHourlyRate(@jakarta.annotation.Nullable BigDecimal budgetHourlyRate) { + this.budgetHourlyRate = JsonNullable.of(budgetHourlyRate); + + return this; + } + + /** + * depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * @return budgetHourlyRate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_HOURLY_RATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetHourlyRate() { + return budgetHourlyRate; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_HOURLY_RATE) + public void setBudgetHourlyRate(JsonNullable budgetHourlyRate) { + this.budgetHourlyRate = budgetHourlyRate; + } + + + + public TaskUpdate budgetPlanned(@jakarta.annotation.Nullable BigDecimal budgetPlanned) { + this.budgetPlanned = JsonNullable.of(budgetPlanned); + + return this; + } + + /** + * the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @return budgetPlanned + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_PLANNED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetPlanned() { + return budgetPlanned; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_PLANNED) + public void setBudgetPlanned(JsonNullable budgetPlanned) { + this.budgetPlanned = budgetPlanned; + } + + + + public TaskUpdate budgetIncludeNonBillableProjectTimes(@jakarta.annotation.Nullable Boolean budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = JsonNullable.of(budgetIncludeNonBillableProjectTimes); + + return this; + } + + /** + * set this property to true, if you want to include not billable hours for all project times booked on this task + * @return budgetIncludeNonBillableProjectTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetIncludeNonBillableProjectTimes() { + return budgetIncludeNonBillableProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_INCLUDE_NON_BILLABLE_PROJECT_TIMES) + public void setBudgetIncludeNonBillableProjectTimes(JsonNullable budgetIncludeNonBillableProjectTimes) { + this.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes; + } + + + + public TaskUpdate locationInherited(@jakarta.annotation.Nullable Boolean locationInherited) { + this.locationInherited = JsonNullable.of(locationInherited); + + return this; + } + + /** + * set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @return locationInherited + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_INHERITED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationInherited() { + return locationInherited; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_INHERITED) + public void setLocationInherited(JsonNullable locationInherited) { + this.locationInherited = locationInherited; + } + + + + public TaskUpdate location(@jakarta.annotation.Nullable TaskLocation location) { + this.location = JsonNullable.of(location); + + return this; + } + + /** + * Get location + * @return location + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocation() { + return location; + } + + @JsonProperty(JSON_PROPERTY_LOCATION) + public void setLocation(JsonNullable location) { + this.location = location; + } + + + + public TaskUpdate locationRestrictionRadiusMeters(@jakarta.annotation.Nullable Integer locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = JsonNullable.of(locationRestrictionRadiusMeters); + + return this; + } + + /** + * set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @return locationRestrictionRadiusMeters + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLocationRestrictionRadiusMeters() { + return locationRestrictionRadiusMeters; + } + + @JsonProperty(JSON_PROPERTY_LOCATION_RESTRICTION_RADIUS_METERS) + public void setLocationRestrictionRadiusMeters(JsonNullable locationRestrictionRadiusMeters) { + this.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters; + } + + + + public TaskUpdate customField1(@jakarta.annotation.Nullable String customField1) { + this.customField1 = JsonNullable.of(customField1); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField1 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD1, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getCustomField1() { + return customField1; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD1) + public void setCustomField1(JsonNullable customField1) { + this.customField1 = customField1; + } + + + + public TaskUpdate customField2(@jakarta.annotation.Nullable String customField2) { + this.customField2 = JsonNullable.of(customField2); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField2 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD2, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getCustomField2() { + return customField2; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD2) + public void setCustomField2(JsonNullable customField2) { + this.customField2 = customField2; + } + + + + public TaskUpdate customField3(@jakarta.annotation.Nullable String customField3) { + this.customField3 = JsonNullable.of(customField3); + + return this; + } + + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @return customField3 + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CUSTOM_FIELD3, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getCustomField3() { + return customField3; + } + + @JsonProperty(JSON_PROPERTY_CUSTOM_FIELD3) + public void setCustomField3(JsonNullable customField3) { + this.customField3 = customField3; + } + + + + public TaskUpdate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public TaskUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public TaskUpdate budgetUpdateProjectTimes(@jakarta.annotation.Nullable Boolean budgetUpdateProjectTimes) { + this.budgetUpdateProjectTimes = JsonNullable.of(budgetUpdateProjectTimes); + + return this; + } + + /** + * this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. + * @return budgetUpdateProjectTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BUDGET_UPDATE_PROJECT_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBudgetUpdateProjectTimes() { + return budgetUpdateProjectTimes; + } + + @JsonProperty(JSON_PROPERTY_BUDGET_UPDATE_PROJECT_TIMES) + public void setBudgetUpdateProjectTimes(JsonNullable budgetUpdateProjectTimes) { + this.budgetUpdateProjectTimes = budgetUpdateProjectTimes; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskUpdate taskUpdate = (TaskUpdate) o; + return equalsNullable(this.name, taskUpdate.name) && + equalsNullable(this.parentTaskId, taskUpdate.parentTaskId) && + equalsNullable(this.externalId, taskUpdate.externalId) && + equalsNullable(this.description, taskUpdate.description) && + equalsNullable(this.descriptionExternal, taskUpdate.descriptionExternal) && + equalsNullable(this.bookable, taskUpdate.bookable) && + equalsNullable(this.billable, taskUpdate.billable) && + equalsNullable(this.projectTimeNotesRequired, taskUpdate.projectTimeNotesRequired) && + equalsNullable(this.startDate, taskUpdate.startDate) && + equalsNullable(this.endDate, taskUpdate.endDate) && + equalsNullable(this.lockDate, taskUpdate.lockDate) && + equalsNullable(this.earliestStartTime, taskUpdate.earliestStartTime) && + equalsNullable(this.latestEndTime, taskUpdate.latestEndTime) && + equalsNullable(this.budgetPlanningType, taskUpdate.budgetPlanningType) && + equalsNullable(this.budgetHoursPlanned, taskUpdate.budgetHoursPlanned) && + equalsNullable(this.budgetHourlyRate, taskUpdate.budgetHourlyRate) && + equalsNullable(this.budgetPlanned, taskUpdate.budgetPlanned) && + equalsNullable(this.budgetIncludeNonBillableProjectTimes, taskUpdate.budgetIncludeNonBillableProjectTimes) && + equalsNullable(this.locationInherited, taskUpdate.locationInherited) && + equalsNullable(this.location, taskUpdate.location) && + equalsNullable(this.locationRestrictionRadiusMeters, taskUpdate.locationRestrictionRadiusMeters) && + equalsNullable(this.customField1, taskUpdate.customField1) && + equalsNullable(this.customField2, taskUpdate.customField2) && + equalsNullable(this.customField3, taskUpdate.customField3) && + equalsNullable(this.metadata, taskUpdate.metadata) && + equalsNullable(this.budgetUpdateProjectTimes, taskUpdate.budgetUpdateProjectTimes); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(name), hashCodeNullable(parentTaskId), hashCodeNullable(externalId), hashCodeNullable(description), hashCodeNullable(descriptionExternal), hashCodeNullable(bookable), hashCodeNullable(billable), hashCodeNullable(projectTimeNotesRequired), hashCodeNullable(startDate), hashCodeNullable(endDate), hashCodeNullable(lockDate), hashCodeNullable(earliestStartTime), hashCodeNullable(latestEndTime), hashCodeNullable(budgetPlanningType), hashCodeNullable(budgetHoursPlanned), hashCodeNullable(budgetHourlyRate), hashCodeNullable(budgetPlanned), hashCodeNullable(budgetIncludeNonBillableProjectTimes), hashCodeNullable(locationInherited), hashCodeNullable(location), hashCodeNullable(locationRestrictionRadiusMeters), hashCodeNullable(customField1), hashCodeNullable(customField2), hashCodeNullable(customField3), hashCodeNullable(metadata), hashCodeNullable(budgetUpdateProjectTimes)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TaskUpdate {\n"); + sb.append(" parentTaskId: ").append(toIndentedString(parentTaskId)).append("\n"); + sb.append(" bookable: ").append(toIndentedString(bookable)).append("\n"); + sb.append(" billable: ").append(toIndentedString(billable)).append("\n"); + sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n"); + sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n"); + sb.append(" lockDate: ").append(toIndentedString(lockDate)).append("\n"); + sb.append(" budgetPlanningType: ").append(toIndentedString(budgetPlanningType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TasksPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TasksPage.java new file mode 100644 index 0000000..07d2656 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TasksPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.Task; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TasksPage + */ +@JsonPropertyOrder({ + TasksPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TasksPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TasksPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public TasksPage() { + } + + public TasksPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TasksPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public TasksPage addDataItem(Task dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TasksPage tasksPage = (TasksPage) o; + return Objects.equals(this.nextPageToken, tasksPage.nextPageToken) && + Objects.equals(this.data, tasksPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TasksPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TasksReducedPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TasksReducedPage.java new file mode 100644 index 0000000..5203600 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TasksReducedPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TaskReduced; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TasksReducedPage + */ +@JsonPropertyOrder({ + TasksReducedPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TasksReducedPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TasksReducedPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public TasksReducedPage() { + } + + public TasksReducedPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TasksReducedPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public TasksReducedPage addDataItem(TaskReduced dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TasksReducedPage tasksReducedPage = (TasksReducedPage) o; + return Objects.equals(this.nextPageToken, tasksReducedPage.nextPageToken) && + Objects.equals(this.data, tasksReducedPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TasksReducedPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TasksSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TasksSortColumn.java new file mode 100644 index 0000000..d494523 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TasksSortColumn.java @@ -0,0 +1,60 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Tasks. `breadcrumbs` orders by the Task's full path, `name` by its own name only. + */ +public enum TasksSortColumn { + + BREADCRUMBS("breadcrumbs"), + + NAME("name"); + + private String value; + + TasksSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TasksSortColumn fromValue(String value) { + for (TasksSortColumn b : TasksSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Team.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Team.java new file mode 100644 index 0000000..14706d5 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Team.java @@ -0,0 +1,279 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TeamPartial; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A team, placed in the hierarchy by `parent_team`, with the full path from the root in `breadcrumbs`. + */ +@JsonPropertyOrder({ + Team.JSON_PROPERTY_ID, + Team.JSON_PROPERTY_NAME, + Team.JSON_PROPERTY_BREADCRUMBS, + Team.JSON_PROPERTY_EXTERNAL_ID, + Team.JSON_PROPERTY_DESCRIPTION, + Team.JSON_PROPERTY_PARENT_TEAM +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Team { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + @jakarta.annotation.Nonnull + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nullable + private String description; + + public static final String JSON_PROPERTY_PARENT_TEAM = "parent_team"; + @jakarta.annotation.Nullable + private TeamPartial parentTeam; + + public Team() { + } + + public Team id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public Team name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public Team breadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public Team externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + public Team description(@jakarta.annotation.Nullable String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@jakarta.annotation.Nullable String description) { + this.description = description; + } + + + public Team parentTeam(@jakarta.annotation.Nullable TeamPartial parentTeam) { + + this.parentTeam = parentTeam; + return this; + } + + /** + * Get parentTeam + * @return parentTeam + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PARENT_TEAM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public TeamPartial getParentTeam() { + return parentTeam; + } + + + @JsonProperty(value = JSON_PROPERTY_PARENT_TEAM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setParentTeam(@jakarta.annotation.Nullable TeamPartial parentTeam) { + this.parentTeam = parentTeam; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Team team = (Team) o; + return Objects.equals(this.id, team.id) && + Objects.equals(this.name, team.name) && + Objects.equals(this.breadcrumbs, team.breadcrumbs) && + Objects.equals(this.externalId, team.externalId) && + Objects.equals(this.description, team.description) && + Objects.equals(this.parentTeam, team.parentTeam); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId, description, parentTeam); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Team {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" parentTeam: ").append(toIndentedString(parentTeam)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamCreate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamCreate.java new file mode 100644 index 0000000..9e0971b --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamCreate.java @@ -0,0 +1,211 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamCreate + */ +@JsonPropertyOrder({ + TeamCreate.JSON_PROPERTY_NAME, + TeamCreate.JSON_PROPERTY_DESCRIPTION, + TeamCreate.JSON_PROPERTY_PARENT_TEAM_ID, + TeamCreate.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamCreate { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nullable + private JsonNullable description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PARENT_TEAM_ID = "parent_team_id"; + @jakarta.annotation.Nullable + private JsonNullable parentTeamId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private JsonNullable externalId = JsonNullable.undefined(); + + public TeamCreate() { + } + + public TeamCreate name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public TeamCreate description(@jakarta.annotation.Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TeamCreate parentTeamId(@jakarta.annotation.Nullable String parentTeamId) { + this.parentTeamId = JsonNullable.of(parentTeamId); + + return this; + } + + /** + * Get parentTeamId + * @return parentTeamId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PARENT_TEAM_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getParentTeamId() { + return parentTeamId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TEAM_ID) + public void setParentTeamId(JsonNullable parentTeamId) { + this.parentTeamId = parentTeamId; + } + + + + public TeamCreate externalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamCreate teamCreate = (TeamCreate) o; + return Objects.equals(this.name, teamCreate.name) && + equalsNullable(this.description, teamCreate.description) && + equalsNullable(this.parentTeamId, teamCreate.parentTeamId) && + equalsNullable(this.externalId, teamCreate.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(name, hashCodeNullable(description), hashCodeNullable(parentTeamId), hashCodeNullable(externalId)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamCreate {\n"); + sb.append(" parentTeamId: ").append(toIndentedString(parentTeamId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamPartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamPartial.java new file mode 100644 index 0000000..cc63068 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamPartial.java @@ -0,0 +1,213 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamPartial + */ +@JsonPropertyOrder({ + TeamPartial.JSON_PROPERTY_ID, + TeamPartial.JSON_PROPERTY_NAME, + TeamPartial.JSON_PROPERTY_BREADCRUMBS, + TeamPartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamPartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_BREADCRUMBS = "breadcrumbs"; + @jakarta.annotation.Nonnull + private String breadcrumbs; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public TeamPartial() { + } + + public TeamPartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public TeamPartial name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public TeamPartial breadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + + this.breadcrumbs = breadcrumbs; + return this; + } + + /** + * Full path of the entry within its hierarchy, including its own name. + * @return breadcrumbs + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getBreadcrumbs() { + return breadcrumbs; + } + + + @JsonProperty(value = JSON_PROPERTY_BREADCRUMBS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreadcrumbs(@jakarta.annotation.Nonnull String breadcrumbs) { + this.breadcrumbs = breadcrumbs; + } + + + public TeamPartial externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamPartial teamPartial = (TeamPartial) o; + return Objects.equals(this.id, teamPartial.id) && + Objects.equals(this.name, teamPartial.name) && + Objects.equals(this.breadcrumbs, teamPartial.breadcrumbs) && + Objects.equals(this.externalId, teamPartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, breadcrumbs, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamUpdate.java new file mode 100644 index 0000000..0411ce4 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamUpdate.java @@ -0,0 +1,209 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamUpdate + */ +@JsonPropertyOrder({ + TeamUpdate.JSON_PROPERTY_NAME, + TeamUpdate.JSON_PROPERTY_DESCRIPTION, + TeamUpdate.JSON_PROPERTY_PARENT_TEAM_ID, + TeamUpdate.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamUpdate { + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private JsonNullable name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nullable + private JsonNullable description = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_PARENT_TEAM_ID = "parent_team_id"; + @jakarta.annotation.Nullable + private JsonNullable parentTeamId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private JsonNullable externalId = JsonNullable.undefined(); + + public TeamUpdate() { + } + + public TeamUpdate name(@jakarta.annotation.Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public TeamUpdate description(@jakarta.annotation.Nullable String description) { + this.description = JsonNullable.of(description); + + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDescription() { + return description; + } + + @JsonProperty(JSON_PROPERTY_DESCRIPTION) + public void setDescription(JsonNullable description) { + this.description = description; + } + + + + public TeamUpdate parentTeamId(@jakarta.annotation.Nullable String parentTeamId) { + this.parentTeamId = JsonNullable.of(parentTeamId); + + return this; + } + + /** + * Get parentTeamId + * @return parentTeamId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_PARENT_TEAM_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getParentTeamId() { + return parentTeamId; + } + + @JsonProperty(JSON_PROPERTY_PARENT_TEAM_ID) + public void setParentTeamId(JsonNullable parentTeamId) { + this.parentTeamId = parentTeamId; + } + + + + public TeamUpdate externalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamUpdate teamUpdate = (TeamUpdate) o; + return equalsNullable(this.name, teamUpdate.name) && + equalsNullable(this.description, teamUpdate.description) && + equalsNullable(this.parentTeamId, teamUpdate.parentTeamId) && + equalsNullable(this.externalId, teamUpdate.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(name), hashCodeNullable(description), hashCodeNullable(parentTeamId), hashCodeNullable(externalId)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamUpdate {\n"); + sb.append(" parentTeamId: ").append(toIndentedString(parentTeamId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamsPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamsPage.java new file mode 100644 index 0000000..9a837ed --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamsPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.Team; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamsPage + */ +@JsonPropertyOrder({ + TeamsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TeamsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public TeamsPage() { + } + + public TeamsPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TeamsPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public TeamsPage addDataItem(Team dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamsPage teamsPage = (TeamsPage) o; + return Objects.equals(this.nextPageToken, teamsPage.nextPageToken) && + Objects.equals(this.data, teamsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamsPartialPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamsPartialPage.java new file mode 100644 index 0000000..442edb8 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamsPartialPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.TeamPartial; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TeamsPartialPage + */ +@JsonPropertyOrder({ + TeamsPartialPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + TeamsPartialPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TeamsPartialPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public TeamsPartialPage() { + } + + public TeamsPartialPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public TeamsPartialPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public TeamsPartialPage addDataItem(TeamPartial dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TeamsPartialPage teamsPartialPage = (TeamsPartialPage) o; + return Objects.equals(this.nextPageToken, teamsPartialPage.nextPageToken) && + Objects.equals(this.data, teamsPartialPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TeamsPartialPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamsSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamsSortColumn.java new file mode 100644 index 0000000..95c7f7d --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TeamsSortColumn.java @@ -0,0 +1,60 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Teams. `breadcrumbs` orders by the Team's full path, `name` by its own name only. + */ +public enum TeamsSortColumn { + + BREADCRUMBS("breadcrumbs"), + + NAME("name"); + + private String value; + + TeamsSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static TeamsSortColumn fromValue(String value) { + for (TeamsSortColumn b : TeamsSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/TimeAccount.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TimeAccount.java new file mode 100644 index 0000000..b429219 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/TimeAccount.java @@ -0,0 +1,343 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.FlexTimeIndicator; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * TimeAccount + */ +@JsonPropertyOrder({ + TimeAccount.JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, + TimeAccount.JSON_PROPERTY_DURATION_ACTUAL_MINUTES, + TimeAccount.JSON_PROPERTY_DURATION_TARGET_MINUTES, + TimeAccount.JSON_PROPERTY_BALANCE_CURRENT_PERIOD_MINUTES, + TimeAccount.JSON_PROPERTY_BALANCE_TOTAL_MINUTES, + TimeAccount.JSON_PROPERTY_WORK_FROM_HOME_DAYS_FULL, + TimeAccount.JSON_PROPERTY_WORK_FROM_HOME_DAYS_PARTIAL, + TimeAccount.JSON_PROPERTY_FLEX_TIME_INDICATOR +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class TimeAccount { + public static final String JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES = "balance_last_period_minutes"; + @jakarta.annotation.Nullable + private Integer balanceLastPeriodMinutes; + + public static final String JSON_PROPERTY_DURATION_ACTUAL_MINUTES = "duration_actual_minutes"; + @jakarta.annotation.Nullable + private Integer durationActualMinutes; + + public static final String JSON_PROPERTY_DURATION_TARGET_MINUTES = "duration_target_minutes"; + @jakarta.annotation.Nullable + private Integer durationTargetMinutes; + + public static final String JSON_PROPERTY_BALANCE_CURRENT_PERIOD_MINUTES = "balance_current_period_minutes"; + @jakarta.annotation.Nullable + private Integer balanceCurrentPeriodMinutes; + + public static final String JSON_PROPERTY_BALANCE_TOTAL_MINUTES = "balance_total_minutes"; + @jakarta.annotation.Nullable + private Integer balanceTotalMinutes; + + public static final String JSON_PROPERTY_WORK_FROM_HOME_DAYS_FULL = "work_from_home_days_full"; + @jakarta.annotation.Nullable + private Integer workFromHomeDaysFull; + + public static final String JSON_PROPERTY_WORK_FROM_HOME_DAYS_PARTIAL = "work_from_home_days_partial"; + @jakarta.annotation.Nullable + private Integer workFromHomeDaysPartial; + + public static final String JSON_PROPERTY_FLEX_TIME_INDICATOR = "flex_time_indicator"; + @jakarta.annotation.Nullable + private JsonNullable flexTimeIndicator = JsonNullable.undefined(); + + public TimeAccount() { + } + + public TimeAccount balanceLastPeriodMinutes(@jakarta.annotation.Nullable Integer balanceLastPeriodMinutes) { + + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + return this; + } + + /** + * Get balanceLastPeriodMinutes + * @return balanceLastPeriodMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getBalanceLastPeriodMinutes() { + return balanceLastPeriodMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceLastPeriodMinutes(@jakarta.annotation.Nullable Integer balanceLastPeriodMinutes) { + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + } + + + public TimeAccount durationActualMinutes(@jakarta.annotation.Nullable Integer durationActualMinutes) { + + this.durationActualMinutes = durationActualMinutes; + return this; + } + + /** + * sum of durations in current period + * @return durationActualMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DURATION_ACTUAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getDurationActualMinutes() { + return durationActualMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION_ACTUAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDurationActualMinutes(@jakarta.annotation.Nullable Integer durationActualMinutes) { + this.durationActualMinutes = durationActualMinutes; + } + + + public TimeAccount durationTargetMinutes(@jakarta.annotation.Nullable Integer durationTargetMinutes) { + + this.durationTargetMinutes = durationTargetMinutes; + return this; + } + + /** + * target duration in current period + * @return durationTargetMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DURATION_TARGET_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getDurationTargetMinutes() { + return durationTargetMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION_TARGET_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDurationTargetMinutes(@jakarta.annotation.Nullable Integer durationTargetMinutes) { + this.durationTargetMinutes = durationTargetMinutes; + } + + + public TimeAccount balanceCurrentPeriodMinutes(@jakarta.annotation.Nullable Integer balanceCurrentPeriodMinutes) { + + this.balanceCurrentPeriodMinutes = balanceCurrentPeriodMinutes; + return this; + } + + /** + * difference between target duration and actual duration + * @return balanceCurrentPeriodMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BALANCE_CURRENT_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getBalanceCurrentPeriodMinutes() { + return balanceCurrentPeriodMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_CURRENT_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceCurrentPeriodMinutes(@jakarta.annotation.Nullable Integer balanceCurrentPeriodMinutes) { + this.balanceCurrentPeriodMinutes = balanceCurrentPeriodMinutes; + } + + + public TimeAccount balanceTotalMinutes(@jakarta.annotation.Nullable Integer balanceTotalMinutes) { + + this.balanceTotalMinutes = balanceTotalMinutes; + return this; + } + + /** + * total duration until balancing date + * @return balanceTotalMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getBalanceTotalMinutes() { + return balanceTotalMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBalanceTotalMinutes(@jakarta.annotation.Nullable Integer balanceTotalMinutes) { + this.balanceTotalMinutes = balanceTotalMinutes; + } + + + public TimeAccount workFromHomeDaysFull(@jakarta.annotation.Nullable Integer workFromHomeDaysFull) { + + this.workFromHomeDaysFull = workFromHomeDaysFull; + return this; + } + + /** + * complete days worked from home in current period + * @return workFromHomeDaysFull + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_WORK_FROM_HOME_DAYS_FULL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getWorkFromHomeDaysFull() { + return workFromHomeDaysFull; + } + + + @JsonProperty(value = JSON_PROPERTY_WORK_FROM_HOME_DAYS_FULL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkFromHomeDaysFull(@jakarta.annotation.Nullable Integer workFromHomeDaysFull) { + this.workFromHomeDaysFull = workFromHomeDaysFull; + } + + + public TimeAccount workFromHomeDaysPartial(@jakarta.annotation.Nullable Integer workFromHomeDaysPartial) { + + this.workFromHomeDaysPartial = workFromHomeDaysPartial; + return this; + } + + /** + * partial days worked from home in current period + * @return workFromHomeDaysPartial + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_WORK_FROM_HOME_DAYS_PARTIAL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getWorkFromHomeDaysPartial() { + return workFromHomeDaysPartial; + } + + + @JsonProperty(value = JSON_PROPERTY_WORK_FROM_HOME_DAYS_PARTIAL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkFromHomeDaysPartial(@jakarta.annotation.Nullable Integer workFromHomeDaysPartial) { + this.workFromHomeDaysPartial = workFromHomeDaysPartial; + } + + + public TimeAccount flexTimeIndicator(@jakarta.annotation.Nullable FlexTimeIndicator flexTimeIndicator) { + this.flexTimeIndicator = JsonNullable.of(flexTimeIndicator); + + return this; + } + + /** + * Get flexTimeIndicator + * @return flexTimeIndicator + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FLEX_TIME_INDICATOR, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getFlexTimeIndicator() { + return flexTimeIndicator; + } + + @JsonProperty(JSON_PROPERTY_FLEX_TIME_INDICATOR) + public void setFlexTimeIndicator(JsonNullable flexTimeIndicator) { + this.flexTimeIndicator = flexTimeIndicator; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TimeAccount timeAccount = (TimeAccount) o; + return Objects.equals(this.balanceLastPeriodMinutes, timeAccount.balanceLastPeriodMinutes) && + Objects.equals(this.durationActualMinutes, timeAccount.durationActualMinutes) && + Objects.equals(this.durationTargetMinutes, timeAccount.durationTargetMinutes) && + Objects.equals(this.balanceCurrentPeriodMinutes, timeAccount.balanceCurrentPeriodMinutes) && + Objects.equals(this.balanceTotalMinutes, timeAccount.balanceTotalMinutes) && + Objects.equals(this.workFromHomeDaysFull, timeAccount.workFromHomeDaysFull) && + Objects.equals(this.workFromHomeDaysPartial, timeAccount.workFromHomeDaysPartial) && + equalsNullable(this.flexTimeIndicator, timeAccount.flexTimeIndicator); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(balanceLastPeriodMinutes, durationActualMinutes, durationTargetMinutes, balanceCurrentPeriodMinutes, balanceTotalMinutes, workFromHomeDaysFull, workFromHomeDaysPartial, hashCodeNullable(flexTimeIndicator)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TimeAccount {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/User.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/User.java new file mode 100644 index 0000000..829963d --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/User.java @@ -0,0 +1,540 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.HolidayCalendarPartial; +import com.timr.api.models.WorkScheduleModelPartial; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A user's identity (`firstname`, `lastname`, `email`), employment dates (`entry_date`, `resign_date`), and the assigned `work_schedule_model` and `holiday_calendar`. + */ +@JsonPropertyOrder({ + User.JSON_PROPERTY_ID, + User.JSON_PROPERTY_FIRSTNAME, + User.JSON_PROPERTY_LASTNAME, + User.JSON_PROPERTY_FULLNAME, + User.JSON_PROPERTY_EMAIL, + User.JSON_PROPERTY_EMPLOYEE_NUMBER, + User.JSON_PROPERTY_EXTERNAL_ID, + User.JSON_PROPERTY_LOGIN, + User.JSON_PROPERTY_ENTRY_DATE, + User.JSON_PROPERTY_RESIGN_DATE, + User.JSON_PROPERTY_WORK_SCHEDULE_MODEL, + User.JSON_PROPERTY_HOLIDAY_CALENDAR, + User.JSON_PROPERTY_VACATION_YEAR_START, + User.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class User { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_FIRSTNAME = "firstname"; + @jakarta.annotation.Nullable + private String firstname; + + public static final String JSON_PROPERTY_LASTNAME = "lastname"; + @jakarta.annotation.Nullable + private String lastname; + + public static final String JSON_PROPERTY_FULLNAME = "fullname"; + @jakarta.annotation.Nullable + private String fullname; + + public static final String JSON_PROPERTY_EMAIL = "email"; + @jakarta.annotation.Nullable + private String email; + + public static final String JSON_PROPERTY_EMPLOYEE_NUMBER = "employee_number"; + @jakarta.annotation.Nullable + private String employeeNumber; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public static final String JSON_PROPERTY_LOGIN = "login"; + @jakarta.annotation.Nullable + private JsonNullable login = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ENTRY_DATE = "entry_date"; + @jakarta.annotation.Nullable + private JsonNullable entryDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RESIGN_DATE = "resign_date"; + @jakarta.annotation.Nullable + private JsonNullable resignDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORK_SCHEDULE_MODEL = "work_schedule_model"; + @jakarta.annotation.Nullable + private JsonNullable workScheduleModel = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_HOLIDAY_CALENDAR = "holiday_calendar"; + @jakarta.annotation.Nullable + private JsonNullable holidayCalendar = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_VACATION_YEAR_START = "vacation_year_start"; + @jakarta.annotation.Nullable + private JsonNullable vacationYearStart = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public User() { + } + + public User id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public User firstname(@jakarta.annotation.Nullable String firstname) { + + this.firstname = firstname; + return this; + } + + /** + * Get firstname + * @return firstname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getFirstname() { + return firstname; + } + + + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFirstname(@jakarta.annotation.Nullable String firstname) { + this.firstname = firstname; + } + + + public User lastname(@jakarta.annotation.Nullable String lastname) { + + this.lastname = lastname; + return this; + } + + /** + * Get lastname + * @return lastname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getLastname() { + return lastname; + } + + + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastname(@jakarta.annotation.Nullable String lastname) { + this.lastname = lastname; + } + + + public User fullname(@jakarta.annotation.Nullable String fullname) { + + this.fullname = fullname; + return this; + } + + /** + * Get fullname + * @return fullname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FULLNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getFullname() { + return fullname; + } + + + @JsonProperty(value = JSON_PROPERTY_FULLNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFullname(@jakarta.annotation.Nullable String fullname) { + this.fullname = fullname; + } + + + public User email(@jakarta.annotation.Nullable String email) { + + this.email = email; + return this; + } + + /** + * Email address must be either valid or null. + * @return email + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getEmail() { + return email; + } + + + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmail(@jakarta.annotation.Nullable String email) { + this.email = email; + } + + + public User employeeNumber(@jakarta.annotation.Nullable String employeeNumber) { + + this.employeeNumber = employeeNumber; + return this; + } + + /** + * Get employeeNumber + * @return employeeNumber + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getEmployeeNumber() { + return employeeNumber; + } + + + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmployeeNumber(@jakarta.annotation.Nullable String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + + public User externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + public User login(@jakarta.annotation.Nullable String login) { + this.login = JsonNullable.of(login); + + return this; + } + + /** + * Get login + * @return login + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOGIN, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLogin() { + return login; + } + + @JsonProperty(JSON_PROPERTY_LOGIN) + public void setLogin(JsonNullable login) { + this.login = login; + } + + + + public User entryDate(@jakarta.annotation.Nullable LocalDate entryDate) { + this.entryDate = JsonNullable.of(entryDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return entryDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ENTRY_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEntryDate() { + return entryDate; + } + + @JsonProperty(JSON_PROPERTY_ENTRY_DATE) + public void setEntryDate(JsonNullable entryDate) { + this.entryDate = entryDate; + } + + + + public User resignDate(@jakarta.annotation.Nullable LocalDate resignDate) { + this.resignDate = JsonNullable.of(resignDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return resignDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_RESIGN_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getResignDate() { + return resignDate; + } + + @JsonProperty(JSON_PROPERTY_RESIGN_DATE) + public void setResignDate(JsonNullable resignDate) { + this.resignDate = resignDate; + } + + + + public User workScheduleModel(@jakarta.annotation.Nullable WorkScheduleModelPartial workScheduleModel) { + this.workScheduleModel = JsonNullable.of(workScheduleModel); + + return this; + } + + /** + * Get workScheduleModel + * @return workScheduleModel + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_WORK_SCHEDULE_MODEL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getWorkScheduleModel() { + return workScheduleModel; + } + + @JsonProperty(JSON_PROPERTY_WORK_SCHEDULE_MODEL) + public void setWorkScheduleModel(JsonNullable workScheduleModel) { + this.workScheduleModel = workScheduleModel; + } + + + + public User holidayCalendar(@jakarta.annotation.Nullable HolidayCalendarPartial holidayCalendar) { + this.holidayCalendar = JsonNullable.of(holidayCalendar); + + return this; + } + + /** + * Get holidayCalendar + * @return holidayCalendar + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_HOLIDAY_CALENDAR, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getHolidayCalendar() { + return holidayCalendar; + } + + @JsonProperty(JSON_PROPERTY_HOLIDAY_CALENDAR) + public void setHolidayCalendar(JsonNullable holidayCalendar) { + this.holidayCalendar = holidayCalendar; + } + + + + public User vacationYearStart(@jakarta.annotation.Nullable String vacationYearStart) { + this.vacationYearStart = JsonNullable.of(vacationYearStart); + + return this; + } + + /** + * recurring month and day on which the user's vacation year starts + * @return vacationYearStart + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_VACATION_YEAR_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getVacationYearStart() { + return vacationYearStart; + } + + @JsonProperty(JSON_PROPERTY_VACATION_YEAR_START) + public void setVacationYearStart(JsonNullable vacationYearStart) { + this.vacationYearStart = vacationYearStart; + } + + + + public User metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public User putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.firstname, user.firstname) && + Objects.equals(this.lastname, user.lastname) && + Objects.equals(this.fullname, user.fullname) && + Objects.equals(this.email, user.email) && + Objects.equals(this.employeeNumber, user.employeeNumber) && + Objects.equals(this.externalId, user.externalId) && + equalsNullable(this.login, user.login) && + equalsNullable(this.entryDate, user.entryDate) && + equalsNullable(this.resignDate, user.resignDate) && + equalsNullable(this.workScheduleModel, user.workScheduleModel) && + equalsNullable(this.holidayCalendar, user.holidayCalendar) && + equalsNullable(this.vacationYearStart, user.vacationYearStart) && + equalsNullable(this.metadata, user.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, firstname, lastname, fullname, email, employeeNumber, externalId, hashCodeNullable(login), hashCodeNullable(entryDate), hashCodeNullable(resignDate), hashCodeNullable(workScheduleModel), hashCodeNullable(holidayCalendar), hashCodeNullable(vacationYearStart), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/UserCreate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UserCreate.java new file mode 100644 index 0000000..6db0a55 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UserCreate.java @@ -0,0 +1,435 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UserCreate + */ +@JsonPropertyOrder({ + UserCreate.JSON_PROPERTY_LOGIN, + UserCreate.JSON_PROPERTY_FIRSTNAME, + UserCreate.JSON_PROPERTY_LASTNAME, + UserCreate.JSON_PROPERTY_EMAIL, + UserCreate.JSON_PROPERTY_ENTRY_DATE, + UserCreate.JSON_PROPERTY_RESIGN_DATE, + UserCreate.JSON_PROPERTY_EMPLOYEE_NUMBER, + UserCreate.JSON_PROPERTY_EXTERNAL_ID, + UserCreate.JSON_PROPERTY_METADATA, + UserCreate.JSON_PROPERTY_AUTH_PROVIDER, + UserCreate.JSON_PROPERTY_AUTH_IDENTIFIER +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UserCreate { + public static final String JSON_PROPERTY_LOGIN = "login"; + @jakarta.annotation.Nonnull + private String login; + + public static final String JSON_PROPERTY_FIRSTNAME = "firstname"; + @jakarta.annotation.Nullable + private JsonNullable firstname = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LASTNAME = "lastname"; + @jakarta.annotation.Nullable + private JsonNullable lastname = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EMAIL = "email"; + @jakarta.annotation.Nullable + private JsonNullable email = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ENTRY_DATE = "entry_date"; + @jakarta.annotation.Nullable + private JsonNullable entryDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RESIGN_DATE = "resign_date"; + @jakarta.annotation.Nullable + private JsonNullable resignDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EMPLOYEE_NUMBER = "employee_number"; + @jakarta.annotation.Nullable + private JsonNullable employeeNumber = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private JsonNullable externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_AUTH_PROVIDER = "auth_provider"; + @jakarta.annotation.Nullable + private JsonNullable authProvider = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_AUTH_IDENTIFIER = "auth_identifier"; + @jakarta.annotation.Nullable + private JsonNullable authIdentifier = JsonNullable.undefined(); + + public UserCreate() { + } + + public UserCreate login(@jakarta.annotation.Nonnull String login) { + + this.login = login; + return this; + } + + /** + * Get login + * @return login + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LOGIN, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getLogin() { + return login; + } + + + @JsonProperty(value = JSON_PROPERTY_LOGIN, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLogin(@jakarta.annotation.Nonnull String login) { + this.login = login; + } + + + public UserCreate firstname(@jakarta.annotation.Nullable String firstname) { + this.firstname = JsonNullable.of(firstname); + + return this; + } + + /** + * Get firstname + * @return firstname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getFirstname() { + return firstname; + } + + @JsonProperty(JSON_PROPERTY_FIRSTNAME) + public void setFirstname(JsonNullable firstname) { + this.firstname = firstname; + } + + + + public UserCreate lastname(@jakarta.annotation.Nullable String lastname) { + this.lastname = JsonNullable.of(lastname); + + return this; + } + + /** + * Get lastname + * @return lastname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLastname() { + return lastname; + } + + @JsonProperty(JSON_PROPERTY_LASTNAME) + public void setLastname(JsonNullable lastname) { + this.lastname = lastname; + } + + + + public UserCreate email(@jakarta.annotation.Nullable String email) { + this.email = JsonNullable.of(email); + + return this; + } + + /** + * Get email + * @return email + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEmail() { + return email; + } + + @JsonProperty(JSON_PROPERTY_EMAIL) + public void setEmail(JsonNullable email) { + this.email = email; + } + + + + public UserCreate entryDate(@jakarta.annotation.Nullable LocalDate entryDate) { + this.entryDate = JsonNullable.of(entryDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return entryDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ENTRY_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEntryDate() { + return entryDate; + } + + @JsonProperty(JSON_PROPERTY_ENTRY_DATE) + public void setEntryDate(JsonNullable entryDate) { + this.entryDate = entryDate; + } + + + + public UserCreate resignDate(@jakarta.annotation.Nullable LocalDate resignDate) { + this.resignDate = JsonNullable.of(resignDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return resignDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_RESIGN_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getResignDate() { + return resignDate; + } + + @JsonProperty(JSON_PROPERTY_RESIGN_DATE) + public void setResignDate(JsonNullable resignDate) { + this.resignDate = resignDate; + } + + + + public UserCreate employeeNumber(@jakarta.annotation.Nullable String employeeNumber) { + this.employeeNumber = JsonNullable.of(employeeNumber); + + return this; + } + + /** + * Get employeeNumber + * @return employeeNumber + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEmployeeNumber() { + return employeeNumber; + } + + @JsonProperty(JSON_PROPERTY_EMPLOYEE_NUMBER) + public void setEmployeeNumber(JsonNullable employeeNumber) { + this.employeeNumber = employeeNumber; + } + + + + public UserCreate externalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Get externalId + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public UserCreate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public UserCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public UserCreate authProvider(@jakarta.annotation.Nullable String authProvider) { + this.authProvider = JsonNullable.of(authProvider); + + return this; + } + + /** + * Get authProvider + * @return authProvider + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_AUTH_PROVIDER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getAuthProvider() { + return authProvider; + } + + @JsonProperty(JSON_PROPERTY_AUTH_PROVIDER) + public void setAuthProvider(JsonNullable authProvider) { + this.authProvider = authProvider; + } + + + + public UserCreate authIdentifier(@jakarta.annotation.Nullable String authIdentifier) { + this.authIdentifier = JsonNullable.of(authIdentifier); + + return this; + } + + /** + * Get authIdentifier + * @return authIdentifier + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_AUTH_IDENTIFIER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getAuthIdentifier() { + return authIdentifier; + } + + @JsonProperty(JSON_PROPERTY_AUTH_IDENTIFIER) + public void setAuthIdentifier(JsonNullable authIdentifier) { + this.authIdentifier = authIdentifier; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserCreate userCreate = (UserCreate) o; + return Objects.equals(this.login, userCreate.login) && + equalsNullable(this.firstname, userCreate.firstname) && + equalsNullable(this.lastname, userCreate.lastname) && + equalsNullable(this.email, userCreate.email) && + equalsNullable(this.entryDate, userCreate.entryDate) && + equalsNullable(this.resignDate, userCreate.resignDate) && + equalsNullable(this.employeeNumber, userCreate.employeeNumber) && + equalsNullable(this.externalId, userCreate.externalId) && + equalsNullable(this.metadata, userCreate.metadata) && + equalsNullable(this.authProvider, userCreate.authProvider) && + equalsNullable(this.authIdentifier, userCreate.authIdentifier); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(login, hashCodeNullable(firstname), hashCodeNullable(lastname), hashCodeNullable(email), hashCodeNullable(entryDate), hashCodeNullable(resignDate), hashCodeNullable(employeeNumber), hashCodeNullable(externalId), hashCodeNullable(metadata), hashCodeNullable(authProvider), hashCodeNullable(authIdentifier)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UserCreate {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/UserPartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UserPartial.java new file mode 100644 index 0000000..b6d6619 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UserPartial.java @@ -0,0 +1,309 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UserPartial + */ +@JsonPropertyOrder({ + UserPartial.JSON_PROPERTY_ID, + UserPartial.JSON_PROPERTY_FIRSTNAME, + UserPartial.JSON_PROPERTY_LASTNAME, + UserPartial.JSON_PROPERTY_FULLNAME, + UserPartial.JSON_PROPERTY_EMAIL, + UserPartial.JSON_PROPERTY_EMPLOYEE_NUMBER, + UserPartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UserPartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_FIRSTNAME = "firstname"; + @jakarta.annotation.Nullable + private String firstname; + + public static final String JSON_PROPERTY_LASTNAME = "lastname"; + @jakarta.annotation.Nullable + private String lastname; + + public static final String JSON_PROPERTY_FULLNAME = "fullname"; + @jakarta.annotation.Nullable + private String fullname; + + public static final String JSON_PROPERTY_EMAIL = "email"; + @jakarta.annotation.Nullable + private String email; + + public static final String JSON_PROPERTY_EMPLOYEE_NUMBER = "employee_number"; + @jakarta.annotation.Nullable + private String employeeNumber; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public UserPartial() { + } + + public UserPartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public UserPartial firstname(@jakarta.annotation.Nullable String firstname) { + + this.firstname = firstname; + return this; + } + + /** + * Get firstname + * @return firstname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getFirstname() { + return firstname; + } + + + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFirstname(@jakarta.annotation.Nullable String firstname) { + this.firstname = firstname; + } + + + public UserPartial lastname(@jakarta.annotation.Nullable String lastname) { + + this.lastname = lastname; + return this; + } + + /** + * Get lastname + * @return lastname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getLastname() { + return lastname; + } + + + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastname(@jakarta.annotation.Nullable String lastname) { + this.lastname = lastname; + } + + + public UserPartial fullname(@jakarta.annotation.Nullable String fullname) { + + this.fullname = fullname; + return this; + } + + /** + * Get fullname + * @return fullname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FULLNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getFullname() { + return fullname; + } + + + @JsonProperty(value = JSON_PROPERTY_FULLNAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFullname(@jakarta.annotation.Nullable String fullname) { + this.fullname = fullname; + } + + + public UserPartial email(@jakarta.annotation.Nullable String email) { + + this.email = email; + return this; + } + + /** + * Email address must be either valid or null. + * @return email + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getEmail() { + return email; + } + + + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmail(@jakarta.annotation.Nullable String email) { + this.email = email; + } + + + public UserPartial employeeNumber(@jakarta.annotation.Nullable String employeeNumber) { + + this.employeeNumber = employeeNumber; + return this; + } + + /** + * Get employeeNumber + * @return employeeNumber + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getEmployeeNumber() { + return employeeNumber; + } + + + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEmployeeNumber(@jakarta.annotation.Nullable String employeeNumber) { + this.employeeNumber = employeeNumber; + } + + + public UserPartial externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserPartial userPartial = (UserPartial) o; + return Objects.equals(this.id, userPartial.id) && + Objects.equals(this.firstname, userPartial.firstname) && + Objects.equals(this.lastname, userPartial.lastname) && + Objects.equals(this.fullname, userPartial.fullname) && + Objects.equals(this.email, userPartial.email) && + Objects.equals(this.employeeNumber, userPartial.employeeNumber) && + Objects.equals(this.externalId, userPartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, firstname, lastname, fullname, email, employeeNumber, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UserPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/UserUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UserUpdate.java new file mode 100644 index 0000000..63ce6ec --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UserUpdate.java @@ -0,0 +1,373 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UserUpdate + */ +@JsonPropertyOrder({ + UserUpdate.JSON_PROPERTY_LOGIN, + UserUpdate.JSON_PROPERTY_FIRSTNAME, + UserUpdate.JSON_PROPERTY_LASTNAME, + UserUpdate.JSON_PROPERTY_EMAIL, + UserUpdate.JSON_PROPERTY_ENTRY_DATE, + UserUpdate.JSON_PROPERTY_RESIGN_DATE, + UserUpdate.JSON_PROPERTY_EMPLOYEE_NUMBER, + UserUpdate.JSON_PROPERTY_EXTERNAL_ID, + UserUpdate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UserUpdate { + public static final String JSON_PROPERTY_LOGIN = "login"; + @jakarta.annotation.Nullable + private JsonNullable login = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_FIRSTNAME = "firstname"; + @jakarta.annotation.Nullable + private JsonNullable firstname = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LASTNAME = "lastname"; + @jakarta.annotation.Nullable + private JsonNullable lastname = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EMAIL = "email"; + @jakarta.annotation.Nullable + private JsonNullable email = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_ENTRY_DATE = "entry_date"; + @jakarta.annotation.Nullable + private JsonNullable entryDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_RESIGN_DATE = "resign_date"; + @jakarta.annotation.Nullable + private JsonNullable resignDate = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EMPLOYEE_NUMBER = "employee_number"; + @jakarta.annotation.Nullable + private JsonNullable employeeNumber = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private JsonNullable externalId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public UserUpdate() { + } + + public UserUpdate login(@jakarta.annotation.Nullable String login) { + this.login = JsonNullable.of(login); + + return this; + } + + /** + * Get login + * @return login + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LOGIN, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLogin() { + return login; + } + + @JsonProperty(JSON_PROPERTY_LOGIN) + public void setLogin(JsonNullable login) { + this.login = login; + } + + + + public UserUpdate firstname(@jakarta.annotation.Nullable String firstname) { + this.firstname = JsonNullable.of(firstname); + + return this; + } + + /** + * Get firstname + * @return firstname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_FIRSTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getFirstname() { + return firstname; + } + + @JsonProperty(JSON_PROPERTY_FIRSTNAME) + public void setFirstname(JsonNullable firstname) { + this.firstname = firstname; + } + + + + public UserUpdate lastname(@jakarta.annotation.Nullable String lastname) { + this.lastname = JsonNullable.of(lastname); + + return this; + } + + /** + * Get lastname + * @return lastname + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LASTNAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLastname() { + return lastname; + } + + @JsonProperty(JSON_PROPERTY_LASTNAME) + public void setLastname(JsonNullable lastname) { + this.lastname = lastname; + } + + + + public UserUpdate email(@jakarta.annotation.Nullable String email) { + this.email = JsonNullable.of(email); + + return this; + } + + /** + * Get email + * @return email + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EMAIL, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEmail() { + return email; + } + + @JsonProperty(JSON_PROPERTY_EMAIL) + public void setEmail(JsonNullable email) { + this.email = email; + } + + + + public UserUpdate entryDate(@jakarta.annotation.Nullable LocalDate entryDate) { + this.entryDate = JsonNullable.of(entryDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return entryDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_ENTRY_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEntryDate() { + return entryDate; + } + + @JsonProperty(JSON_PROPERTY_ENTRY_DATE) + public void setEntryDate(JsonNullable entryDate) { + this.entryDate = entryDate; + } + + + + public UserUpdate resignDate(@jakarta.annotation.Nullable LocalDate resignDate) { + this.resignDate = JsonNullable.of(resignDate); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return resignDate + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_RESIGN_DATE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getResignDate() { + return resignDate; + } + + @JsonProperty(JSON_PROPERTY_RESIGN_DATE) + public void setResignDate(JsonNullable resignDate) { + this.resignDate = resignDate; + } + + + + public UserUpdate employeeNumber(@jakarta.annotation.Nullable String employeeNumber) { + this.employeeNumber = JsonNullable.of(employeeNumber); + + return this; + } + + /** + * Get employeeNumber + * @return employeeNumber + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EMPLOYEE_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEmployeeNumber() { + return employeeNumber; + } + + @JsonProperty(JSON_PROPERTY_EMPLOYEE_NUMBER) + public void setEmployeeNumber(JsonNullable employeeNumber) { + this.employeeNumber = employeeNumber; + } + + + + public UserUpdate externalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = JsonNullable.of(externalId); + + return this; + } + + /** + * Get externalId + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getExternalId() { + return externalId; + } + + @JsonProperty(JSON_PROPERTY_EXTERNAL_ID) + public void setExternalId(JsonNullable externalId) { + this.externalId = externalId; + } + + + + public UserUpdate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public UserUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserUpdate userUpdate = (UserUpdate) o; + return equalsNullable(this.login, userUpdate.login) && + equalsNullable(this.firstname, userUpdate.firstname) && + equalsNullable(this.lastname, userUpdate.lastname) && + equalsNullable(this.email, userUpdate.email) && + equalsNullable(this.entryDate, userUpdate.entryDate) && + equalsNullable(this.resignDate, userUpdate.resignDate) && + equalsNullable(this.employeeNumber, userUpdate.employeeNumber) && + equalsNullable(this.externalId, userUpdate.externalId) && + equalsNullable(this.metadata, userUpdate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(login), hashCodeNullable(firstname), hashCodeNullable(lastname), hashCodeNullable(email), hashCodeNullable(entryDate), hashCodeNullable(resignDate), hashCodeNullable(employeeNumber), hashCodeNullable(externalId), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UserUpdate {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/UsersPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UsersPage.java new file mode 100644 index 0000000..8b5dcda --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UsersPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.User; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UsersPage + */ +@JsonPropertyOrder({ + UsersPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + UsersPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UsersPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public UsersPage() { + } + + public UsersPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public UsersPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public UsersPage addDataItem(User dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UsersPage usersPage = (UsersPage) o; + return Objects.equals(this.nextPageToken, usersPage.nextPageToken) && + Objects.equals(this.data, usersPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UsersPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/UsersPartialPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UsersPartialPage.java new file mode 100644 index 0000000..3e38636 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UsersPartialPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * UsersPartialPage + */ +@JsonPropertyOrder({ + UsersPartialPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + UsersPartialPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class UsersPartialPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public UsersPartialPage() { + } + + public UsersPartialPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public UsersPartialPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public UsersPartialPage addDataItem(UserPartial dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UsersPartialPage usersPartialPage = (UsersPartialPage) o; + return Objects.equals(this.nextPageToken, usersPartialPage.nextPageToken) && + Objects.equals(this.data, usersPartialPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class UsersPartialPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/UsersSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UsersSortColumn.java new file mode 100644 index 0000000..47f5b40 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/UsersSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Users. `name` orders by last name, then first name. + */ +public enum UsersSortColumn { + + NAME("name"); + + private String value; + + UsersSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static UsersSortColumn fromValue(String value) { + for (UsersSortColumn b : UsersSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccount.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccount.java new file mode 100644 index 0000000..8262c38 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccount.java @@ -0,0 +1,51 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.VacationAccountDays; +import com.timr.api.models.VacationAccountMinutes; +import com.timr.api.models.VacationUnit; +import java.math.BigDecimal; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +@JsonIgnoreProperties( + value = "unit", // ignore manually set unit, it will be automatically generated by Jackson during serialization + allowSetters = true // allows the unit to be set during deserialization +) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "unit", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = VacationAccountDays.class, name = "days"), + @JsonSubTypes.Type(value = VacationAccountMinutes.class, name = "minutes"), +}) + +public interface VacationAccount { + public VacationUnit getUnit(); +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccountBase.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccountBase.java new file mode 100644 index 0000000..79dc860 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccountBase.java @@ -0,0 +1,117 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.VacationUnit; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Members shared by every kind of vacation account, including the discriminator. + */ +@JsonPropertyOrder({ + VacationAccountBase.JSON_PROPERTY_UNIT +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class VacationAccountBase { + public static final String JSON_PROPERTY_UNIT = "unit"; + @jakarta.annotation.Nonnull + protected VacationUnit unit; + + public VacationAccountBase() { + } + + public VacationAccountBase unit(@jakarta.annotation.Nonnull VacationUnit unit) { + + this.unit = unit; + return this; + } + + /** + * Get unit + * @return unit + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_UNIT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public VacationUnit getUnit() { + return unit; + } + + + @JsonProperty(value = JSON_PROPERTY_UNIT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUnit(@jakarta.annotation.Nonnull VacationUnit unit) { + this.unit = unit; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VacationAccountBase vacationAccountBase = (VacationAccountBase) o; + return Objects.equals(this.unit, vacationAccountBase.unit); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(unit); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class VacationAccountBase {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccountDays.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccountDays.java new file mode 100644 index 0000000..8ab03fc --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccountDays.java @@ -0,0 +1,214 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.VacationAccountBase; +import com.timr.api.models.VacationUnit; +import java.math.BigDecimal; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * VacationAccountDays + */ +@JsonPropertyOrder({ + VacationAccountDays.JSON_PROPERTY_BALANCE_LAST_PERIOD_DAYS, + VacationAccountDays.JSON_PROPERTY_CONSUMED_DAYS, + VacationAccountDays.JSON_PROPERTY_NEW_DAYS, + VacationAccountDays.JSON_PROPERTY_BALANCE_TOTAL_DAYS +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class VacationAccountDays extends VacationAccountBase implements VacationAccount { + public static final String JSON_PROPERTY_BALANCE_LAST_PERIOD_DAYS = "balance_last_period_days"; + @jakarta.annotation.Nullable + private JsonNullable balanceLastPeriodDays = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CONSUMED_DAYS = "consumed_days"; + @jakarta.annotation.Nullable + private JsonNullable consumedDays = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NEW_DAYS = "new_days"; + @jakarta.annotation.Nullable + private JsonNullable newDays = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BALANCE_TOTAL_DAYS = "balance_total_days"; + @jakarta.annotation.Nullable + private JsonNullable balanceTotalDays = JsonNullable.undefined(); + + public VacationAccountDays() { + + } + + public VacationAccountDays balanceLastPeriodDays(@jakarta.annotation.Nullable BigDecimal balanceLastPeriodDays) { + this.balanceLastPeriodDays = JsonNullable.of(balanceLastPeriodDays); + + return this; + } + + /** + * vacation balance carried over from the previous vacation period, in days + * @return balanceLastPeriodDays + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_DAYS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBalanceLastPeriodDays() { + return balanceLastPeriodDays; + } + + @JsonProperty(JSON_PROPERTY_BALANCE_LAST_PERIOD_DAYS) + public void setBalanceLastPeriodDays(JsonNullable balanceLastPeriodDays) { + this.balanceLastPeriodDays = balanceLastPeriodDays; + } + + + + public VacationAccountDays consumedDays(@jakarta.annotation.Nullable BigDecimal consumedDays) { + this.consumedDays = JsonNullable.of(consumedDays); + + return this; + } + + /** + * vacation consumed in the current vacation period, in days + * @return consumedDays + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CONSUMED_DAYS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getConsumedDays() { + return consumedDays; + } + + @JsonProperty(JSON_PROPERTY_CONSUMED_DAYS) + public void setConsumedDays(JsonNullable consumedDays) { + this.consumedDays = consumedDays; + } + + + + public VacationAccountDays newDays(@jakarta.annotation.Nullable BigDecimal newDays) { + this.newDays = JsonNullable.of(newDays); + + return this; + } + + /** + * vacation newly granted in the current vacation period, in days + * @return newDays + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEW_DAYS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNewDays() { + return newDays; + } + + @JsonProperty(JSON_PROPERTY_NEW_DAYS) + public void setNewDays(JsonNullable newDays) { + this.newDays = newDays; + } + + + + public VacationAccountDays balanceTotalDays(@jakarta.annotation.Nullable BigDecimal balanceTotalDays) { + this.balanceTotalDays = JsonNullable.of(balanceTotalDays); + + return this; + } + + /** + * total vacation balance for the current vacation period, in days + * @return balanceTotalDays + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_DAYS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBalanceTotalDays() { + return balanceTotalDays; + } + + @JsonProperty(JSON_PROPERTY_BALANCE_TOTAL_DAYS) + public void setBalanceTotalDays(JsonNullable balanceTotalDays) { + this.balanceTotalDays = balanceTotalDays; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VacationAccountDays vacationAccountDays = (VacationAccountDays) o; + return equalsNullable(this.balanceLastPeriodDays, vacationAccountDays.balanceLastPeriodDays) && + equalsNullable(this.consumedDays, vacationAccountDays.consumedDays) && + equalsNullable(this.newDays, vacationAccountDays.newDays) && + equalsNullable(this.balanceTotalDays, vacationAccountDays.balanceTotalDays) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(balanceLastPeriodDays), hashCodeNullable(consumedDays), hashCodeNullable(newDays), hashCodeNullable(balanceTotalDays), super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class VacationAccountDays {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccountMinutes.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccountMinutes.java new file mode 100644 index 0000000..3abb299 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationAccountMinutes.java @@ -0,0 +1,214 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.VacationAccountBase; +import com.timr.api.models.VacationUnit; +import java.math.BigDecimal; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * VacationAccountMinutes + */ +@JsonPropertyOrder({ + VacationAccountMinutes.JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, + VacationAccountMinutes.JSON_PROPERTY_CONSUMED_MINUTES, + VacationAccountMinutes.JSON_PROPERTY_NEW_MINUTES, + VacationAccountMinutes.JSON_PROPERTY_BALANCE_TOTAL_MINUTES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class VacationAccountMinutes extends VacationAccountBase implements VacationAccount { + public static final String JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES = "balance_last_period_minutes"; + @jakarta.annotation.Nullable + private JsonNullable balanceLastPeriodMinutes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CONSUMED_MINUTES = "consumed_minutes"; + @jakarta.annotation.Nullable + private JsonNullable consumedMinutes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NEW_MINUTES = "new_minutes"; + @jakarta.annotation.Nullable + private JsonNullable newMinutes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BALANCE_TOTAL_MINUTES = "balance_total_minutes"; + @jakarta.annotation.Nullable + private JsonNullable balanceTotalMinutes = JsonNullable.undefined(); + + public VacationAccountMinutes() { + + } + + public VacationAccountMinutes balanceLastPeriodMinutes(@jakarta.annotation.Nullable BigDecimal balanceLastPeriodMinutes) { + this.balanceLastPeriodMinutes = JsonNullable.of(balanceLastPeriodMinutes); + + return this; + } + + /** + * vacation balance carried over from the previous vacation period, in minutes + * @return balanceLastPeriodMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBalanceLastPeriodMinutes() { + return balanceLastPeriodMinutes; + } + + @JsonProperty(JSON_PROPERTY_BALANCE_LAST_PERIOD_MINUTES) + public void setBalanceLastPeriodMinutes(JsonNullable balanceLastPeriodMinutes) { + this.balanceLastPeriodMinutes = balanceLastPeriodMinutes; + } + + + + public VacationAccountMinutes consumedMinutes(@jakarta.annotation.Nullable BigDecimal consumedMinutes) { + this.consumedMinutes = JsonNullable.of(consumedMinutes); + + return this; + } + + /** + * vacation consumed in the current vacation period, in minutes + * @return consumedMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CONSUMED_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getConsumedMinutes() { + return consumedMinutes; + } + + @JsonProperty(JSON_PROPERTY_CONSUMED_MINUTES) + public void setConsumedMinutes(JsonNullable consumedMinutes) { + this.consumedMinutes = consumedMinutes; + } + + + + public VacationAccountMinutes newMinutes(@jakarta.annotation.Nullable BigDecimal newMinutes) { + this.newMinutes = JsonNullable.of(newMinutes); + + return this; + } + + /** + * vacation newly granted in the current vacation period, in minutes + * @return newMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEW_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNewMinutes() { + return newMinutes; + } + + @JsonProperty(JSON_PROPERTY_NEW_MINUTES) + public void setNewMinutes(JsonNullable newMinutes) { + this.newMinutes = newMinutes; + } + + + + public VacationAccountMinutes balanceTotalMinutes(@jakarta.annotation.Nullable BigDecimal balanceTotalMinutes) { + this.balanceTotalMinutes = JsonNullable.of(balanceTotalMinutes); + + return this; + } + + /** + * total vacation balance for the current vacation period, in minutes + * @return balanceTotalMinutes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BALANCE_TOTAL_MINUTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getBalanceTotalMinutes() { + return balanceTotalMinutes; + } + + @JsonProperty(JSON_PROPERTY_BALANCE_TOTAL_MINUTES) + public void setBalanceTotalMinutes(JsonNullable balanceTotalMinutes) { + this.balanceTotalMinutes = balanceTotalMinutes; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VacationAccountMinutes vacationAccountMinutes = (VacationAccountMinutes) o; + return equalsNullable(this.balanceLastPeriodMinutes, vacationAccountMinutes.balanceLastPeriodMinutes) && + equalsNullable(this.consumedMinutes, vacationAccountMinutes.consumedMinutes) && + equalsNullable(this.newMinutes, vacationAccountMinutes.newMinutes) && + equalsNullable(this.balanceTotalMinutes, vacationAccountMinutes.balanceTotalMinutes) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(balanceLastPeriodMinutes), hashCodeNullable(consumedMinutes), hashCodeNullable(newMinutes), hashCodeNullable(balanceTotalMinutes), super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class VacationAccountMinutes {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationUnit.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationUnit.java new file mode 100644 index 0000000..288b1d6 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VacationUnit.java @@ -0,0 +1,60 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Unit a vacation entitlement is expressed in. + */ +public enum VacationUnit { + + DAYS("days"), + + MINUTES("minutes"); + + private String value; + + VacationUnit(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static VacationUnit fromValue(String value) { + for (VacationUnit b : VacationUnit.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/VenuePartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VenuePartial.java new file mode 100644 index 0000000..848ead7 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/VenuePartial.java @@ -0,0 +1,369 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * VenuePartial + */ +@JsonPropertyOrder({ + VenuePartial.JSON_PROPERTY_ID, + VenuePartial.JSON_PROPERTY_NAME, + VenuePartial.JSON_PROPERTY_CITY, + VenuePartial.JSON_PROPERTY_ZIP_CODE, + VenuePartial.JSON_PROPERTY_STREET, + VenuePartial.JSON_PROPERTY_STREET_NUMBER, + VenuePartial.JSON_PROPERTY_COUNTRY, + VenuePartial.JSON_PROPERTY_LAT, + VenuePartial.JSON_PROPERTY_LON +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class VenuePartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_CITY = "city"; + @jakarta.annotation.Nonnull + private String city; + + public static final String JSON_PROPERTY_ZIP_CODE = "zip_code"; + @jakarta.annotation.Nonnull + private String zipCode; + + public static final String JSON_PROPERTY_STREET = "street"; + @jakarta.annotation.Nonnull + private String street; + + public static final String JSON_PROPERTY_STREET_NUMBER = "street_number"; + @jakarta.annotation.Nonnull + private String streetNumber; + + public static final String JSON_PROPERTY_COUNTRY = "country"; + @jakarta.annotation.Nonnull + private String country; + + public static final String JSON_PROPERTY_LAT = "lat"; + @jakarta.annotation.Nullable + private JsonNullable lat = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LON = "lon"; + @jakarta.annotation.Nullable + private JsonNullable lon = JsonNullable.undefined(); + + public VenuePartial() { + } + + public VenuePartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public VenuePartial name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public VenuePartial city(@jakarta.annotation.Nonnull String city) { + + this.city = city; + return this; + } + + /** + * Get city + * @return city + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CITY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCity() { + return city; + } + + + @JsonProperty(value = JSON_PROPERTY_CITY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCity(@jakarta.annotation.Nonnull String city) { + this.city = city; + } + + + public VenuePartial zipCode(@jakarta.annotation.Nonnull String zipCode) { + + this.zipCode = zipCode; + return this; + } + + /** + * Get zipCode + * @return zipCode + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ZIP_CODE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getZipCode() { + return zipCode; + } + + + @JsonProperty(value = JSON_PROPERTY_ZIP_CODE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setZipCode(@jakarta.annotation.Nonnull String zipCode) { + this.zipCode = zipCode; + } + + + public VenuePartial street(@jakarta.annotation.Nonnull String street) { + + this.street = street; + return this; + } + + /** + * Get street + * @return street + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STREET, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getStreet() { + return street; + } + + + @JsonProperty(value = JSON_PROPERTY_STREET, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStreet(@jakarta.annotation.Nonnull String street) { + this.street = street; + } + + + public VenuePartial streetNumber(@jakarta.annotation.Nonnull String streetNumber) { + + this.streetNumber = streetNumber; + return this; + } + + /** + * Get streetNumber + * @return streetNumber + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STREET_NUMBER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getStreetNumber() { + return streetNumber; + } + + + @JsonProperty(value = JSON_PROPERTY_STREET_NUMBER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStreetNumber(@jakarta.annotation.Nonnull String streetNumber) { + this.streetNumber = streetNumber; + } + + + public VenuePartial country(@jakarta.annotation.Nonnull String country) { + + this.country = country; + return this; + } + + /** + * Get country + * @return country + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_COUNTRY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getCountry() { + return country; + } + + + @JsonProperty(value = JSON_PROPERTY_COUNTRY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCountry(@jakarta.annotation.Nonnull String country) { + this.country = country; + } + + + public VenuePartial lat(@jakarta.annotation.Nullable Float lat) { + this.lat = JsonNullable.of(lat); + + return this; + } + + /** + * Latitude in decimal degrees. + * @return lat + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAT, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLat() { + return lat; + } + + @JsonProperty(JSON_PROPERTY_LAT) + public void setLat(JsonNullable lat) { + this.lat = lat; + } + + + + public VenuePartial lon(@jakarta.annotation.Nullable Float lon) { + this.lon = JsonNullable.of(lon); + + return this; + } + + /** + * Longitude in decimal degrees. + * @return lon + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LON, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getLon() { + return lon; + } + + @JsonProperty(JSON_PROPERTY_LON) + public void setLon(JsonNullable lon) { + this.lon = lon; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + VenuePartial venuePartial = (VenuePartial) o; + return Objects.equals(this.id, venuePartial.id) && + Objects.equals(this.name, venuePartial.name) && + Objects.equals(this.city, venuePartial.city) && + Objects.equals(this.zipCode, venuePartial.zipCode) && + Objects.equals(this.street, venuePartial.street) && + Objects.equals(this.streetNumber, venuePartial.streetNumber) && + Objects.equals(this.country, venuePartial.country) && + equalsNullable(this.lat, venuePartial.lat) && + equalsNullable(this.lon, venuePartial.lon); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, city, zipCode, street, streetNumber, country, hashCodeNullable(lat), hashCodeNullable(lon)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class VenuePartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/Waypoint.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Waypoint.java new file mode 100644 index 0000000..3bb3205 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/Waypoint.java @@ -0,0 +1,148 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * Waypoint + */ +@JsonPropertyOrder({ + Waypoint.JSON_PROPERTY_LAT, + Waypoint.JSON_PROPERTY_LON +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class Waypoint { + public static final String JSON_PROPERTY_LAT = "lat"; + @jakarta.annotation.Nonnull + private Double lat; + + public static final String JSON_PROPERTY_LON = "lon"; + @jakarta.annotation.Nonnull + private Double lon; + + public Waypoint() { + } + + public Waypoint lat(@jakarta.annotation.Nonnull Double lat) { + + this.lat = lat; + return this; + } + + /** + * Get lat + * @return lat + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LAT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Double getLat() { + return lat; + } + + + @JsonProperty(value = JSON_PROPERTY_LAT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLat(@jakarta.annotation.Nonnull Double lat) { + this.lat = lat; + } + + + public Waypoint lon(@jakarta.annotation.Nonnull Double lon) { + + this.lon = lon; + return this; + } + + /** + * Get lon + * @return lon + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LON, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Double getLon() { + return lon; + } + + + @JsonProperty(value = JSON_PROPERTY_LON, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLon(@jakarta.annotation.Nonnull Double lon) { + this.lon = lon; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Waypoint waypoint = (Waypoint) o; + return Objects.equals(this.lat, waypoint.lat) && + Objects.equals(this.lon, waypoint.lon); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(lat, lon); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Waypoint {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModel.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModel.java new file mode 100644 index 0000000..7302c96 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModel.java @@ -0,0 +1,260 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkScheduleModelType; +import com.timr.api.models.WorkScheduleModelWeek; +import com.timr.api.models.WorkingTimeRules; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * The weekday targets a user is measured against: `weeks` holds the layout, `type` selects the calculation mode, and `working_time_rules` the recording constraints. + */ +@JsonPropertyOrder({ + WorkScheduleModel.JSON_PROPERTY_ID, + WorkScheduleModel.JSON_PROPERTY_NAME, + WorkScheduleModel.JSON_PROPERTY_TYPE, + WorkScheduleModel.JSON_PROPERTY_WEEKS, + WorkScheduleModel.JSON_PROPERTY_WORKING_TIME_RULES +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkScheduleModel { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_TYPE = "type"; + @jakarta.annotation.Nonnull + private WorkScheduleModelType type; + + public static final String JSON_PROPERTY_WEEKS = "weeks"; + @jakarta.annotation.Nonnull + private List weeks; + + public static final String JSON_PROPERTY_WORKING_TIME_RULES = "working_time_rules"; + @jakarta.annotation.Nullable + private WorkingTimeRules workingTimeRules; + + public WorkScheduleModel() { + } + + public WorkScheduleModel id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public WorkScheduleModel name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public WorkScheduleModel type(@jakarta.annotation.Nonnull WorkScheduleModelType type) { + + this.type = type; + return this; + } + + /** + * working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks) + * @return type + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkScheduleModelType getType() { + return type; + } + + + @JsonProperty(value = JSON_PROPERTY_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setType(@jakarta.annotation.Nonnull WorkScheduleModelType type) { + this.type = type; + } + + + public WorkScheduleModel weeks(@jakarta.annotation.Nonnull List weeks) { + + this.weeks = weeks; + return this; + } + + public WorkScheduleModel addWeeksItem(WorkScheduleModelWeek weeksItem) { + if (this.weeks == null) { + this.weeks = new ArrayList<>(); + } + this.weeks.add(weeksItem); + return this; + } + + /** + * for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name + * @return weeks + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_WEEKS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getWeeks() { + return weeks; + } + + + @JsonProperty(value = JSON_PROPERTY_WEEKS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWeeks(@jakarta.annotation.Nonnull List weeks) { + this.weeks = weeks; + } + + + public WorkScheduleModel workingTimeRules(@jakarta.annotation.Nullable WorkingTimeRules workingTimeRules) { + + this.workingTimeRules = workingTimeRules; + return this; + } + + /** + * Get workingTimeRules + * @return workingTimeRules + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_RULES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeRules getWorkingTimeRules() { + return workingTimeRules; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_RULES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeRules(@jakarta.annotation.Nullable WorkingTimeRules workingTimeRules) { + this.workingTimeRules = workingTimeRules; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkScheduleModel workScheduleModel = (WorkScheduleModel) o; + return Objects.equals(this.id, workScheduleModel.id) && + Objects.equals(this.name, workScheduleModel.name) && + Objects.equals(this.type, workScheduleModel.type) && + Objects.equals(this.weeks, workScheduleModel.weeks) && + Objects.equals(this.workingTimeRules, workScheduleModel.workingTimeRules); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, type, weeks, workingTimeRules); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkScheduleModel {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelPartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelPartial.java new file mode 100644 index 0000000..dcfc465 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelPartial.java @@ -0,0 +1,149 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkScheduleModelPartial + */ +@JsonPropertyOrder({ + WorkScheduleModelPartial.JSON_PROPERTY_ID, + WorkScheduleModelPartial.JSON_PROPERTY_NAME +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkScheduleModelPartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public WorkScheduleModelPartial() { + } + + public WorkScheduleModelPartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public WorkScheduleModelPartial name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkScheduleModelPartial workScheduleModelPartial = (WorkScheduleModelPartial) o; + return Objects.equals(this.id, workScheduleModelPartial.id) && + Objects.equals(this.name, workScheduleModelPartial.name); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkScheduleModelPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelSortColumn.java new file mode 100644 index 0000000..1f83d17 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Work Schedule Models. + */ +public enum WorkScheduleModelSortColumn { + + NAME("name"); + + private String value; + + WorkScheduleModelSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkScheduleModelSortColumn fromValue(String value) { + for (WorkScheduleModelSortColumn b : WorkScheduleModelSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelType.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelType.java new file mode 100644 index 0000000..146eee1 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelType.java @@ -0,0 +1,60 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * How the target working time of the model is defined. + */ +public enum WorkScheduleModelType { + + DAILY_TARGET_HOURS("daily_target_hours"), + + NORMAL_WORKING_TIME("normal_working_time"); + + private String value; + + WorkScheduleModelType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkScheduleModelType fromValue(String value) { + for (WorkScheduleModelType b : WorkScheduleModelType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelWeek.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelWeek.java new file mode 100644 index 0000000..f101458 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelWeek.java @@ -0,0 +1,405 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DailyWorkSchedule; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkScheduleModelWeek + */ +@JsonPropertyOrder({ + WorkScheduleModelWeek.JSON_PROPERTY_WEEK_NUMBER, + WorkScheduleModelWeek.JSON_PROPERTY_NAME, + WorkScheduleModelWeek.JSON_PROPERTY_TARGET_DURATION_WEEKLY_MINUTES, + WorkScheduleModelWeek.JSON_PROPERTY_MONDAY, + WorkScheduleModelWeek.JSON_PROPERTY_TUESDAY, + WorkScheduleModelWeek.JSON_PROPERTY_WEDNESDAY, + WorkScheduleModelWeek.JSON_PROPERTY_THURSDAY, + WorkScheduleModelWeek.JSON_PROPERTY_FRIDAY, + WorkScheduleModelWeek.JSON_PROPERTY_SATURDAY, + WorkScheduleModelWeek.JSON_PROPERTY_SUNDAY +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkScheduleModelWeek { + public static final String JSON_PROPERTY_WEEK_NUMBER = "week_number"; + @jakarta.annotation.Nullable + private JsonNullable weekNumber = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nullable + private JsonNullable name = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_TARGET_DURATION_WEEKLY_MINUTES = "target_duration_weekly_minutes"; + @jakarta.annotation.Nonnull + private Long targetDurationWeeklyMinutes; + + public static final String JSON_PROPERTY_MONDAY = "monday"; + @jakarta.annotation.Nonnull + private DailyWorkSchedule monday; + + public static final String JSON_PROPERTY_TUESDAY = "tuesday"; + @jakarta.annotation.Nonnull + private DailyWorkSchedule tuesday; + + public static final String JSON_PROPERTY_WEDNESDAY = "wednesday"; + @jakarta.annotation.Nonnull + private DailyWorkSchedule wednesday; + + public static final String JSON_PROPERTY_THURSDAY = "thursday"; + @jakarta.annotation.Nonnull + private DailyWorkSchedule thursday; + + public static final String JSON_PROPERTY_FRIDAY = "friday"; + @jakarta.annotation.Nonnull + private DailyWorkSchedule friday; + + public static final String JSON_PROPERTY_SATURDAY = "saturday"; + @jakarta.annotation.Nonnull + private DailyWorkSchedule saturday; + + public static final String JSON_PROPERTY_SUNDAY = "sunday"; + @jakarta.annotation.Nonnull + private DailyWorkSchedule sunday; + + public WorkScheduleModelWeek() { + } + + public WorkScheduleModelWeek weekNumber(@jakarta.annotation.Nullable Integer weekNumber) { + this.weekNumber = JsonNullable.of(weekNumber); + + return this; + } + + /** + * index of the week in alternating_weeks models (0-based); omitted for fixed_week models + * @return weekNumber + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_WEEK_NUMBER, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getWeekNumber() { + return weekNumber; + } + + @JsonProperty(JSON_PROPERTY_WEEK_NUMBER) + public void setWeekNumber(JsonNullable weekNumber) { + this.weekNumber = weekNumber; + } + + + + public WorkScheduleModelWeek name(@jakarta.annotation.Nullable String name) { + this.name = JsonNullable.of(name); + + return this; + } + + /** + * display name of the week in alternating_weeks models; omitted for fixed_week models + * @return name + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getName() { + return name; + } + + @JsonProperty(JSON_PROPERTY_NAME) + public void setName(JsonNullable name) { + this.name = name; + } + + + + public WorkScheduleModelWeek targetDurationWeeklyMinutes(@jakarta.annotation.Nonnull Long targetDurationWeeklyMinutes) { + + this.targetDurationWeeklyMinutes = targetDurationWeeklyMinutes; + return this; + } + + /** + * value in minutes + * @return targetDurationWeeklyMinutes + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TARGET_DURATION_WEEKLY_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Long getTargetDurationWeeklyMinutes() { + return targetDurationWeeklyMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_TARGET_DURATION_WEEKLY_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTargetDurationWeeklyMinutes(@jakarta.annotation.Nonnull Long targetDurationWeeklyMinutes) { + this.targetDurationWeeklyMinutes = targetDurationWeeklyMinutes; + } + + + public WorkScheduleModelWeek monday(@jakarta.annotation.Nonnull DailyWorkSchedule monday) { + + this.monday = monday; + return this; + } + + /** + * Get monday + * @return monday + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_MONDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getMonday() { + return monday; + } + + + @JsonProperty(value = JSON_PROPERTY_MONDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setMonday(@jakarta.annotation.Nonnull DailyWorkSchedule monday) { + this.monday = monday; + } + + + public WorkScheduleModelWeek tuesday(@jakarta.annotation.Nonnull DailyWorkSchedule tuesday) { + + this.tuesday = tuesday; + return this; + } + + /** + * Get tuesday + * @return tuesday + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_TUESDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getTuesday() { + return tuesday; + } + + + @JsonProperty(value = JSON_PROPERTY_TUESDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setTuesday(@jakarta.annotation.Nonnull DailyWorkSchedule tuesday) { + this.tuesday = tuesday; + } + + + public WorkScheduleModelWeek wednesday(@jakarta.annotation.Nonnull DailyWorkSchedule wednesday) { + + this.wednesday = wednesday; + return this; + } + + /** + * Get wednesday + * @return wednesday + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_WEDNESDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getWednesday() { + return wednesday; + } + + + @JsonProperty(value = JSON_PROPERTY_WEDNESDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWednesday(@jakarta.annotation.Nonnull DailyWorkSchedule wednesday) { + this.wednesday = wednesday; + } + + + public WorkScheduleModelWeek thursday(@jakarta.annotation.Nonnull DailyWorkSchedule thursday) { + + this.thursday = thursday; + return this; + } + + /** + * Get thursday + * @return thursday + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_THURSDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getThursday() { + return thursday; + } + + + @JsonProperty(value = JSON_PROPERTY_THURSDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setThursday(@jakarta.annotation.Nonnull DailyWorkSchedule thursday) { + this.thursday = thursday; + } + + + public WorkScheduleModelWeek friday(@jakarta.annotation.Nonnull DailyWorkSchedule friday) { + + this.friday = friday; + return this; + } + + /** + * Get friday + * @return friday + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_FRIDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getFriday() { + return friday; + } + + + @JsonProperty(value = JSON_PROPERTY_FRIDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setFriday(@jakarta.annotation.Nonnull DailyWorkSchedule friday) { + this.friday = friday; + } + + + public WorkScheduleModelWeek saturday(@jakarta.annotation.Nonnull DailyWorkSchedule saturday) { + + this.saturday = saturday; + return this; + } + + /** + * Get saturday + * @return saturday + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_SATURDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getSaturday() { + return saturday; + } + + + @JsonProperty(value = JSON_PROPERTY_SATURDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSaturday(@jakarta.annotation.Nonnull DailyWorkSchedule saturday) { + this.saturday = saturday; + } + + + public WorkScheduleModelWeek sunday(@jakarta.annotation.Nonnull DailyWorkSchedule sunday) { + + this.sunday = sunday; + return this; + } + + /** + * Get sunday + * @return sunday + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_SUNDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DailyWorkSchedule getSunday() { + return sunday; + } + + + @JsonProperty(value = JSON_PROPERTY_SUNDAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSunday(@jakarta.annotation.Nonnull DailyWorkSchedule sunday) { + this.sunday = sunday; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkScheduleModelWeek workScheduleModelWeek = (WorkScheduleModelWeek) o; + return equalsNullable(this.weekNumber, workScheduleModelWeek.weekNumber) && + equalsNullable(this.name, workScheduleModelWeek.name) && + Objects.equals(this.targetDurationWeeklyMinutes, workScheduleModelWeek.targetDurationWeeklyMinutes) && + Objects.equals(this.monday, workScheduleModelWeek.monday) && + Objects.equals(this.tuesday, workScheduleModelWeek.tuesday) && + Objects.equals(this.wednesday, workScheduleModelWeek.wednesday) && + Objects.equals(this.thursday, workScheduleModelWeek.thursday) && + Objects.equals(this.friday, workScheduleModelWeek.friday) && + Objects.equals(this.saturday, workScheduleModelWeek.saturday) && + Objects.equals(this.sunday, workScheduleModelWeek.sunday); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(weekNumber), hashCodeNullable(name), targetDurationWeeklyMinutes, monday, tuesday, wednesday, thursday, friday, saturday, sunday); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkScheduleModelWeek {\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelsPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelsPage.java new file mode 100644 index 0000000..6a5c2b7 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkScheduleModelsPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkScheduleModel; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkScheduleModelsPage + */ +@JsonPropertyOrder({ + WorkScheduleModelsPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + WorkScheduleModelsPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkScheduleModelsPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public WorkScheduleModelsPage() { + } + + public WorkScheduleModelsPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public WorkScheduleModelsPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public WorkScheduleModelsPage addDataItem(WorkScheduleModel dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkScheduleModelsPage workScheduleModelsPage = (WorkScheduleModelsPage) o; + return Objects.equals(this.nextPageToken, workScheduleModelsPage.nextPageToken) && + Objects.equals(this.data, workScheduleModelsPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkScheduleModelsPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTime.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTime.java new file mode 100644 index 0000000..5230369 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTime.java @@ -0,0 +1,735 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTime; +import com.timr.api.models.Duration; +import com.timr.api.models.Location; +import com.timr.api.models.Platform; +import com.timr.api.models.UserPartial; +import com.timr.api.models.WorkingTimeDateSpanPartial; +import com.timr.api.models.WorkingTimeStatus; +import com.timr.api.models.WorkingTimeTypePartial; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * One continuous stretch from `start` to `end`, classified by its `working_time_type`. Attendance entries carry `break_times`, locations and the platform they were recorded on; an entry derived from a multi-day absence links back to its `working_time_date_span`. + */ +@JsonPropertyOrder({ + WorkingTime.JSON_PROPERTY_ID, + WorkingTime.JSON_PROPERTY_START, + WorkingTime.JSON_PROPERTY_END, + WorkingTime.JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, + WorkingTime.JSON_PROPERTY_BREAK_TIMES, + WorkingTime.JSON_PROPERTY_DURATION, + WorkingTime.JSON_PROPERTY_CHANGED, + WorkingTime.JSON_PROPERTY_NOTES, + WorkingTime.JSON_PROPERTY_USER, + WorkingTime.JSON_PROPERTY_WORKING_TIME_TYPE, + WorkingTime.JSON_PROPERTY_WORKING_TIME_DATE_SPAN, + WorkingTime.JSON_PROPERTY_START_LOCATION, + WorkingTime.JSON_PROPERTY_END_LOCATION, + WorkingTime.JSON_PROPERTY_START_PLATFORM, + WorkingTime.JSON_PROPERTY_END_PLATFORM, + WorkingTime.JSON_PROPERTY_LAST_MODIFIED, + WorkingTime.JSON_PROPERTY_LAST_MODIFIED_BY, + WorkingTime.JSON_PROPERTY_STATUS, + WorkingTime.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTime { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nonnull + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private OffsetDateTime end; + + public static final String JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES = "break_time_total_minutes"; + @jakarta.annotation.Nonnull + private Integer breakTimeTotalMinutes; + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + @jakarta.annotation.Nonnull + private List breakTimes; + + public static final String JSON_PROPERTY_DURATION = "duration"; + @jakarta.annotation.Nullable + private Duration duration; + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nonnull + private Boolean changed; + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private String notes; + + public static final String JSON_PROPERTY_USER = "user"; + @jakarta.annotation.Nonnull + private UserPartial user; + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE = "working_time_type"; + @jakarta.annotation.Nonnull + private WorkingTimeTypePartial workingTimeType; + + public static final String JSON_PROPERTY_WORKING_TIME_DATE_SPAN = "working_time_date_span"; + @jakarta.annotation.Nullable + private WorkingTimeDateSpanPartial workingTimeDateSpan; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + @jakarta.annotation.Nullable + private Location startLocation; + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + @jakarta.annotation.Nullable + private Location endLocation; + + public static final String JSON_PROPERTY_START_PLATFORM = "start_platform"; + @jakarta.annotation.Nullable + private Platform startPlatform; + + public static final String JSON_PROPERTY_END_PLATFORM = "end_platform"; + @jakarta.annotation.Nullable + private Platform endPlatform; + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + @jakarta.annotation.Nonnull + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + @jakarta.annotation.Nullable + private UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private WorkingTimeStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public WorkingTime() { + } + + public WorkingTime id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public WorkingTime start(@jakarta.annotation.Nonnull OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nonnull OffsetDateTime start) { + this.start = start; + } + + + public WorkingTime end(@jakarta.annotation.Nullable OffsetDateTime end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = end; + } + + + public WorkingTime breakTimeTotalMinutes(@jakarta.annotation.Nonnull Integer breakTimeTotalMinutes) { + + this.breakTimeTotalMinutes = breakTimeTotalMinutes; + return this; + } + + /** + * Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + * @return breakTimeTotalMinutes + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Integer getBreakTimeTotalMinutes() { + return breakTimeTotalMinutes; + } + + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIME_TOTAL_MINUTES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreakTimeTotalMinutes(@jakarta.annotation.Nonnull Integer breakTimeTotalMinutes) { + this.breakTimeTotalMinutes = breakTimeTotalMinutes; + } + + + public WorkingTime breakTimes(@jakarta.annotation.Nonnull List breakTimes) { + + this.breakTimes = breakTimes; + return this; + } + + public WorkingTime addBreakTimesItem(BreakTime breakTimesItem) { + if (this.breakTimes == null) { + this.breakTimes = new ArrayList<>(); + } + this.breakTimes.add(breakTimesItem); + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getBreakTimes() { + return breakTimes; + } + + + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setBreakTimes(@jakarta.annotation.Nonnull List breakTimes) { + this.breakTimes = breakTimes; + } + + + public WorkingTime duration(@jakarta.annotation.Nullable Duration duration) { + + this.duration = duration; + return this; + } + + /** + * Get duration + * @return duration + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Duration getDuration() { + return duration; + } + + + @JsonProperty(value = JSON_PROPERTY_DURATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDuration(@jakarta.annotation.Nullable Duration duration) { + this.duration = duration; + } + + + public WorkingTime changed(@jakarta.annotation.Nonnull Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(@jakarta.annotation.Nonnull Boolean changed) { + this.changed = changed; + } + + + public WorkingTime notes(@jakarta.annotation.Nullable String notes) { + + this.notes = notes; + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNotes() { + return notes; + } + + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNotes(@jakarta.annotation.Nullable String notes) { + this.notes = notes; + } + + + public WorkingTime user(@jakarta.annotation.Nonnull UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(@jakarta.annotation.Nonnull UserPartial user) { + this.user = user; + } + + + public WorkingTime workingTimeType(@jakarta.annotation.Nonnull WorkingTimeTypePartial workingTimeType) { + + this.workingTimeType = workingTimeType; + return this; + } + + /** + * Get workingTimeType + * @return workingTimeType + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeTypePartial getWorkingTimeType() { + return workingTimeType; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeType(@jakarta.annotation.Nonnull WorkingTimeTypePartial workingTimeType) { + this.workingTimeType = workingTimeType; + } + + + public WorkingTime workingTimeDateSpan(@jakarta.annotation.Nullable WorkingTimeDateSpanPartial workingTimeDateSpan) { + + this.workingTimeDateSpan = workingTimeDateSpan; + return this; + } + + /** + * Get workingTimeDateSpan + * @return workingTimeDateSpan + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_DATE_SPAN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeDateSpanPartial getWorkingTimeDateSpan() { + return workingTimeDateSpan; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_DATE_SPAN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeDateSpan(@jakarta.annotation.Nullable WorkingTimeDateSpanPartial workingTimeDateSpan) { + this.workingTimeDateSpan = workingTimeDateSpan; + } + + + public WorkingTime startLocation(@jakarta.annotation.Nullable Location startLocation) { + + this.startLocation = startLocation; + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Location getStartLocation() { + return startLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartLocation(@jakarta.annotation.Nullable Location startLocation) { + this.startLocation = startLocation; + } + + + public WorkingTime endLocation(@jakarta.annotation.Nullable Location endLocation) { + + this.endLocation = endLocation; + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Location getEndLocation() { + return endLocation; + } + + + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndLocation(@jakarta.annotation.Nullable Location endLocation) { + this.endLocation = endLocation; + } + + + public WorkingTime startPlatform(@jakarta.annotation.Nullable Platform startPlatform) { + + this.startPlatform = startPlatform; + return this; + } + + /** + * Get startPlatform + * @return startPlatform + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Platform getStartPlatform() { + return startPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_START_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartPlatform(@jakarta.annotation.Nullable Platform startPlatform) { + this.startPlatform = startPlatform; + } + + + public WorkingTime endPlatform(@jakarta.annotation.Nullable Platform endPlatform) { + + this.endPlatform = endPlatform; + return this; + } + + /** + * Get endPlatform + * @return endPlatform + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Platform getEndPlatform() { + return endPlatform; + } + + + @JsonProperty(value = JSON_PROPERTY_END_PLATFORM, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndPlatform(@jakarta.annotation.Nullable Platform endPlatform) { + this.endPlatform = endPlatform; + } + + + public WorkingTime lastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public WorkingTime lastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public WorkingTime status(@jakarta.annotation.Nonnull WorkingTimeStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull WorkingTimeStatus status) { + this.status = status; + } + + + public WorkingTime metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTime putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTime workingTime = (WorkingTime) o; + return Objects.equals(this.id, workingTime.id) && + Objects.equals(this.start, workingTime.start) && + Objects.equals(this.end, workingTime.end) && + Objects.equals(this.breakTimeTotalMinutes, workingTime.breakTimeTotalMinutes) && + Objects.equals(this.breakTimes, workingTime.breakTimes) && + Objects.equals(this.duration, workingTime.duration) && + Objects.equals(this.changed, workingTime.changed) && + Objects.equals(this.notes, workingTime.notes) && + Objects.equals(this.user, workingTime.user) && + Objects.equals(this.workingTimeType, workingTime.workingTimeType) && + Objects.equals(this.workingTimeDateSpan, workingTime.workingTimeDateSpan) && + Objects.equals(this.startLocation, workingTime.startLocation) && + Objects.equals(this.endLocation, workingTime.endLocation) && + Objects.equals(this.startPlatform, workingTime.startPlatform) && + Objects.equals(this.endPlatform, workingTime.endPlatform) && + Objects.equals(this.lastModified, workingTime.lastModified) && + Objects.equals(this.lastModifiedBy, workingTime.lastModifiedBy) && + Objects.equals(this.status, workingTime.status) && + equalsNullable(this.metadata, workingTime.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, start, end, breakTimeTotalMinutes, breakTimes, duration, changed, notes, user, workingTimeType, workingTimeDateSpan, startLocation, endLocation, startPlatform, endPlatform, lastModified, lastModifiedBy, status, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTime {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" workingTimeType: ").append(toIndentedString(workingTimeType)).append("\n"); + sb.append(" workingTimeDateSpan: ").append(toIndentedString(workingTimeDateSpan)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeCreate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeCreate.java new file mode 100644 index 0000000..a9baba8 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeCreate.java @@ -0,0 +1,498 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.DurationType; +import com.timr.api.models.LocationCreate; +import com.timr.api.models.WorkingTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeCreate + */ +@JsonPropertyOrder({ + WorkingTimeCreate.JSON_PROPERTY_START, + WorkingTimeCreate.JSON_PROPERTY_END, + WorkingTimeCreate.JSON_PROPERTY_BREAK_TIMES, + WorkingTimeCreate.JSON_PROPERTY_DURATION_TYPE, + WorkingTimeCreate.JSON_PROPERTY_CHANGED, + WorkingTimeCreate.JSON_PROPERTY_NOTES, + WorkingTimeCreate.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeCreate.JSON_PROPERTY_STATUS, + WorkingTimeCreate.JSON_PROPERTY_METADATA, + WorkingTimeCreate.JSON_PROPERTY_USER_ID, + WorkingTimeCreate.JSON_PROPERTY_START_LOCATION, + WorkingTimeCreate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeCreate { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nonnull + private OffsetDateTime start; + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + @jakarta.annotation.Nullable + private JsonNullable> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_DURATION_TYPE = "duration_type"; + @jakarta.annotation.Nullable + private JsonNullable durationType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nonnull + private Boolean changed; + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private JsonNullable notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + @jakarta.annotation.Nonnull + private String workingTimeTypeId; + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nonnull + private WorkingTimeStatus status; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_USER_ID = "user_id"; + @jakarta.annotation.Nonnull + private String userId; + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + @jakarta.annotation.Nullable + private JsonNullable startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + @jakarta.annotation.Nullable + private JsonNullable endLocation = JsonNullable.undefined(); + + public WorkingTimeCreate() { + } + + public WorkingTimeCreate start(@jakarta.annotation.Nonnull OffsetDateTime start) { + + this.start = start; + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nonnull OffsetDateTime start) { + this.start = start; + } + + + public WorkingTimeCreate end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public WorkingTimeCreate breakTimes(@jakarta.annotation.Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public WorkingTimeCreate addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public WorkingTimeCreate durationType(@jakarta.annotation.Nullable DurationType durationType) { + this.durationType = JsonNullable.of(durationType); + + return this; + } + + /** + * Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @return durationType + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DURATION_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDurationType() { + return durationType; + } + + @JsonProperty(JSON_PROPERTY_DURATION_TYPE) + public void setDurationType(JsonNullable durationType) { + this.durationType = durationType; + } + + + + public WorkingTimeCreate changed(@jakarta.annotation.Nonnull Boolean changed) { + + this.changed = changed; + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getChanged() { + return changed; + } + + + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setChanged(@jakarta.annotation.Nonnull Boolean changed) { + this.changed = changed; + } + + + public WorkingTimeCreate notes(@jakarta.annotation.Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeCreate workingTimeTypeId(@jakarta.annotation.Nonnull String workingTimeTypeId) { + + this.workingTimeTypeId = workingTimeTypeId; + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeTypeId(@jakarta.annotation.Nonnull String workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + public WorkingTimeCreate status(@jakarta.annotation.Nonnull WorkingTimeStatus status) { + + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeStatus getStatus() { + return status; + } + + + @JsonProperty(value = JSON_PROPERTY_STATUS, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStatus(@jakarta.annotation.Nonnull WorkingTimeStatus status) { + this.status = status; + } + + + public WorkingTimeCreate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public WorkingTimeCreate userId(@jakarta.annotation.Nonnull String userId) { + + this.userId = userId; + return this; + } + + /** + * Get userId + * @return userId + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getUserId() { + return userId; + } + + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUserId(@jakarta.annotation.Nonnull String userId) { + this.userId = userId; + } + + + public WorkingTimeCreate startLocation(@jakarta.annotation.Nullable LocationCreate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public WorkingTimeCreate endLocation(@jakarta.annotation.Nullable LocationCreate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeCreate workingTimeCreate = (WorkingTimeCreate) o; + return Objects.equals(this.start, workingTimeCreate.start) && + equalsNullable(this.end, workingTimeCreate.end) && + equalsNullable(this.breakTimes, workingTimeCreate.breakTimes) && + equalsNullable(this.durationType, workingTimeCreate.durationType) && + Objects.equals(this.changed, workingTimeCreate.changed) && + equalsNullable(this.notes, workingTimeCreate.notes) && + Objects.equals(this.workingTimeTypeId, workingTimeCreate.workingTimeTypeId) && + Objects.equals(this.status, workingTimeCreate.status) && + equalsNullable(this.metadata, workingTimeCreate.metadata) && + Objects.equals(this.userId, workingTimeCreate.userId) && + equalsNullable(this.startLocation, workingTimeCreate.startLocation) && + equalsNullable(this.endLocation, workingTimeCreate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(durationType), changed, hashCodeNullable(notes), workingTimeTypeId, status, hashCodeNullable(metadata), userId, hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeCreate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" durationType: ").append(toIndentedString(durationType)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpan.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpan.java new file mode 100644 index 0000000..7eaccff --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpan.java @@ -0,0 +1,492 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.UserPartial; +import com.timr.api.models.WorkingTimeTypePartial; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A span from `start` to `end` of a single `working_time_type`. Every working time derived for a covered day links back to it via `WorkingTime.working_time_date_span`. It can be created directly or become effective through an approved request. + */ +@JsonPropertyOrder({ + WorkingTimeDateSpan.JSON_PROPERTY_ID, + WorkingTimeDateSpan.JSON_PROPERTY_START, + WorkingTimeDateSpan.JSON_PROPERTY_START_HALF_DAY, + WorkingTimeDateSpan.JSON_PROPERTY_END, + WorkingTimeDateSpan.JSON_PROPERTY_END_HALF_DAY, + WorkingTimeDateSpan.JSON_PROPERTY_NOTES, + WorkingTimeDateSpan.JSON_PROPERTY_USER, + WorkingTimeDateSpan.JSON_PROPERTY_WORKING_TIME_TYPE, + WorkingTimeDateSpan.JSON_PROPERTY_SUBSTITUTE, + WorkingTimeDateSpan.JSON_PROPERTY_LAST_MODIFIED, + WorkingTimeDateSpan.JSON_PROPERTY_LAST_MODIFIED_BY, + WorkingTimeDateSpan.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpan { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nonnull + private LocalDate start; + + public static final String JSON_PROPERTY_START_HALF_DAY = "start_half_day"; + @jakarta.annotation.Nonnull + private Boolean startHalfDay; + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nonnull + private LocalDate end; + + public static final String JSON_PROPERTY_END_HALF_DAY = "end_half_day"; + @jakarta.annotation.Nonnull + private Boolean endHalfDay; + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private String notes; + + public static final String JSON_PROPERTY_USER = "user"; + @jakarta.annotation.Nonnull + private UserPartial user; + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE = "working_time_type"; + @jakarta.annotation.Nonnull + private WorkingTimeTypePartial workingTimeType; + + public static final String JSON_PROPERTY_SUBSTITUTE = "substitute"; + @jakarta.annotation.Nullable + private JsonNullable substitute = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_LAST_MODIFIED = "last_modified"; + @jakarta.annotation.Nonnull + private OffsetDateTime lastModified; + + public static final String JSON_PROPERTY_LAST_MODIFIED_BY = "last_modified_by"; + @jakarta.annotation.Nullable + private UserPartial lastModifiedBy; + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public WorkingTimeDateSpan() { + } + + public WorkingTimeDateSpan id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public WorkingTimeDateSpan start(@jakarta.annotation.Nonnull LocalDate start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return start + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nonnull LocalDate start) { + this.start = start; + } + + + public WorkingTimeDateSpan startHalfDay(@jakarta.annotation.Nonnull Boolean startHalfDay) { + + this.startHalfDay = startHalfDay; + return this; + } + + /** + * Marks the first day of the working time date span as a half day. + * @return startHalfDay + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getStartHalfDay() { + return startHalfDay; + } + + + @JsonProperty(value = JSON_PROPERTY_START_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStartHalfDay(@jakarta.annotation.Nonnull Boolean startHalfDay) { + this.startHalfDay = startHalfDay; + } + + + public WorkingTimeDateSpan end(@jakarta.annotation.Nonnull LocalDate end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return end + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_END, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@jakarta.annotation.Nonnull LocalDate end) { + this.end = end; + } + + + public WorkingTimeDateSpan endHalfDay(@jakarta.annotation.Nonnull Boolean endHalfDay) { + + this.endHalfDay = endHalfDay; + return this; + } + + /** + * Marks the last day of the working time date span as a half day. + * @return endHalfDay + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_END_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getEndHalfDay() { + return endHalfDay; + } + + + @JsonProperty(value = JSON_PROPERTY_END_HALF_DAY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEndHalfDay(@jakarta.annotation.Nonnull Boolean endHalfDay) { + this.endHalfDay = endHalfDay; + } + + + public WorkingTimeDateSpan notes(@jakarta.annotation.Nullable String notes) { + + this.notes = notes; + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNotes() { + return notes; + } + + + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNotes(@jakarta.annotation.Nullable String notes) { + this.notes = notes; + } + + + public WorkingTimeDateSpan user(@jakarta.annotation.Nonnull UserPartial user) { + + this.user = user; + return this; + } + + /** + * Get user + * @return user + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getUser() { + return user; + } + + + @JsonProperty(value = JSON_PROPERTY_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUser(@jakarta.annotation.Nonnull UserPartial user) { + this.user = user; + } + + + public WorkingTimeDateSpan workingTimeType(@jakarta.annotation.Nonnull WorkingTimeTypePartial workingTimeType) { + + this.workingTimeType = workingTimeType; + return this; + } + + /** + * Get workingTimeType + * @return workingTimeType + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeTypePartial getWorkingTimeType() { + return workingTimeType; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeType(@jakarta.annotation.Nonnull WorkingTimeTypePartial workingTimeType) { + this.workingTimeType = workingTimeType; + } + + + public WorkingTimeDateSpan substitute(@jakarta.annotation.Nullable UserPartial substitute) { + this.substitute = JsonNullable.of(substitute); + + return this; + } + + /** + * Get substitute + * @return substitute + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_SUBSTITUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getSubstitute() { + return substitute; + } + + @JsonProperty(JSON_PROPERTY_SUBSTITUTE) + public void setSubstitute(JsonNullable substitute) { + this.substitute = substitute; + } + + + + public WorkingTimeDateSpan lastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + + this.lastModified = lastModified; + return this; + } + + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @return lastModified + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public OffsetDateTime getLastModified() { + return lastModified; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModified(@jakarta.annotation.Nonnull OffsetDateTime lastModified) { + this.lastModified = lastModified; + } + + + public WorkingTimeDateSpan lastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + + this.lastModifiedBy = lastModifiedBy; + return this; + } + + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @return lastModifiedBy + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public UserPartial getLastModifiedBy() { + return lastModifiedBy; + } + + + @JsonProperty(value = JSON_PROPERTY_LAST_MODIFIED_BY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setLastModifiedBy(@jakarta.annotation.Nullable UserPartial lastModifiedBy) { + this.lastModifiedBy = lastModifiedBy; + } + + + public WorkingTimeDateSpan metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeDateSpan putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpan workingTimeDateSpan = (WorkingTimeDateSpan) o; + return Objects.equals(this.id, workingTimeDateSpan.id) && + Objects.equals(this.start, workingTimeDateSpan.start) && + Objects.equals(this.startHalfDay, workingTimeDateSpan.startHalfDay) && + Objects.equals(this.end, workingTimeDateSpan.end) && + Objects.equals(this.endHalfDay, workingTimeDateSpan.endHalfDay) && + Objects.equals(this.notes, workingTimeDateSpan.notes) && + Objects.equals(this.user, workingTimeDateSpan.user) && + Objects.equals(this.workingTimeType, workingTimeDateSpan.workingTimeType) && + equalsNullable(this.substitute, workingTimeDateSpan.substitute) && + Objects.equals(this.lastModified, workingTimeDateSpan.lastModified) && + Objects.equals(this.lastModifiedBy, workingTimeDateSpan.lastModifiedBy) && + equalsNullable(this.metadata, workingTimeDateSpan.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, start, startHalfDay, end, endHalfDay, notes, user, workingTimeType, hashCodeNullable(substitute), lastModified, lastModifiedBy, hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpan {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" user: ").append(toIndentedString(user)).append("\n"); + sb.append(" workingTimeType: ").append(toIndentedString(workingTimeType)).append("\n"); + sb.append(" substitute: ").append(toIndentedString(substitute)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanCreate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanCreate.java new file mode 100644 index 0000000..18b4584 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanCreate.java @@ -0,0 +1,386 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeDateSpanCreate + */ +@JsonPropertyOrder({ + WorkingTimeDateSpanCreate.JSON_PROPERTY_START, + WorkingTimeDateSpanCreate.JSON_PROPERTY_START_HALF_DAY, + WorkingTimeDateSpanCreate.JSON_PROPERTY_END, + WorkingTimeDateSpanCreate.JSON_PROPERTY_END_HALF_DAY, + WorkingTimeDateSpanCreate.JSON_PROPERTY_NOTES, + WorkingTimeDateSpanCreate.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeDateSpanCreate.JSON_PROPERTY_SUBSTITUTE_ID, + WorkingTimeDateSpanCreate.JSON_PROPERTY_METADATA, + WorkingTimeDateSpanCreate.JSON_PROPERTY_USER_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpanCreate { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nonnull + private LocalDate start; + + public static final String JSON_PROPERTY_START_HALF_DAY = "start_half_day"; + @jakarta.annotation.Nullable + private JsonNullable startHalfDay = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nonnull + private LocalDate end; + + public static final String JSON_PROPERTY_END_HALF_DAY = "end_half_day"; + @jakarta.annotation.Nullable + private JsonNullable endHalfDay = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private JsonNullable notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + @jakarta.annotation.Nonnull + private String workingTimeTypeId; + + public static final String JSON_PROPERTY_SUBSTITUTE_ID = "substitute_id"; + @jakarta.annotation.Nullable + private JsonNullable substituteId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_USER_ID = "user_id"; + @jakarta.annotation.Nonnull + private String userId; + + public WorkingTimeDateSpanCreate() { + } + + public WorkingTimeDateSpanCreate start(@jakarta.annotation.Nonnull LocalDate start) { + + this.start = start; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return start + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getStart() { + return start; + } + + + @JsonProperty(value = JSON_PROPERTY_START, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setStart(@jakarta.annotation.Nonnull LocalDate start) { + this.start = start; + } + + + public WorkingTimeDateSpanCreate startHalfDay(@jakarta.annotation.Nullable Boolean startHalfDay) { + this.startHalfDay = JsonNullable.of(startHalfDay); + + return this; + } + + /** + * Get startHalfDay + * @return startHalfDay + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_HALF_DAY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartHalfDay() { + return startHalfDay; + } + + @JsonProperty(JSON_PROPERTY_START_HALF_DAY) + public void setStartHalfDay(JsonNullable startHalfDay) { + this.startHalfDay = startHalfDay; + } + + + + public WorkingTimeDateSpanCreate end(@jakarta.annotation.Nonnull LocalDate end) { + + this.end = end; + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return end + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_END, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public LocalDate getEnd() { + return end; + } + + + @JsonProperty(value = JSON_PROPERTY_END, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEnd(@jakarta.annotation.Nonnull LocalDate end) { + this.end = end; + } + + + public WorkingTimeDateSpanCreate endHalfDay(@jakarta.annotation.Nullable Boolean endHalfDay) { + this.endHalfDay = JsonNullable.of(endHalfDay); + + return this; + } + + /** + * Get endHalfDay + * @return endHalfDay + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_HALF_DAY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndHalfDay() { + return endHalfDay; + } + + @JsonProperty(JSON_PROPERTY_END_HALF_DAY) + public void setEndHalfDay(JsonNullable endHalfDay) { + this.endHalfDay = endHalfDay; + } + + + + public WorkingTimeDateSpanCreate notes(@jakarta.annotation.Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeDateSpanCreate workingTimeTypeId(@jakarta.annotation.Nonnull String workingTimeTypeId) { + + this.workingTimeTypeId = workingTimeTypeId; + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setWorkingTimeTypeId(@jakarta.annotation.Nonnull String workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + public WorkingTimeDateSpanCreate substituteId(@jakarta.annotation.Nullable String substituteId) { + this.substituteId = JsonNullable.of(substituteId); + + return this; + } + + /** + * Get substituteId + * @return substituteId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_SUBSTITUTE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getSubstituteId() { + return substituteId; + } + + @JsonProperty(JSON_PROPERTY_SUBSTITUTE_ID) + public void setSubstituteId(JsonNullable substituteId) { + this.substituteId = substituteId; + } + + + + public WorkingTimeDateSpanCreate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeDateSpanCreate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public WorkingTimeDateSpanCreate userId(@jakarta.annotation.Nonnull String userId) { + + this.userId = userId; + return this; + } + + /** + * Get userId + * @return userId + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getUserId() { + return userId; + } + + + @JsonProperty(value = JSON_PROPERTY_USER_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setUserId(@jakarta.annotation.Nonnull String userId) { + this.userId = userId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpanCreate workingTimeDateSpanCreate = (WorkingTimeDateSpanCreate) o; + return Objects.equals(this.start, workingTimeDateSpanCreate.start) && + equalsNullable(this.startHalfDay, workingTimeDateSpanCreate.startHalfDay) && + Objects.equals(this.end, workingTimeDateSpanCreate.end) && + equalsNullable(this.endHalfDay, workingTimeDateSpanCreate.endHalfDay) && + equalsNullable(this.notes, workingTimeDateSpanCreate.notes) && + Objects.equals(this.workingTimeTypeId, workingTimeDateSpanCreate.workingTimeTypeId) && + equalsNullable(this.substituteId, workingTimeDateSpanCreate.substituteId) && + equalsNullable(this.metadata, workingTimeDateSpanCreate.metadata) && + Objects.equals(this.userId, workingTimeDateSpanCreate.userId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(start, hashCodeNullable(startHalfDay), end, hashCodeNullable(endHalfDay), hashCodeNullable(notes), workingTimeTypeId, hashCodeNullable(substituteId), hashCodeNullable(metadata), userId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpanCreate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" substituteId: ").append(toIndentedString(substituteId)).append("\n"); + sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanPage.java new file mode 100644 index 0000000..a282b7d --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkingTimeDateSpan; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeDateSpanPage + */ +@JsonPropertyOrder({ + WorkingTimeDateSpanPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + WorkingTimeDateSpanPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpanPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public WorkingTimeDateSpanPage() { + } + + public WorkingTimeDateSpanPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public WorkingTimeDateSpanPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public WorkingTimeDateSpanPage addDataItem(WorkingTimeDateSpan dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpanPage workingTimeDateSpanPage = (WorkingTimeDateSpanPage) o; + return Objects.equals(this.nextPageToken, workingTimeDateSpanPage.nextPageToken) && + Objects.equals(this.data, workingTimeDateSpanPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpanPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanPartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanPartial.java new file mode 100644 index 0000000..84c593f --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanPartial.java @@ -0,0 +1,117 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * References the date span this working time belongs to, if any. All working times generated for a date span reference the same span; working times recorded on their own have none. + */ +@JsonPropertyOrder({ + WorkingTimeDateSpanPartial.JSON_PROPERTY_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpanPartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public WorkingTimeDateSpanPartial() { + } + + public WorkingTimeDateSpanPartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpanPartial workingTimeDateSpanPartial = (WorkingTimeDateSpanPartial) o; + return Objects.equals(this.id, workingTimeDateSpanPartial.id); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpanPartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanUpdate.java new file mode 100644 index 0000000..68e6667 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpanUpdate.java @@ -0,0 +1,347 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeDateSpanUpdate + */ +@JsonPropertyOrder({ + WorkingTimeDateSpanUpdate.JSON_PROPERTY_START, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_START_HALF_DAY, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_END, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_END_HALF_DAY, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_NOTES, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_SUBSTITUTE_ID, + WorkingTimeDateSpanUpdate.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeDateSpanUpdate { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private JsonNullable start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_START_HALF_DAY = "start_half_day"; + @jakarta.annotation.Nullable + private JsonNullable startHalfDay = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_HALF_DAY = "end_half_day"; + @jakarta.annotation.Nullable + private JsonNullable endHalfDay = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private JsonNullable notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + @jakarta.annotation.Nullable + private JsonNullable workingTimeTypeId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_SUBSTITUTE_ID = "substitute_id"; + @jakarta.annotation.Nullable + private JsonNullable substituteId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public WorkingTimeDateSpanUpdate() { + } + + public WorkingTimeDateSpanUpdate start(@jakarta.annotation.Nullable LocalDate start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public WorkingTimeDateSpanUpdate startHalfDay(@jakarta.annotation.Nullable Boolean startHalfDay) { + this.startHalfDay = JsonNullable.of(startHalfDay); + + return this; + } + + /** + * Get startHalfDay + * @return startHalfDay + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_HALF_DAY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartHalfDay() { + return startHalfDay; + } + + @JsonProperty(JSON_PROPERTY_START_HALF_DAY) + public void setStartHalfDay(JsonNullable startHalfDay) { + this.startHalfDay = startHalfDay; + } + + + + public WorkingTimeDateSpanUpdate end(@jakarta.annotation.Nullable LocalDate end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * RFC 3339 date (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public WorkingTimeDateSpanUpdate endHalfDay(@jakarta.annotation.Nullable Boolean endHalfDay) { + this.endHalfDay = JsonNullable.of(endHalfDay); + + return this; + } + + /** + * Get endHalfDay + * @return endHalfDay + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_HALF_DAY, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndHalfDay() { + return endHalfDay; + } + + @JsonProperty(JSON_PROPERTY_END_HALF_DAY) + public void setEndHalfDay(JsonNullable endHalfDay) { + this.endHalfDay = endHalfDay; + } + + + + public WorkingTimeDateSpanUpdate notes(@jakarta.annotation.Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeDateSpanUpdate workingTimeTypeId(@jakarta.annotation.Nullable String workingTimeTypeId) { + this.workingTimeTypeId = JsonNullable.of(workingTimeTypeId); + + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + @JsonProperty(JSON_PROPERTY_WORKING_TIME_TYPE_ID) + public void setWorkingTimeTypeId(JsonNullable workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + + public WorkingTimeDateSpanUpdate substituteId(@jakarta.annotation.Nullable String substituteId) { + this.substituteId = JsonNullable.of(substituteId); + + return this; + } + + /** + * Get substituteId + * @return substituteId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_SUBSTITUTE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getSubstituteId() { + return substituteId; + } + + @JsonProperty(JSON_PROPERTY_SUBSTITUTE_ID) + public void setSubstituteId(JsonNullable substituteId) { + this.substituteId = substituteId; + } + + + + public WorkingTimeDateSpanUpdate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeDateSpanUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeDateSpanUpdate workingTimeDateSpanUpdate = (WorkingTimeDateSpanUpdate) o; + return equalsNullable(this.start, workingTimeDateSpanUpdate.start) && + equalsNullable(this.startHalfDay, workingTimeDateSpanUpdate.startHalfDay) && + equalsNullable(this.end, workingTimeDateSpanUpdate.end) && + equalsNullable(this.endHalfDay, workingTimeDateSpanUpdate.endHalfDay) && + equalsNullable(this.notes, workingTimeDateSpanUpdate.notes) && + equalsNullable(this.workingTimeTypeId, workingTimeDateSpanUpdate.workingTimeTypeId) && + equalsNullable(this.substituteId, workingTimeDateSpanUpdate.substituteId) && + equalsNullable(this.metadata, workingTimeDateSpanUpdate.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(startHalfDay), hashCodeNullable(end), hashCodeNullable(endHalfDay), hashCodeNullable(notes), hashCodeNullable(workingTimeTypeId), hashCodeNullable(substituteId), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeDateSpanUpdate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" substituteId: ").append(toIndentedString(substituteId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpansSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpansSortColumn.java new file mode 100644 index 0000000..0fe0248 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeDateSpansSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Working Time Date Spans. + */ +public enum WorkingTimeDateSpansSortColumn { + + START("start"); + + private String value; + + WorkingTimeDateSpansSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeDateSpansSortColumn fromValue(String value) { + for (WorkingTimeDateSpansSortColumn b : WorkingTimeDateSpansSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeRules.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeRules.java new file mode 100644 index 0000000..d25aded --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeRules.java @@ -0,0 +1,149 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeRules + */ +@JsonPropertyOrder({ + WorkingTimeRules.JSON_PROPERTY_ID, + WorkingTimeRules.JSON_PROPERTY_NAME +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeRules { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public WorkingTimeRules() { + } + + public WorkingTimeRules id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public WorkingTimeRules name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeRules workingTimeRules = (WorkingTimeRules) o; + return Objects.equals(this.id, workingTimeRules.id) && + Objects.equals(this.name, workingTimeRules.name); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeRules {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeStatus.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeStatus.java new file mode 100644 index 0000000..7c0cfad --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeStatus.java @@ -0,0 +1,70 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Processing state of a Working Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, closed and archived. + */ +public enum WorkingTimeStatus { + + RUNNING("running"), + + PAUSED("paused"), + + CHANGEABLE("changeable"), + + LOCKED("locked"), + + APPROVED("approved"), + + CLOSED("closed"), + + ARCHIVED("archived"); + + private String value; + + WorkingTimeStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeStatus fromValue(String value) { + for (WorkingTimeStatus b : WorkingTimeStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeType.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeType.java new file mode 100644 index 0000000..db5e2a2 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeType.java @@ -0,0 +1,445 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.DurationUnit; +import com.timr.api.models.RecordingModeUser; +import com.timr.api.models.WorkingTimeTypeCategory; +import com.timr.api.models.WorkingTimeTypeSubCategory; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * A working time type. `category` and `sub_category` place it in the classification, `edit_unit` decides whether it is recorded by time or by day, and `requires_substitute` governs how it is recorded. + */ +@JsonPropertyOrder({ + WorkingTimeType.JSON_PROPERTY_ID, + WorkingTimeType.JSON_PROPERTY_NAME, + WorkingTimeType.JSON_PROPERTY_SHORT_NAME, + WorkingTimeType.JSON_PROPERTY_DESCRIPTION, + WorkingTimeType.JSON_PROPERTY_EXTERNAL_ID, + WorkingTimeType.JSON_PROPERTY_EDIT_UNIT, + WorkingTimeType.JSON_PROPERTY_CATEGORY, + WorkingTimeType.JSON_PROPERTY_SUB_CATEGORY, + WorkingTimeType.JSON_PROPERTY_RECORDING_MODE_USER, + WorkingTimeType.JSON_PROPERTY_ARCHIVED, + WorkingTimeType.JSON_PROPERTY_REQUIRES_SUBSTITUTE +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeType { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_SHORT_NAME = "short_name"; + @jakarta.annotation.Nullable + private String shortName; + + public static final String JSON_PROPERTY_DESCRIPTION = "description"; + @jakarta.annotation.Nullable + private String description; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public static final String JSON_PROPERTY_EDIT_UNIT = "edit_unit"; + @jakarta.annotation.Nonnull + private DurationUnit editUnit; + + public static final String JSON_PROPERTY_CATEGORY = "category"; + @jakarta.annotation.Nonnull + private WorkingTimeTypeCategory category; + + public static final String JSON_PROPERTY_SUB_CATEGORY = "sub_category"; + @jakarta.annotation.Nullable + private WorkingTimeTypeSubCategory subCategory; + + public static final String JSON_PROPERTY_RECORDING_MODE_USER = "recording_mode_user"; + @jakarta.annotation.Nonnull + private RecordingModeUser recordingModeUser; + + public static final String JSON_PROPERTY_ARCHIVED = "archived"; + @jakarta.annotation.Nonnull + private Boolean archived; + + public static final String JSON_PROPERTY_REQUIRES_SUBSTITUTE = "requires_substitute"; + @jakarta.annotation.Nullable + private JsonNullable requiresSubstitute = JsonNullable.undefined(); + + public WorkingTimeType() { + } + + public WorkingTimeType id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public WorkingTimeType name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public WorkingTimeType shortName(@jakarta.annotation.Nullable String shortName) { + + this.shortName = shortName; + return this; + } + + /** + * Get shortName + * @return shortName + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_SHORT_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getShortName() { + return shortName; + } + + + @JsonProperty(value = JSON_PROPERTY_SHORT_NAME, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setShortName(@jakarta.annotation.Nullable String shortName) { + this.shortName = shortName; + } + + + public WorkingTimeType description(@jakarta.annotation.Nullable String description) { + + this.description = description; + return this; + } + + /** + * Get description + * @return description + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getDescription() { + return description; + } + + + @JsonProperty(value = JSON_PROPERTY_DESCRIPTION, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setDescription(@jakarta.annotation.Nullable String description) { + this.description = description; + } + + + public WorkingTimeType externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + public WorkingTimeType editUnit(@jakarta.annotation.Nonnull DurationUnit editUnit) { + + this.editUnit = editUnit; + return this; + } + + /** + * Get editUnit + * @return editUnit + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_EDIT_UNIT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public DurationUnit getEditUnit() { + return editUnit; + } + + + @JsonProperty(value = JSON_PROPERTY_EDIT_UNIT, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setEditUnit(@jakarta.annotation.Nonnull DurationUnit editUnit) { + this.editUnit = editUnit; + } + + + public WorkingTimeType category(@jakarta.annotation.Nonnull WorkingTimeTypeCategory category) { + + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_CATEGORY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeTypeCategory getCategory() { + return category; + } + + + @JsonProperty(value = JSON_PROPERTY_CATEGORY, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setCategory(@jakarta.annotation.Nonnull WorkingTimeTypeCategory category) { + this.category = category; + } + + + public WorkingTimeType subCategory(@jakarta.annotation.Nullable WorkingTimeTypeSubCategory subCategory) { + + this.subCategory = subCategory; + return this; + } + + /** + * Get subCategory + * @return subCategory + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_SUB_CATEGORY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public WorkingTimeTypeSubCategory getSubCategory() { + return subCategory; + } + + + @JsonProperty(value = JSON_PROPERTY_SUB_CATEGORY, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setSubCategory(@jakarta.annotation.Nullable WorkingTimeTypeSubCategory subCategory) { + this.subCategory = subCategory; + } + + + public WorkingTimeType recordingModeUser(@jakarta.annotation.Nonnull RecordingModeUser recordingModeUser) { + + this.recordingModeUser = recordingModeUser; + return this; + } + + /** + * Specifies how the user can record this working time type. + * @return recordingModeUser + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_RECORDING_MODE_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public RecordingModeUser getRecordingModeUser() { + return recordingModeUser; + } + + + @JsonProperty(value = JSON_PROPERTY_RECORDING_MODE_USER, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setRecordingModeUser(@jakarta.annotation.Nonnull RecordingModeUser recordingModeUser) { + this.recordingModeUser = recordingModeUser; + } + + + public WorkingTimeType archived(@jakarta.annotation.Nonnull Boolean archived) { + + this.archived = archived; + return this; + } + + /** + * Get archived + * @return archived + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ARCHIVED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public Boolean getArchived() { + return archived; + } + + + @JsonProperty(value = JSON_PROPERTY_ARCHIVED, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setArchived(@jakarta.annotation.Nonnull Boolean archived) { + this.archived = archived; + } + + + public WorkingTimeType requiresSubstitute(@jakarta.annotation.Nullable Boolean requiresSubstitute) { + this.requiresSubstitute = JsonNullable.of(requiresSubstitute); + + return this; + } + + /** + * Get requiresSubstitute + * @return requiresSubstitute + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_REQUIRES_SUBSTITUTE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getRequiresSubstitute() { + return requiresSubstitute; + } + + @JsonProperty(JSON_PROPERTY_REQUIRES_SUBSTITUTE) + public void setRequiresSubstitute(JsonNullable requiresSubstitute) { + this.requiresSubstitute = requiresSubstitute; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeType workingTimeType = (WorkingTimeType) o; + return Objects.equals(this.id, workingTimeType.id) && + Objects.equals(this.name, workingTimeType.name) && + Objects.equals(this.shortName, workingTimeType.shortName) && + Objects.equals(this.description, workingTimeType.description) && + Objects.equals(this.externalId, workingTimeType.externalId) && + Objects.equals(this.editUnit, workingTimeType.editUnit) && + Objects.equals(this.category, workingTimeType.category) && + Objects.equals(this.subCategory, workingTimeType.subCategory) && + Objects.equals(this.recordingModeUser, workingTimeType.recordingModeUser) && + Objects.equals(this.archived, workingTimeType.archived) && + equalsNullable(this.requiresSubstitute, workingTimeType.requiresSubstitute); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, shortName, description, externalId, editUnit, category, subCategory, recordingModeUser, archived, hashCodeNullable(requiresSubstitute)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeType {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" editUnit: ").append(toIndentedString(editUnit)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" subCategory: ").append(toIndentedString(subCategory)).append("\n"); + sb.append(" recordingModeUser: ").append(toIndentedString(recordingModeUser)).append("\n"); + sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); + sb.append(" requiresSubstitute: ").append(toIndentedString(requiresSubstitute)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypeCategory.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypeCategory.java new file mode 100644 index 0000000..b0a27f4 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypeCategory.java @@ -0,0 +1,68 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Category of a Working Time Type. `attendance_time` counts as time at work, the remaining categories describe kinds of absence. + */ +public enum WorkingTimeTypeCategory { + + ATTENDANCE_TIME("attendance_time"), + + VACATION("vacation"), + + PAID_TIME_OFF("paid_time_off"), + + UNPAID_TIME_OFF("unpaid_time_off"), + + SUSPENSION("suspension"), + + BREAK_TIME("break_time"); + + private String value; + + WorkingTimeTypeCategory(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeTypeCategory fromValue(String value) { + for (WorkingTimeTypeCategory b : WorkingTimeTypeCategory.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypePartial.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypePartial.java new file mode 100644 index 0000000..e6a4d66 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypePartial.java @@ -0,0 +1,181 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeTypePartial + */ +@JsonPropertyOrder({ + WorkingTimeTypePartial.JSON_PROPERTY_ID, + WorkingTimeTypePartial.JSON_PROPERTY_NAME, + WorkingTimeTypePartial.JSON_PROPERTY_EXTERNAL_ID +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeTypePartial { + public static final String JSON_PROPERTY_ID = "id"; + @jakarta.annotation.Nonnull + private String id; + + public static final String JSON_PROPERTY_NAME = "name"; + @jakarta.annotation.Nonnull + private String name; + + public static final String JSON_PROPERTY_EXTERNAL_ID = "external_id"; + @jakarta.annotation.Nullable + private String externalId; + + public WorkingTimeTypePartial() { + } + + public WorkingTimeTypePartial id(@jakarta.annotation.Nonnull String id) { + + this.id = id; + return this; + } + + /** + * Unique identifier. Treat it as an opaque string. + * @return id + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getId() { + return id; + } + + + @JsonProperty(value = JSON_PROPERTY_ID, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setId(@jakarta.annotation.Nonnull String id) { + this.id = id; + } + + + public WorkingTimeTypePartial name(@jakarta.annotation.Nonnull String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(value = JSON_PROPERTY_NAME, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(@jakarta.annotation.Nonnull String name) { + this.name = name; + } + + + public WorkingTimeTypePartial externalId(@jakarta.annotation.Nullable String externalId) { + + this.externalId = externalId; + return this; + } + + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @return externalId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getExternalId() { + return externalId; + } + + + @JsonProperty(value = JSON_PROPERTY_EXTERNAL_ID, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setExternalId(@jakarta.annotation.Nullable String externalId) { + this.externalId = externalId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeTypePartial workingTimeTypePartial = (WorkingTimeTypePartial) o; + return Objects.equals(this.id, workingTimeTypePartial.id) && + Objects.equals(this.name, workingTimeTypePartial.name) && + Objects.equals(this.externalId, workingTimeTypePartial.externalId); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, externalId); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeTypePartial {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypeSubCategory.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypeSubCategory.java new file mode 100644 index 0000000..396794c --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypeSubCategory.java @@ -0,0 +1,66 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Further classification of a Working Time Type within its category. + */ +public enum WorkingTimeTypeSubCategory { + + PRESENT("present"), + + WORK_FROM_HOME("work_from_home"), + + AWAY("away"), + + ACTIVE_DRIVING_TIME("active_driving_time"), + + PASSIVE_TRAVELLING_TIME("passive_travelling_time"); + + private String value; + + WorkingTimeTypeSubCategory(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeTypeSubCategory fromValue(String value) { + for (WorkingTimeTypeSubCategory b : WorkingTimeTypeSubCategory.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypesPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypesPage.java new file mode 100644 index 0000000..71b9e3e --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypesPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkingTimeType; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeTypesPage + */ +@JsonPropertyOrder({ + WorkingTimeTypesPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + WorkingTimeTypesPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeTypesPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public WorkingTimeTypesPage() { + } + + public WorkingTimeTypesPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public WorkingTimeTypesPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public WorkingTimeTypesPage addDataItem(WorkingTimeType dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeTypesPage workingTimeTypesPage = (WorkingTimeTypesPage) o; + return Objects.equals(this.nextPageToken, workingTimeTypesPage.nextPageToken) && + Objects.equals(this.data, workingTimeTypesPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeTypesPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypesSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypesSortColumn.java new file mode 100644 index 0000000..28a71e1 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeTypesSortColumn.java @@ -0,0 +1,58 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Working Time Types. + */ +public enum WorkingTimeTypesSortColumn { + + NAME("name"); + + private String value; + + WorkingTimeTypesSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimeTypesSortColumn fromValue(String value) { + for (WorkingTimeTypesSortColumn b : WorkingTimeTypesSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeUpdate.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeUpdate.java new file mode 100644 index 0000000..57a0ee7 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeUpdate.java @@ -0,0 +1,457 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.DurationType; +import com.timr.api.models.LocationUpdate; +import com.timr.api.models.WorkingTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeUpdate + */ +@JsonPropertyOrder({ + WorkingTimeUpdate.JSON_PROPERTY_START, + WorkingTimeUpdate.JSON_PROPERTY_END, + WorkingTimeUpdate.JSON_PROPERTY_BREAK_TIMES, + WorkingTimeUpdate.JSON_PROPERTY_DURATION_TYPE, + WorkingTimeUpdate.JSON_PROPERTY_CHANGED, + WorkingTimeUpdate.JSON_PROPERTY_NOTES, + WorkingTimeUpdate.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeUpdate.JSON_PROPERTY_STATUS, + WorkingTimeUpdate.JSON_PROPERTY_METADATA, + WorkingTimeUpdate.JSON_PROPERTY_START_LOCATION, + WorkingTimeUpdate.JSON_PROPERTY_END_LOCATION +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeUpdate { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private JsonNullable start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + @jakarta.annotation.Nullable + private JsonNullable> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_DURATION_TYPE = "duration_type"; + @jakarta.annotation.Nullable + private JsonNullable durationType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nullable + private JsonNullable changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private JsonNullable notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + @jakarta.annotation.Nullable + private JsonNullable workingTimeTypeId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nullable + private JsonNullable status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_START_LOCATION = "start_location"; + @jakarta.annotation.Nullable + private JsonNullable startLocation = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END_LOCATION = "end_location"; + @jakarta.annotation.Nullable + private JsonNullable endLocation = JsonNullable.undefined(); + + public WorkingTimeUpdate() { + } + + public WorkingTimeUpdate start(@jakarta.annotation.Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public WorkingTimeUpdate end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public WorkingTimeUpdate breakTimes(@jakarta.annotation.Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public WorkingTimeUpdate addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public WorkingTimeUpdate durationType(@jakarta.annotation.Nullable DurationType durationType) { + this.durationType = JsonNullable.of(durationType); + + return this; + } + + /** + * Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @return durationType + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DURATION_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDurationType() { + return durationType; + } + + @JsonProperty(JSON_PROPERTY_DURATION_TYPE) + public void setDurationType(JsonNullable durationType) { + this.durationType = durationType; + } + + + + public WorkingTimeUpdate changed(@jakarta.annotation.Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public WorkingTimeUpdate notes(@jakarta.annotation.Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeUpdate workingTimeTypeId(@jakarta.annotation.Nullable String workingTimeTypeId) { + this.workingTimeTypeId = JsonNullable.of(workingTimeTypeId); + + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + @JsonProperty(JSON_PROPERTY_WORKING_TIME_TYPE_ID) + public void setWorkingTimeTypeId(JsonNullable workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + + public WorkingTimeUpdate status(@jakarta.annotation.Nullable WorkingTimeStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public WorkingTimeUpdate metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeUpdate putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + public WorkingTimeUpdate startLocation(@jakarta.annotation.Nullable LocationUpdate startLocation) { + this.startLocation = JsonNullable.of(startLocation); + + return this; + } + + /** + * Get startLocation + * @return startLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStartLocation() { + return startLocation; + } + + @JsonProperty(JSON_PROPERTY_START_LOCATION) + public void setStartLocation(JsonNullable startLocation) { + this.startLocation = startLocation; + } + + + + public WorkingTimeUpdate endLocation(@jakarta.annotation.Nullable LocationUpdate endLocation) { + this.endLocation = JsonNullable.of(endLocation); + + return this; + } + + /** + * Get endLocation + * @return endLocation + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END_LOCATION, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEndLocation() { + return endLocation; + } + + @JsonProperty(JSON_PROPERTY_END_LOCATION) + public void setEndLocation(JsonNullable endLocation) { + this.endLocation = endLocation; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeUpdate workingTimeUpdate = (WorkingTimeUpdate) o; + return equalsNullable(this.start, workingTimeUpdate.start) && + equalsNullable(this.end, workingTimeUpdate.end) && + equalsNullable(this.breakTimes, workingTimeUpdate.breakTimes) && + equalsNullable(this.durationType, workingTimeUpdate.durationType) && + equalsNullable(this.changed, workingTimeUpdate.changed) && + equalsNullable(this.notes, workingTimeUpdate.notes) && + equalsNullable(this.workingTimeTypeId, workingTimeUpdate.workingTimeTypeId) && + equalsNullable(this.status, workingTimeUpdate.status) && + equalsNullable(this.metadata, workingTimeUpdate.metadata) && + equalsNullable(this.startLocation, workingTimeUpdate.startLocation) && + equalsNullable(this.endLocation, workingTimeUpdate.endLocation); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(durationType), hashCodeNullable(changed), hashCodeNullable(notes), hashCodeNullable(workingTimeTypeId), hashCodeNullable(status), hashCodeNullable(metadata), hashCodeNullable(startLocation), hashCodeNullable(endLocation)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeUpdate {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" durationType: ").append(toIndentedString(durationType)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeUpsert.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeUpsert.java new file mode 100644 index 0000000..ce4e244 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimeUpsert.java @@ -0,0 +1,396 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.BreakTimeUpdate; +import com.timr.api.models.DurationType; +import com.timr.api.models.WorkingTimeStatus; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimeUpsert + */ +@JsonPropertyOrder({ + WorkingTimeUpsert.JSON_PROPERTY_START, + WorkingTimeUpsert.JSON_PROPERTY_END, + WorkingTimeUpsert.JSON_PROPERTY_BREAK_TIMES, + WorkingTimeUpsert.JSON_PROPERTY_DURATION_TYPE, + WorkingTimeUpsert.JSON_PROPERTY_CHANGED, + WorkingTimeUpsert.JSON_PROPERTY_NOTES, + WorkingTimeUpsert.JSON_PROPERTY_WORKING_TIME_TYPE_ID, + WorkingTimeUpsert.JSON_PROPERTY_STATUS, + WorkingTimeUpsert.JSON_PROPERTY_METADATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimeUpsert { + public static final String JSON_PROPERTY_START = "start"; + @jakarta.annotation.Nullable + private JsonNullable start = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_END = "end"; + @jakarta.annotation.Nullable + private JsonNullable end = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_BREAK_TIMES = "break_times"; + @jakarta.annotation.Nullable + private JsonNullable> breakTimes = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_DURATION_TYPE = "duration_type"; + @jakarta.annotation.Nullable + private JsonNullable durationType = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_CHANGED = "changed"; + @jakarta.annotation.Nullable + private JsonNullable changed = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NOTES = "notes"; + @jakarta.annotation.Nullable + private JsonNullable notes = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_WORKING_TIME_TYPE_ID = "working_time_type_id"; + @jakarta.annotation.Nullable + private JsonNullable workingTimeTypeId = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STATUS = "status"; + @jakarta.annotation.Nullable + private JsonNullable status = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_METADATA = "metadata"; + @jakarta.annotation.Nullable + private JsonNullable> metadata = JsonNullable.>undefined(); + + public WorkingTimeUpsert() { + } + + public WorkingTimeUpsert start(@jakarta.annotation.Nullable OffsetDateTime start) { + this.start = JsonNullable.of(start); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * @return start + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_START, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStart() { + return start; + } + + @JsonProperty(JSON_PROPERTY_START) + public void setStart(JsonNullable start) { + this.start = start; + } + + + + public WorkingTimeUpsert end(@jakarta.annotation.Nullable OffsetDateTime end) { + this.end = JsonNullable.of(end); + + return this; + } + + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * @return end + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_END, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getEnd() { + return end; + } + + @JsonProperty(JSON_PROPERTY_END) + public void setEnd(JsonNullable end) { + this.end = end; + } + + + + public WorkingTimeUpsert breakTimes(@jakarta.annotation.Nullable List breakTimes) { + this.breakTimes = JsonNullable.>of(breakTimes); + + return this; + } + + public WorkingTimeUpsert addBreakTimesItem(BreakTimeUpdate breakTimesItem) { + if (this.breakTimes == null || !this.breakTimes.isPresent()) { + this.breakTimes = JsonNullable.>of(new ArrayList<>()); + } + try { + this.breakTimes.get().add(breakTimesItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get breakTimes + * @return breakTimes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_BREAK_TIMES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getBreakTimes() { + return breakTimes; + } + + @JsonProperty(JSON_PROPERTY_BREAK_TIMES) + public void setBreakTimes(JsonNullable> breakTimes) { + this.breakTimes = breakTimes; + } + + + + public WorkingTimeUpsert durationType(@jakarta.annotation.Nullable DurationType durationType) { + this.durationType = JsonNullable.of(durationType); + + return this; + } + + /** + * Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @return durationType + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_DURATION_TYPE, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getDurationType() { + return durationType; + } + + @JsonProperty(JSON_PROPERTY_DURATION_TYPE) + public void setDurationType(JsonNullable durationType) { + this.durationType = durationType; + } + + + + public WorkingTimeUpsert changed(@jakarta.annotation.Nullable Boolean changed) { + this.changed = JsonNullable.of(changed); + + return this; + } + + /** + * Get changed + * @return changed + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_CHANGED, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getChanged() { + return changed; + } + + @JsonProperty(JSON_PROPERTY_CHANGED) + public void setChanged(JsonNullable changed) { + this.changed = changed; + } + + + + public WorkingTimeUpsert notes(@jakarta.annotation.Nullable String notes) { + this.notes = JsonNullable.of(notes); + + return this; + } + + /** + * Get notes + * @return notes + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NOTES, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getNotes() { + return notes; + } + + @JsonProperty(JSON_PROPERTY_NOTES) + public void setNotes(JsonNullable notes) { + this.notes = notes; + } + + + + public WorkingTimeUpsert workingTimeTypeId(@jakarta.annotation.Nullable String workingTimeTypeId) { + this.workingTimeTypeId = JsonNullable.of(workingTimeTypeId); + + return this; + } + + /** + * Get workingTimeTypeId + * @return workingTimeTypeId + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_WORKING_TIME_TYPE_ID, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getWorkingTimeTypeId() { + return workingTimeTypeId; + } + + @JsonProperty(JSON_PROPERTY_WORKING_TIME_TYPE_ID) + public void setWorkingTimeTypeId(JsonNullable workingTimeTypeId) { + this.workingTimeTypeId = workingTimeTypeId; + } + + + + public WorkingTimeUpsert status(@jakarta.annotation.Nullable WorkingTimeStatus status) { + this.status = JsonNullable.of(status); + + return this; + } + + /** + * Get status + * @return status + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_STATUS, required = false) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable getStatus() { + return status; + } + + @JsonProperty(JSON_PROPERTY_STATUS) + public void setStatus(JsonNullable status) { + this.status = status; + } + + + + public WorkingTimeUpsert metadata(@jakarta.annotation.Nullable Map metadata) { + this.metadata = JsonNullable.>of(metadata); + + return this; + } + + public WorkingTimeUpsert putMetadataItem(String key, Object metadataItem) { + if (this.metadata == null || !this.metadata.isPresent()) { + this.metadata = JsonNullable.>of(new HashMap<>()); + } + try { + this.metadata.get().put(key, metadataItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get metadata + * @return metadata + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_METADATA, required = false) + @JsonInclude(content = JsonInclude.Include.ALWAYS, value = JsonInclude.Include.USE_DEFAULTS) + public JsonNullable> getMetadata() { + return metadata; + } + + @JsonProperty(JSON_PROPERTY_METADATA) + public void setMetadata(JsonNullable> metadata) { + this.metadata = metadata; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimeUpsert workingTimeUpsert = (WorkingTimeUpsert) o; + return equalsNullable(this.start, workingTimeUpsert.start) && + equalsNullable(this.end, workingTimeUpsert.end) && + equalsNullable(this.breakTimes, workingTimeUpsert.breakTimes) && + equalsNullable(this.durationType, workingTimeUpsert.durationType) && + equalsNullable(this.changed, workingTimeUpsert.changed) && + equalsNullable(this.notes, workingTimeUpsert.notes) && + equalsNullable(this.workingTimeTypeId, workingTimeUpsert.workingTimeTypeId) && + equalsNullable(this.status, workingTimeUpsert.status) && + equalsNullable(this.metadata, workingTimeUpsert.metadata); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(start), hashCodeNullable(end), hashCodeNullable(breakTimes), hashCodeNullable(durationType), hashCodeNullable(changed), hashCodeNullable(notes), hashCodeNullable(workingTimeTypeId), hashCodeNullable(status), hashCodeNullable(metadata)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimeUpsert {\n"); + sb.append(" start: ").append(toIndentedString(start)).append("\n"); + sb.append(" end: ").append(toIndentedString(end)).append("\n"); + sb.append(" durationType: ").append(toIndentedString(durationType)).append("\n"); + sb.append(" workingTimeTypeId: ").append(toIndentedString(workingTimeTypeId)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimesPage.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimesPage.java new file mode 100644 index 0000000..44a9881 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimesPage.java @@ -0,0 +1,161 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import com.timr.api.models.WorkingTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * WorkingTimesPage + */ +@JsonPropertyOrder({ + WorkingTimesPage.JSON_PROPERTY_NEXT_PAGE_TOKEN, + WorkingTimesPage.JSON_PROPERTY_DATA +}) +@jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.22.0") +public class WorkingTimesPage { + public static final String JSON_PROPERTY_NEXT_PAGE_TOKEN = "next_page_token"; + @jakarta.annotation.Nullable + private String nextPageToken; + + public static final String JSON_PROPERTY_DATA = "data"; + @jakarta.annotation.Nonnull + private List data; + + public WorkingTimesPage() { + } + + public WorkingTimesPage nextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + + this.nextPageToken = nextPageToken; + return this; + } + + /** + * Token for the next page, or null when this is the last page. + * @return nextPageToken + */ + @jakarta.annotation.Nullable + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getNextPageToken() { + return nextPageToken; + } + + + @JsonProperty(value = JSON_PROPERTY_NEXT_PAGE_TOKEN, required = false) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setNextPageToken(@jakarta.annotation.Nullable String nextPageToken) { + this.nextPageToken = nextPageToken; + } + + + public WorkingTimesPage data(@jakarta.annotation.Nonnull List data) { + + this.data = data; + return this; + } + + public WorkingTimesPage addDataItem(WorkingTime dataItem) { + if (this.data == null) { + this.data = new ArrayList<>(); + } + this.data.add(dataItem); + return this; + } + + /** + * Get data + * @return data + */ + @jakarta.annotation.Nonnull + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getData() { + return data; + } + + + @JsonProperty(value = JSON_PROPERTY_DATA, required = true) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setData(@jakarta.annotation.Nonnull List data) { + this.data = data; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + WorkingTimesPage workingTimesPage = (WorkingTimesPage) o; + return Objects.equals(this.nextPageToken, workingTimesPage.nextPageToken) && + Objects.equals(this.data, workingTimesPage.data); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nextPageToken, data); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class WorkingTimesPage {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +} + diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimesSortColumn.java b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimesSortColumn.java new file mode 100644 index 0000000..86653c5 --- /dev/null +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/models/WorkingTimesSortColumn.java @@ -0,0 +1,60 @@ +/* + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.timr.api.models; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Sort property for Working Times. + */ +public enum WorkingTimesSortColumn { + + START("start"), + + LAST_MODIFIED("last_modified"); + + private String value; + + WorkingTimesSortColumn(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static WorkingTimesSortColumn fromValue(String value) { + for (WorkingTimesSortColumn b : WorkingTimesSortColumn.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/sdk/java-resttemplate/src/test/java/com/timr/api/ApiClientJackson3Test.java b/sdk/java-resttemplate/src/test/java/com/timr/api/ApiClientJackson3Test.java new file mode 100644 index 0000000..f8f8564 --- /dev/null +++ b/sdk/java-resttemplate/src/test/java/com/timr/api/ApiClientJackson3Test.java @@ -0,0 +1,68 @@ +package com.timr.api; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.junit.jupiter.api.Test; +import org.openapitools.jackson.nullable.JsonNullable; + +import java.time.OffsetDateTime; +import java.text.DateFormat; +import java.lang.reflect.Modifier; +import org.springframework.web.client.RestTemplate; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ApiClientJackson3Test { + + private final tools.jackson.databind.json.JsonMapper mapper = + ApiClient.createDefaultMapper(ApiClient.createDefaultDateFormat()); + + @Test + void exposesRestTemplateOnlyThroughConstructorInjection() throws Exception { + var mapperFactory = ApiClient.class.getDeclaredMethod("createDefaultMapper", DateFormat.class); + var restTemplateConstructor = ApiClient.class.getDeclaredConstructor(RestTemplate.class); + + assertFalse(Modifier.isPublic(mapperFactory.getModifiers())); + assertTrue(Modifier.isPublic(restTemplateConstructor.getModifiers())); + assertThrows(NoSuchMethodException.class, () -> ApiClient.class.getMethod("getRestTemplate")); + } + + @Test + void preservesJsonNullableUndefinedNullAndValueStates() throws Exception { + var undefined = mapper.readValue("{}", NullablePayload.class); + var explicitNull = mapper.readValue("{\"value\":null}", NullablePayload.class); + var present = mapper.readValue("{\"value\":\"timr\"}", NullablePayload.class); + + assertFalse(undefined.value.isPresent()); + assertTrue(explicitNull.value.isPresent()); + assertNull(explicitNull.value.get()); + assertEquals("timr", present.value.get()); + + assertEquals("{}", mapper.writeValueAsString(undefined)); + assertEquals("{\"value\":null}", mapper.writeValueAsString(explicitNull)); + assertEquals("{\"value\":\"timr\"}", mapper.writeValueAsString(present)); + } + + @Test + void preservesRfc3339OffsetWhenReadingAndWriting() throws Exception { + var input = "2023-10-10T12:00:00.123+02:00"; + + var payload = mapper.readValue("{\"value\":\"" + input + "\"}", DateTimePayload.class); + + assertEquals(OffsetDateTime.parse(input), payload.value); + assertEquals("{\"value\":\"" + input + "\"}", mapper.writeValueAsString(payload)); + } + + static final class NullablePayload { + @JsonProperty("value") + public JsonNullable value = JsonNullable.undefined(); + } + + static final class DateTimePayload { + @JsonProperty("value") + public OffsetDateTime value; + } +} diff --git a/sdk/java-resttemplate/src/test/java/com/timr/api/apis/UserApiTest.java b/sdk/java-resttemplate/src/test/java/com/timr/api/apis/UserApiTest.java new file mode 100644 index 0000000..e416108 --- /dev/null +++ b/sdk/java-resttemplate/src/test/java/com/timr/api/apis/UserApiTest.java @@ -0,0 +1,276 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.models.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +import java.time.LocalDate; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +class UserApiTest { + + private static final String BASE_PATH = "http://localhost:8081/"; + + private MockRestServiceServer server; + private UserApi userApi; + + @BeforeEach + void setUp() { + var restTemplate = new RestTemplate(); + server = MockRestServiceServer.bindTo(restTemplate).build(); + + ApiClient apiClient = new ApiClient(restTemplate); + apiClient.setBasePath(BASE_PATH); + apiClient.getAuthentication().setAccessToken("dummyToken"); + userApi = new UserApi(apiClient); + } + + @Test + void getUser() { + String id = "user123"; + String jsonResponse = """ + { + "id": "user123", + "firstname": "John", + "lastname": "Doe", + "fullname": "John Doe", + "email": "john.doe@example.com", + "employee_number": "E123", + "external_id": "EXT123", + "login": "johndoe", + "entry_date": "2023-01-01", + "resign_date": null, + "work_schedule_model": { + "id": "schedule123", + "name": "Standard Schedule" + }, + "holiday_calendar": { + "id": "calendar123", + "description": "Standard Holidays" + } + } + """; + + server.expect(requestTo(BASE_PATH + "users/" + id)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + User user = userApi.getUser(id); + + server.verify(); + + assertNotNull(user); + assertEquals("user123", user.getId()); + assertEquals("John", user.getFirstname()); + assertEquals("Doe", user.getLastname()); + assertEquals("John Doe", user.getFullname()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals("E123", user.getEmployeeNumber()); + assertEquals("EXT123", user.getExternalId()); + assertEquals("johndoe", user.getLogin().orElse(null)); + assertEquals(LocalDate.parse("2023-01-01"), user.getEntryDate().orElse(null)); + assertNull(user.getResignDate().orElse(null)); + + assertNotNull(user.getWorkScheduleModel().orElse(null)); + assertEquals("schedule123", user.getWorkScheduleModel().orElse(null).getId()); + assertEquals("Standard Schedule", user.getWorkScheduleModel().orElse(null).getName()); + + assertNotNull(user.getHolidayCalendar().orElse(null)); + assertEquals("calendar123", user.getHolidayCalendar().orElse(null).getId()); + assertEquals("Standard Holidays", user.getHolidayCalendar().orElse(null).getDescription()); + } + + @Test + void fetchUsers() { + String jsonResponse = """ + { + "next_page_token": "token123", + "data": [ + { + "id": "user123", + "firstname": "John", + "lastname": "Doe", + "fullname": "John Doe", + "email": "john.doe@example.com", + "employee_number": "E123", + "external_id": "EXT123", + "login": "johndoe", + "entry_date": "2023-01-01", + "resign_date": null, + "work_schedule_model": { + "id": "schedule123", + "name": "Standard Schedule" + }, + "holiday_calendar": { + "id": "calendar123", + "description": "Standard Holidays" + } + } + ] + } + """; + + server.expect(requestTo(BASE_PATH + "users?name=John&entry_date_from=2023-01-01&entry_date_to=2023-12-31&resign_date_from=2023-01-01&resign_date_to=2023-12-31&resigned=false&employee_number=E123&page_token=token123&limit=10&sort_direction=asc&sort_by=name")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + UsersPage usersPage = userApi.fetchUsers("John", + LocalDate.parse("2023-01-01"), + LocalDate.parse("2023-12-31"), + LocalDate.parse("2023-01-01"), + LocalDate.parse("2023-12-31"), + false, + "E123", + "token123", + 10, + SortDirection.ASC, + UsersSortColumn.NAME); + + server.verify(); + + assertNotNull(usersPage); + assertEquals("token123", usersPage.getNextPageToken()); + + List users = usersPage.getData(); + assertNotNull(users); + assertEquals(1, users.size()); + + User user = users.get(0); + assertNotNull(user); + assertEquals("user123", user.getId()); + assertEquals("John", user.getFirstname()); + assertEquals("Doe", user.getLastname()); + assertEquals("John Doe", user.getFullname()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals("E123", user.getEmployeeNumber()); + assertEquals("EXT123", user.getExternalId()); + assertEquals("johndoe", user.getLogin().orElse(null)); + assertEquals(LocalDate.parse("2023-01-01"), user.getEntryDate().orElse(null)); + assertNull(user.getResignDate().orElse(null)); + + assertNotNull(user.getWorkScheduleModel().orElse(null)); + assertEquals("schedule123", user.getWorkScheduleModel().orElse(null).getId()); + assertEquals("Standard Schedule", user.getWorkScheduleModel().orElse(null).getName()); + + assertNotNull(user.getHolidayCalendar().orElse(null)); + assertEquals("calendar123", user.getHolidayCalendar().orElse(null).getId()); + assertEquals("Standard Holidays", user.getHolidayCalendar().orElse(null).getDescription()); + } + + @Test + void createUser() { + // given + UserCreate userCreate = new UserCreate() + .login("johndoe") + .firstname("John") + .lastname("Doe") + .email("john.doe@example.com") + .entryDate(LocalDate.parse("2023-01-01")) + .resignDate(null) + .employeeNumber("E123") + .externalId("EXT123") + .authProvider("provider") + .authIdentifier("identifier"); + + server.expect(requestTo(BASE_PATH + "users")) + .andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.login").value("johndoe")) + .andExpect(jsonPath("$.firstname").value("John")) + .andExpect(jsonPath("$.lastname").value("Doe")) + .andExpect(jsonPath("$.email").value("john.doe@example.com")) + .andExpect(jsonPath("$.entry_date").value("2023-01-01")) + .andExpect(jsonPath("$.resign_date").doesNotExist()) + .andExpect(jsonPath("$.employee_number").value("E123")) + .andExpect(jsonPath("$.external_id").value("EXT123")) + .andExpect(jsonPath("$.auth_provider").value("provider")) + .andExpect(jsonPath("$.auth_identifier").value("identifier")) + .andRespond(withSuccess(""" + { + "id": "user123", + "login": "johndoe", + "firstname": "John", + "lastname": "Doe", + "email": "john.doe@example.com", + "entry_date": "2023-01-01", + "resign_date": null, + "employee_number": "E123", + "external_id": "EXT123" + } + """, MediaType.APPLICATION_JSON)); + + User user = userApi.createUser(userCreate); + + server.verify(); + + assertNotNull(user); + assertEquals("user123", user.getId()); + assertEquals("johndoe", user.getLogin().get()); + assertEquals("John", user.getFirstname()); + assertEquals("Doe", user.getLastname()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals(LocalDate.parse("2023-01-01"), user.getEntryDate().orElse(null)); + assertNull(user.getResignDate().orElse(null)); + assertEquals("E123", user.getEmployeeNumber()); + assertEquals("EXT123", user.getExternalId()); + } + + @Test + void updateUser() { + // given + UserUpdate userUpdate = new UserUpdate() + .login("johndoe") + .firstname("John") + .lastname("Doe") + .email("john.doe@example.com"); + + server.expect(requestTo(BASE_PATH + "users/user123")) + .andExpect(method(HttpMethod.PATCH)) + .andExpect(jsonPath("$.login").value("johndoe")) + .andExpect(jsonPath("$.firstname").value("John")) + .andExpect(jsonPath("$.lastname").value("Doe")) + .andExpect(jsonPath("$.email").value("john.doe@example.com")) + .andExpect(jsonPath("$.entry_date").doesNotExist()) + .andExpect(jsonPath("$.resign_date").doesNotExist()) + .andExpect(jsonPath("$.employee_number").doesNotExist()) + .andRespond(withSuccess(""" + { + "id": "user123", + "login": "johndoe", + "firstname": "John", + "lastname": "Doe", + "email": "john.doe@example.com", + "entry_date": "2023-01-01", + "resign_date": null, + "employee_number": "E123", + "external_id": "EXT123" + } + """, MediaType.APPLICATION_JSON)); + + // when + User user = userApi.updateUser("user123", userUpdate); + + // then + server.verify(); + + assertNotNull(user); + assertEquals("user123", user.getId()); + assertEquals("johndoe", user.getLogin().get()); + assertEquals("John", user.getFirstname()); + assertEquals("Doe", user.getLastname()); + assertEquals("john.doe@example.com", user.getEmail()); + assertEquals(LocalDate.parse("2023-01-01"), user.getEntryDate().orElse(null)); + assertNull(user.getResignDate().orElse(null)); + assertEquals("E123", user.getEmployeeNumber()); + assertEquals("EXT123", user.getExternalId()); + } + +} diff --git a/sdk/java-resttemplate/src/test/java/com/timr/api/apis/WorkingTimeApiTest.java b/sdk/java-resttemplate/src/test/java/com/timr/api/apis/WorkingTimeApiTest.java new file mode 100644 index 0000000..d9a516d --- /dev/null +++ b/sdk/java-resttemplate/src/test/java/com/timr/api/apis/WorkingTimeApiTest.java @@ -0,0 +1,417 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.models.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openapitools.jackson.nullable.JsonNullable; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +class WorkingTimeApiTest { + + private static final String BASE_PATH = "http://localhost:8081/"; + + private MockRestServiceServer server; + private WorkingTimeApi workingTimeApi; + + @BeforeEach + void setUp() { + var restTemplate = new RestTemplate(); + server = MockRestServiceServer.bindTo(restTemplate).build(); + + ApiClient apiClient = new ApiClient(restTemplate); + apiClient.setBasePath(BASE_PATH); + apiClient.getAuthentication().setAccessToken("dummyToken"); + workingTimeApi = new WorkingTimeApi(apiClient); + } + + @Test + void getWorkingTime1() { + String id = "123"; + String jsonResponse = """ + { + "id": "123", + "start": "2023-10-10T10:00:00Z", + "end": "2023-10-10T18:00:00Z", + "break_time_total_minutes": 60, + "break_times": [], + "duration": null, + "changed": true, + "notes": "Worked on project", + "user": { "id": "user123" }, + "working_time_type": { "id": "type123" }, + "working_time_date_span": null, + "start_location": null, + "end_location": null, + "start_platform": null, + "end_platform": null, + "last_modified": "2023-10-10T18:00:00Z", + "last_modified_by": { "id": "user123" }, + "status": "changeable", + "metadata": null + } + """; + + server.expect(requestTo(BASE_PATH + "working-times/" + id)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + WorkingTime workingTime = workingTimeApi.getWorkingTime(id); + + server.verify(); + + assertNotNull(workingTime); + assertEquals("123", workingTime.getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T10:00:00Z"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getEnd()); + assertEquals(60, workingTime.getBreakTimeTotalMinutes()); + assertTrue(workingTime.getBreakTimes().isEmpty()); + assertTrue(workingTime.getChanged()); + assertEquals("Worked on project", workingTime.getNotes()); + assertEquals("user123", workingTime.getUser().getId()); + assertEquals("type123", workingTime.getWorkingTimeType().getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getLastModified()); + assertEquals("user123", workingTime.getLastModifiedBy().getId()); + assertEquals(WorkingTimeStatus.CHANGEABLE, workingTime.getStatus()); + } + + @Test + void getWorkingTime2() { + String id = "123"; + String jsonResponse = """ + { + "id": "123", + "start": "2023-10-10T10:00:00Z", + "end": "2023-10-10T18:00:00Z", + "break_time_total_minutes": 60, + "break_times": [ + { + "type": "manual", + "start" : "2023-10-10T12:00:00Z", + "end" : "2023-10-10T12:30:00Z", + "duration_minutes": 30 + }, + { + "type": "automatic", + "start" : "2023-10-10T14:00:00Z", + "end" : "2023-10-10T15:00:00Z", + "duration_minutes": 60 + } + ], + "duration": null, + "changed": true, + "notes": "Worked on project", + "user": { "id": "user123" }, + "working_time_type": { "id": "type123" }, + "working_time_date_span": null, + "start_location": { + "lat": 12.34, + "lon": 56.78, + "timestamp": "2023-10-10T12:00:00Z", + "formatted_address": "Example street 123" + }, + "end_location": { + "lat": 98.76, + "lon": 55.77, + "timestamp": "2023-10-10T12:00:00Z", + "formatted_address": "Marina" + }, + "start_platform": "timr_api", + "end_platform": "timr_api", + "last_modified": "2023-10-10T18:00:00Z", + "last_modified_by": { "id": "user123" }, + "status": "changeable" + } + """; + + server.expect(requestTo(BASE_PATH + "working-times/" + id)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + WorkingTime workingTime = workingTimeApi.getWorkingTime(id); + + assertNotNull(workingTime); + assertEquals("123", workingTime.getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T10:00:00Z"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getEnd()); + assertEquals(60, workingTime.getBreakTimeTotalMinutes()); + + assertFalse(workingTime.getBreakTimes().isEmpty()); + assertEquals(BreakTimeType.MANUAL, workingTime.getBreakTimes().get(0).getType()); + BreakTimeManual manualModel = (BreakTimeManual) workingTime.getBreakTimes().get(0); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00Z"), manualModel.getStart().get()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:30:00Z"), manualModel.getEnd().get()); + assertEquals(30, manualModel.getDurationMinutes()); + assertEquals(BreakTimeType.AUTOMATIC, workingTime.getBreakTimes().get(1).getType()); + BreakTimeAutomatic automaticModel = (BreakTimeAutomatic) workingTime.getBreakTimes().get(1); + assertEquals(OffsetDateTime.parse("2023-10-10T14:00:00Z"), automaticModel.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T15:00:00Z"), automaticModel.getEnd()); + assertEquals(60, automaticModel.getDurationMinutes()); + + assertTrue(workingTime.getChanged()); + assertEquals("Worked on project", workingTime.getNotes()); + assertEquals("user123", workingTime.getUser().getId()); + assertEquals("type123", workingTime.getWorkingTimeType().getId()); + + assertEquals(12.34f, workingTime.getStartLocation().getLat()); + assertEquals(56.78f, workingTime.getStartLocation().getLon()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00Z"), workingTime.getStartLocation().getTimestamp().get()); + assertEquals("Example street 123", workingTime.getStartLocation().getFormattedAddress().get()); + assertNotNull(workingTime.getEndLocation()); + assertEquals(98.76f, workingTime.getEndLocation().getLat()); + assertEquals(55.77f, workingTime.getEndLocation().getLon()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00Z"), workingTime.getEndLocation().getTimestamp().get()); + assertEquals("Marina", workingTime.getEndLocation().getFormattedAddress().get()); + assertEquals(Platform.TIMR_API, workingTime.getStartPlatform()); + assertEquals(Platform.TIMR_API, workingTime.getEndPlatform()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getLastModified()); + assertEquals("user123", workingTime.getLastModifiedBy().getId()); + assertEquals(WorkingTimeStatus.CHANGEABLE, workingTime.getStatus()); + assertEquals(JsonNullable.undefined(), workingTime.getMetadata()); + + server.verify(); + } + + + @Test + void deserializesRfc3339DateTimeWithOffsetAndFraction() { + // RFC3339 permits a numeric UTC offset and fractional seconds (not just a trailing "Z"). + // Verify both are parsed to the correct instant. + String jsonResponse = """ + { + "id": "123", + "start": "2023-10-10T12:00:00.123+02:00", + "end": "2023-10-10T20:30:45-04:30", + "break_time_total_minutes": 60, + "break_times": [], + "changed": true, + "user": { "id": "user123" }, + "working_time_type": { "id": "type123" }, + "last_modified": "2023-10-10T18:00:00Z", + "status": "changeable" + } + """; + + server.expect(requestTo(BASE_PATH + "working-times/123")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(jsonResponse, MediaType.APPLICATION_JSON)); + + WorkingTime workingTime = workingTimeApi.getWorkingTime("123"); + + server.verify(); + // Preserve the wire offsets while parsing the same instants correctly. + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00.123+02:00"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00.123+02:00").toInstant(), workingTime.getStart().toInstant()); + assertEquals(OffsetDateTime.parse("2023-10-10T20:30:45-04:30"), workingTime.getEnd()); + } + + @Test + void serializesRfc3339DateTimeWithNonUtcOffset() { + // A date-time carrying a non-UTC offset must be serialized as a valid RFC3339 string. + WorkingTimeCreate workingTimeCreate = new WorkingTimeCreate() + .start(OffsetDateTime.parse("2023-10-10T12:00:00+02:00")) + .end(OffsetDateTime.parse("2023-10-10T18:00:00Z")) + .breakTimes(new ArrayList<>()) + .changed(true) + .workingTimeTypeId("typeId") + .status(WorkingTimeStatus.CHANGEABLE) + .userId("userId"); + + server.expect(requestTo(BASE_PATH + "working-times")) + .andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.start").value("2023-10-10T12:00:00+02:00")) + .andExpect(jsonPath("$.end").value("2023-10-10T18:00:00Z")) + .andRespond(withSuccess(""" + { + "id": "id", + "start": "2023-10-10T12:00:00+02:00", + "end": "2023-10-10T18:00:00Z", + "break_times": [], + "changed": true, + "working_time_type": { "id" : "typeId" }, + "status": "changeable", + "user": {"id": "userId" } + } + """, MediaType.APPLICATION_JSON)); + + WorkingTime workingTime = workingTimeApi.createWorkingTime(workingTimeCreate); + + server.verify(); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00+02:00").toInstant(), workingTime.getStart().toInstant()); + } + + @Test + void createWorkingTime() { + // given + WorkingTimeCreate workingTimeCreate = new WorkingTimeCreate() + .start(OffsetDateTime.parse("2023-10-10T10:00:00Z")) + .end(OffsetDateTime.parse("2023-10-10T18:00:00Z")) + .breakTimes(new ArrayList<>()) + .durationType(DurationType.FULL_DAY) + .changed(true) + .notes("Test notes") + .workingTimeTypeId("typeId") + .status(WorkingTimeStatus.CHANGEABLE) + .metadata(Map.of("key", "value")) + .userId("userId"); + + server.expect(requestTo(BASE_PATH + "working-times")) + .andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.start").value("2023-10-10T10:00:00Z")) + .andExpect(jsonPath("$.end").value("2023-10-10T18:00:00Z")) + .andExpect(jsonPath("$.break_times").isEmpty()) + .andExpect(jsonPath("$.duration_type").value("full_day")) + .andExpect(jsonPath("$.changed").value(true)) + .andExpect(jsonPath("$.notes").value("Test notes")) + .andExpect(jsonPath("$.working_time_type_id").value("typeId")) + .andExpect(jsonPath("$.start_location").doesNotExist()) + .andExpect(jsonPath("$.end_location").doesNotExist()) + .andExpect(jsonPath("$.status").value("changeable")) + .andExpect(jsonPath("$.metadata.key").value("value")) + .andExpect(jsonPath("$.user_id").value("userId")) + .andExpect(jsonPath("$.status").value("changeable")) + .andRespond(withSuccess(""" + { + "id": "id", + "start": "2023-10-10T10:00:00Z", + "end": "2023-10-10T18:00:00Z", + "break_times": [], + "duration": { + "type": "full_day", + "minutes": 480 + }, + "changed": true, + "notes": "Test notes", + "working_time_type": { "id" : "typeId" }, + "start_location": {}, + "end_location": {}, + "status": "changeable", + "metadata": {"key": "value"}, + "user": {"id": "userId" } + } + """, MediaType.APPLICATION_JSON)); + + // when + WorkingTime workingTime = workingTimeApi.createWorkingTime(workingTimeCreate); + + // then + server.verify(); + + assertNotNull(workingTime); + assertEquals("id", workingTime.getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T10:00:00Z"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getEnd()); + assertEquals(0, workingTime.getBreakTimes().size()); + assertEquals(DurationType.FULL_DAY, workingTime.getDuration().getType()); + assertTrue(workingTime.getChanged()); + assertEquals("Test notes", workingTime.getNotes()); + assertEquals("typeId", workingTime.getWorkingTimeType().getId()); + assertNotNull(workingTime.getStartLocation()); + assertNotNull(workingTime.getEndLocation()); + assertEquals(WorkingTimeStatus.CHANGEABLE, workingTime.getStatus()); + assertEquals(JsonNullable.of(Map.of("key", "value")), workingTime.getMetadata()); + assertEquals("userId", workingTime.getUser().getId()); + + // todo breaktimes + } + + @Test + void updateWorkingTime() { + // given + var breakTimeManual = new BreakTimeManual() + .durationMinutes(30) + .start(OffsetDateTime.parse("2023-10-10T12:00:00Z")) + .end(OffsetDateTime.parse("2023-10-10T12:30:00Z")); + + WorkingTimeUpdate workingTimeUpdate = new WorkingTimeUpdate() + .start(OffsetDateTime.parse("2023-10-10T10:00:00Z")) + .end(OffsetDateTime.parse("2023-10-10T18:00:00Z")) + .breakTimes(List.of(breakTimeManual)) + .notes("Test notes") + .workingTimeTypeId("typeId") + .status(WorkingTimeStatus.CHANGEABLE) + .metadata(Map.of("key", "value")); + + server.expect(requestTo(BASE_PATH + "working-times/123")) + .andExpect(method(HttpMethod.PATCH)) + .andExpect(jsonPath("$.start").value("2023-10-10T10:00:00Z")) + .andExpect(jsonPath("$.end").value("2023-10-10T18:00:00Z")) + .andExpect(jsonPath("$.break_times[0].type").value("manual")) + .andExpect(jsonPath("$.break_times[0].start").value("2023-10-10T12:00:00Z")) + .andExpect(jsonPath("$.break_times[0].end").value("2023-10-10T12:30:00Z")) + .andExpect(jsonPath("$.break_times[0].duration_minutes").value(30)) + .andExpect(jsonPath("$.notes").value("Test notes")) + .andExpect(jsonPath("$.working_time_type_id").value("typeId")) + .andExpect(jsonPath("$.status").value("changeable")) + .andExpect(jsonPath("$.metadata.key").value("value")) + .andRespond(withSuccess(""" + { + "id": "123", + "start": "2023-10-10T10:00:00Z", + "end": "2023-10-10T18:00:00Z", + "break_time_total_minutes": 60, + "break_times": [ + { + "type": "manual", + "start" : "2023-10-10T12:00:00Z", + "end" : "2023-10-10T12:30:00Z", + "duration_minutes": 30 + } + ], + "duration": { + "type": "full_day", + "minutes": 480 + }, + "changed": true, + "notes": "Test notes", + "working_time_type": { "id" : "typeId" }, + "start_location": {}, + "end_location": {}, + "status": "changeable", + "metadata": {"key": "value"}, + "user": {"id": "userId" } + } + """, MediaType.APPLICATION_JSON)); + + // when + WorkingTime workingTime = workingTimeApi.updateWorkingTime("123", workingTimeUpdate); + + // then + server.verify(); + + assertNotNull(workingTime); + assertEquals("123", workingTime.getId()); + assertEquals(OffsetDateTime.parse("2023-10-10T10:00:00Z"), workingTime.getStart()); + assertEquals(OffsetDateTime.parse("2023-10-10T18:00:00Z"), workingTime.getEnd()); + assertEquals(60, workingTime.getBreakTimeTotalMinutes()); + assertFalse(workingTime.getBreakTimes().isEmpty()); + assertEquals(BreakTimeType.MANUAL, workingTime.getBreakTimes().get(0).getType()); + BreakTimeManual manualModel = (BreakTimeManual) workingTime.getBreakTimes().get(0); + assertEquals(OffsetDateTime.parse("2023-10-10T12:00:00Z"), manualModel.getStart().get()); + assertEquals(OffsetDateTime.parse("2023-10-10T12:30:00Z"), manualModel.getEnd().get()); + assertEquals(30, manualModel.getDurationMinutes()); + assertEquals(DurationType.FULL_DAY, workingTime.getDuration().getType()); + assertEquals(480, workingTime.getDuration().getMinutes()); + assertTrue(workingTime.getChanged()); + assertEquals("Test notes", workingTime.getNotes()); + assertEquals("typeId", workingTime.getWorkingTimeType().getId()); + assertNotNull(workingTime.getStartLocation()); + assertNotNull(workingTime.getEndLocation()); + assertEquals(WorkingTimeStatus.CHANGEABLE, workingTime.getStatus()); + assertEquals(JsonNullable.of(Map.of("key", "value")), workingTime.getMetadata()); + assertEquals("userId", workingTime.getUser().getId()); + } + +} diff --git a/sdk/java-resttemplate/src/test/java/com/timr/api/apis/WorkingTimeTypeApiTest.java b/sdk/java-resttemplate/src/test/java/com/timr/api/apis/WorkingTimeTypeApiTest.java new file mode 100644 index 0000000..0d8ce7f --- /dev/null +++ b/sdk/java-resttemplate/src/test/java/com/timr/api/apis/WorkingTimeTypeApiTest.java @@ -0,0 +1,115 @@ +package com.timr.api.apis; + +import com.timr.api.ApiClient; +import com.timr.api.models.DurationUnit; +import com.timr.api.models.RecordingModeUser; +import com.timr.api.models.WorkingTimeTypeCategory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +class WorkingTimeTypeApiTest { + + private static final String BASE_PATH = "http://localhost:8080/"; + + private MockRestServiceServer server; + private WorkingTimeTypeApi workingTimeTypeApi; + + @BeforeEach + void setUp() { + var restTemplate = new RestTemplate(); + server = MockRestServiceServer.bindTo(restTemplate).build(); + + ApiClient apiClient = new ApiClient(restTemplate); + apiClient.setBasePath(BASE_PATH); + apiClient.getAuthentication().setAccessToken("dummyToken"); + workingTimeTypeApi = new WorkingTimeTypeApi(apiClient); + } + + @Test + void getWorkingTimeTypes() { + //given + server.expect(requestTo(BASE_PATH + "working-time-types")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(""" + { + "next_page_token": "string", + "data": [ + { + "id": "id", + "name": "example", + "short_name": "exmpl", + "description": "attendance type", + "external_id": "external id", + "edit_unit": "minutes", + "category": "attendance_time", + "sub_category": "present", + "recording_mode_user": "not_allowed", + "archived": true + } + ] + } + """, MediaType.APPLICATION_JSON)); + + // when + var workingTimes = workingTimeTypeApi.fetchWorkingTimeTypes(null, null, null, null, null, null, null, null, null, null, null, null); + + // then + server.verify(); + var workingTimeType = workingTimes.getData().get(0); + assertEquals("id", workingTimeType.getId()); + assertEquals("example", workingTimeType.getName()); + assertEquals("exmpl", workingTimeType.getShortName()); + assertEquals("attendance type", workingTimeType.getDescription()); + assertEquals("external id", workingTimeType.getExternalId()); + assertEquals(true, workingTimeType.getArchived()); + } + + @Test + void getWorkingTimeType() { + //given + server.expect(requestTo(BASE_PATH + "working-time-types/id")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(""" + { + "id": "id", + "name": "example", + "short_name": "exmpl", + "description": "attendance type", + "external_id": "external id", + "edit_unit": "days", + "category": "paid_time_off", + "recording_mode_user": "by_request", + "archived": false + } + """, MediaType.APPLICATION_JSON)); + + // when + var workingTimeType = workingTimeTypeApi.getWorkingTimeType("id"); + + // then + server.verify(); + + assertNotNull(workingTimeType); + assertEquals("id", workingTimeType.getId()); + assertEquals("example", workingTimeType.getName()); + assertEquals("exmpl", workingTimeType.getShortName()); + assertEquals("attendance type", workingTimeType.getDescription()); + assertEquals("external id", workingTimeType.getExternalId()); + assertEquals(DurationUnit.DAYS, workingTimeType.getEditUnit()); + assertEquals(WorkingTimeTypeCategory.PAID_TIME_OFF, workingTimeType.getCategory()); + assertEquals(RecordingModeUser.BY_REQUEST, workingTimeType.getRecordingModeUser()); + assertFalse(workingTimeType.getArchived()); + } + +} diff --git a/sdk/java-resttemplate/src/test/java/com/timr/api/models/ModelToStringLogSafetyTest.java b/sdk/java-resttemplate/src/test/java/com/timr/api/models/ModelToStringLogSafetyTest.java new file mode 100644 index 0000000..c213649 --- /dev/null +++ b/sdk/java-resttemplate/src/test/java/com/timr/api/models/ModelToStringLogSafetyTest.java @@ -0,0 +1,44 @@ +package com.timr.api.models; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class ModelToStringLogSafetyTest { + + @Test + void durationToStringIncludesUsefulSummaryFields() { + String rendered = new Duration() + .type(DurationType.MINUTES) + .minutes(42L) + .minutesRounded(45L) + .toString(); + + assertTrue(rendered.contains("type: minutes")); + assertTrue(rendered.contains("minutes: 42")); + assertFalse(rendered.contains("minutesRounded: 45")); + } + + @Test + void breakTimeToStringIsNotEmpty() { + // type() is inherited from BreakTimeBase and returns the base type, so the + // variant's own setters have to come first for the chain to stay typed. + String rendered = new BreakTimeManual() + .durationMinutes(15) + .type(BreakTimeType.MANUAL) + .toString(); + + assertTrue(rendered.contains("type: manual")); + assertTrue(rendered.contains("durationMinutes: 15")); + } + + @Test + void pagingInformationToStringDoesNotExposePageToken() { + String rendered = new PagingInformation() + .nextPageToken("next-page-token") + .toString(); + + assertFalse(rendered.contains("next-page-token")); + } +} diff --git a/sdk/java-resttemplate/templates/nullable_var_annotations.mustache b/sdk/java-resttemplate/templates/nullable_var_annotations.mustache new file mode 100644 index 0000000..ef4e208 --- /dev/null +++ b/sdk/java-resttemplate/templates/nullable_var_annotations.mustache @@ -0,0 +1 @@ +{{#lambda.jSpecifyNullable}}{{#required}}{{#isNullable}}@{{javaxPackage}}.annotation.Nullable{{/isNullable}}{{^useJspecify}}{{^isNullable}}@{{javaxPackage}}.annotation.Nonnull{{/isNullable}}{{/useJspecify}}{{/required}}{{^required}}@{{javaxPackage}}.annotation.Nullable{{/required}}{{/lambda.jSpecifyNullable}} \ No newline at end of file diff --git a/sdk/java-resttemplate/templates/pojo.mustache b/sdk/java-resttemplate/templates/pojo.mustache new file mode 100644 index 0000000..5d2ee24 --- /dev/null +++ b/sdk/java-resttemplate/templates/pojo.mustache @@ -0,0 +1,625 @@ +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.*; + +/** + * {{description}}{{^description}}{{classname}}{{/description}}{{#isDeprecated}} + * @deprecated{{/isDeprecated}} + */{{#isDeprecated}} +@Deprecated{{/isDeprecated}} +{{#swagger1AnnotationLibrary}} +{{#description}} +@ApiModel(description = "{{{.}}}") +{{/description}} +{{/swagger1AnnotationLibrary}} +{{#swagger2AnnotationLibrary}} +{{#description}} +@Schema(description = "{{{.}}}") +{{/description}} +{{/swagger2AnnotationLibrary}} +{{#jackson}} +@JsonPropertyOrder({ +{{#vars}} + {{classname}}.JSON_PROPERTY_{{nameInSnakeCase}}{{^-last}},{{/-last}} +{{/vars}} +}) +{{#isClassnameSanitized}} +{{^hasDiscriminatorWithNonEmptyMapping}} +@JsonTypeName("{{name}}") +{{/hasDiscriminatorWithNonEmptyMapping}} +{{/isClassnameSanitized}} +{{/jackson}} +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{>xmlAnnotation}} +{{#vendorExtensions.x-class-extra-annotation}} +{{{vendorExtensions.x-class-extra-annotation}}} +{{/vendorExtensions.x-class-extra-annotation}} +public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{#-last}} {{/-last}}{{/vendorExtensions.x-implements}}{ +{{#serializableModel}} + private static final long serialVersionUID = 1L; + +{{/serializableModel}} + {{#vars}} + {{#isEnum}} + {{^isContainer}} +{{>modelInnerEnum}} + + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} +{{>modelInnerEnum}} + + {{/mostInnerItems}} + {{/isContainer}} + {{/isEnum}} + {{#gson}} + public static final String SERIALIZED_NAME_{{nameInSnakeCase}} = "{{baseName}}"; + {{/gson}} + {{#jackson}} + public static final String JSON_PROPERTY_{{nameInSnakeCase}} = "{{baseName}}"; + {{/jackson}} + {{#withXml}} + @Xml{{#isXmlAttribute}}Attribute{{/isXmlAttribute}}{{^isXmlAttribute}}Element{{/isXmlAttribute}}(name = "{{items.xmlName}}{{^items.xmlName}}{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}{{/items.xmlName}}"{{#xmlNamespace}}, namespace = "{{.}}"{{/xmlNamespace}}) + {{#isXmlWrapped}} + @XmlElementWrapper(name = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}"{{#xmlNamespace}}, namespace = "{{.}}"{{/xmlNamespace}}) + {{/isXmlWrapped}} + {{^isXmlAttribute}} + {{#isDateTime}} + @XmlJavaTypeAdapter(OffsetDateTimeXmlAdapter.class) + {{/isDateTime}} + {{/isXmlAttribute}} + {{/withXml}} + {{#gson}} + @SerializedName(SERIALIZED_NAME_{{nameInSnakeCase}}) + {{/gson}} + {{^isDiscriminator}} + {{>nullable_var_annotations}}{{! prevent indent}} + {{/isDiscriminator}} + {{#isDiscriminator}} + // The discriminator does not have Nullability-annotation since it is added during serialization by the @JsonTypeName annotation + {{/isDiscriminator}} + {{#vendorExtensions.x-field-extra-annotation}} + {{{.}}} + {{/vendorExtensions.x-field-extra-annotation}} + {{^required}} + {{#isContainer}} + {{#hasChildren}}protected{{/hasChildren}}{{^hasChildren}}private{{/hasChildren}} JsonNullable<{{>nullableDatatypeWithEnum}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined(); + {{/isContainer}} + {{^isContainer}} + {{#hasChildren}}protected{{/hasChildren}}{{^hasChildren}}private{{/hasChildren}} JsonNullable<{{>nullableDatatypeWithEnum}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; + {{/isContainer}} + {{/required}} + {{#required}} + {{#isContainer}} + {{#hasChildren}}protected{{/hasChildren}}{{^hasChildren}}private{{/hasChildren}} {{>nullableDatatypeWithEnum}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{/isContainer}} + {{^isContainer}} + {{#hasChildren}}protected{{/hasChildren}}{{^hasChildren}}private{{/hasChildren}} {{>nullableDatatypeWithEnum}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{/isContainer}} + {{/required}} + + {{/vars}} + public {{classname}}() { + {{#parent}} + {{#parcelableModel}} + super();{{/parcelableModel}} + {{/parent}} + {{#gson}} + {{#discriminator}} + {{#discriminator.isEnum}} + this.{{{discriminatorName}}} = this.getClass().getSimpleName(); + {{/discriminator.isEnum}} + {{/discriminator}} + {{/gson}} + } + {{#vendorExtensions.x-has-readonly-properties}} + {{^withXml}} + /** + * Constructor with only readonly parameters{{#generateConstructorWithAllArgs}}{{^vendorExtensions.x-java-all-args-constructor}} and all parameters{{/vendorExtensions.x-java-all-args-constructor}}{{/generateConstructorWithAllArgs}} + */ + {{#jsonb}}@JsonbCreator{{/jsonb}}{{#jackson}}@JsonCreator{{/jackson}} + public {{classname}}( + {{#readOnlyVars}} + {{#jsonb}}@JsonbProperty(value = "{{baseName}}"{{^required}}, nullable = true{{/required}}){{/jsonb}}{{#jackson}}@JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}){{/jackson}} {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} + {{/readOnlyVars}} + ) { + this(); + {{#readOnlyVars}} + this.{{name}} = {{^required}}{{name}} == null ? JsonNullable.<{{{datatypeWithEnum}}}>undefined() : JsonNullable.of({{name}}){{/required}}{{#required}}{{name}}{{/required}}; + {{/readOnlyVars}} + } + {{/withXml}} + {{/vendorExtensions.x-has-readonly-properties}} +{{#vendorExtensions.x-java-all-args-constructor}} + + /** + * Constructor with all args parameters + */ + public {{classname}}({{#vendorExtensions.x-java-all-args-constructor-vars}}{{#jsonb}}@JsonbProperty(value = "{{baseName}}"{{^required}}, nullable = true{{/required}}){{/jsonb}}{{#jackson}}@JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}){{/jackson}} {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-java-all-args-constructor-vars}}) { +{{#parent}} + super({{#parentVars}}{{name}}{{^-last}}, {{/-last}}{{/parentVars}}); +{{/parent}} + {{#vars}} + this.{{name}} = {{^required}}{{name}} == null ? JsonNullable.<{{{datatypeWithEnum}}}>undefined() : JsonNullable.of({{name}}){{/required}}{{#required}}{{name}}{{/required}}; +{{/vars}} + } +{{/vendorExtensions.x-java-all-args-constructor}} + +{{#vars}} + {{^isReadOnly}} + public {{classname}} {{name}}({{>nullableArgumentWithEnum}} {{name}}) { + {{^required}}this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}});{{/required}} + {{#required}}this.{{name}} = {{name}};{{/required}} + return this; + } + {{#isArray}} + + public {{classname}} add{{nameInPascalCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + {{^required}} + if (this.{{name}} == null || !this.{{name}}.isPresent()) { + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}{{^defaultValue}}new {{#uniqueItems}}LinkedHashSet{{/uniqueItems}}{{^uniqueItems}}ArrayList{{/uniqueItems}}<>(){{/defaultValue}}); + } + try { + this.{{name}}.get().add({{name}}Item); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + {{/required}} + {{#required}} + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}{{^defaultValue}}new {{#uniqueItems}}LinkedHashSet{{/uniqueItems}}{{^uniqueItems}}ArrayList{{/uniqueItems}}<>(){{/defaultValue}}; + } + this.{{name}}.add({{name}}Item); + return this; + {{/required}} + } + {{/isArray}} + {{#isMap}} + + public {{classname}} put{{nameInPascalCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + {{^required}} + if (this.{{name}} == null || !this.{{name}}.isPresent()) { + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}{{^defaultValue}}new HashMap<>(){{/defaultValue}}); + } + try { + this.{{name}}.get().put(key, {{name}}Item); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + {{/required}} + {{#required}} + {{^required}} + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}{{^defaultValue}}new HashMap<>(){{/defaultValue}}; + } + {{/required}} + this.{{name}}.put(key, {{name}}Item); + return this; + {{/required}} + } + {{/isMap}} + + {{/isReadOnly}} + /** + {{#description}} + * {{.}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + * @return {{name}} + {{#deprecated}} + * @deprecated + {{/deprecated}} + */ +{{#deprecated}} + @Deprecated +{{/deprecated}} + {{>nullable_var_annotations}}{{! prevent indent}} +{{#jsonb}} + @JsonbProperty("{{baseName}}") +{{/jsonb}} +{{#useBeanValidation}} +{{>beanValidation}} + +{{/useBeanValidation}} +{{#swagger1AnnotationLibrary}} + @ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{/swagger1AnnotationLibrary}} +{{#swagger2AnnotationLibrary}} + @Schema({{#example}}example = "{{{.}}}", {{/example}}requiredMode = {{#required}}Schema.RequiredMode.REQUIRED{{/required}}{{^required}}Schema.RequiredMode.NOT_REQUIRED{{/required}}, description = "{{{description}}}") +{{/swagger2AnnotationLibrary}} +{{#vendorExtensions.x-extra-annotation}} + {{{vendorExtensions.x-extra-annotation}}} +{{/vendorExtensions.x-extra-annotation}} +{{#required}}{{#jackson}}{{> jackson_annotations}}{{/jackson}} + public {{>nullableDatatypeWithEnum}} {{getter}}() { + return {{name}}; + } +{{/required}} +{{^required}} +{{> jackson_annotations}} + public JsonNullable<{{>nullableDatatypeWithEnum}}> {{getter}}() { + {{#isReadOnly}}{{! A readonly attribute doesn't have setter => jackson will set null directly if explicitly returned by API, so make sure we have an empty JsonNullable}} + if ({{name}} == null) { + {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; + } + {{/isReadOnly}} + return {{name}}; + } + + @JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}) + {{#isReadOnly}}private{{/isReadOnly}}{{^isReadOnly}}public{{/isReadOnly}} void {{setter}}(JsonNullable<{{{datatypeWithEnum}}}> {{name}}) { + {{! For getters/setters that have name differing from attribute name, we must include setter (albeit private) for jackson to be able to set the attribute}} + this.{{name}} = {{name}}; + } +{{/required}} + + {{^isReadOnly}}{{#required}} +{{#vendorExtensions.x-setter-extra-annotation}} {{{vendorExtensions.x-setter-extra-annotation}}} +{{/vendorExtensions.x-setter-extra-annotation}}{{#jackson}}{{> jackson_annotations}}{{/jackson}} public void {{setter}}({{>nullableArgumentWithEnum}} {{name}}) { + this.{{name}} = {{name}}; + } + {{/required}}{{/isReadOnly}} + + {{/vars}} +{{>libraries/resttemplate/additional_properties}} + + {{#parent}} + {{#readWriteVars}} + {{#isOverridden}} + @Override + public {{classname}} {{name}}({{>nullableArgumentWithEnum}} {{name}}) { + {{^required}} + this.{{setter}}(JsonNullable.<{{{datatypeWithEnum}}}>of({{name}})); + {{/required}} + {{#required}} + this.{{setter}}({{name}}); + {{/required}} + return this; + } + + {{/isOverridden}} + {{/readWriteVars}} + {{/parent}} + @Override + public boolean equals(Object o) { + {{#useReflectionEqualsHashCode}} + return EqualsBuilder.reflectionEquals(this, o, false, null, true); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}{{^required}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/required}}{{#required}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/required}}{{^-last}} && + {{/-last}}{{/vars}}{{#additionalPropertiesType}} && + Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/additionalPropertiesType}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} + return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} + {{/useReflectionEqualsHashCode}} + }{{#openApiNullable}} + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + }{{/openApiNullable}} + + @Override + public int hashCode() { + {{#useReflectionEqualsHashCode}} + return HashCodeBuilder.reflectionHashCode(this); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + return Objects.hash({{#vars}}{{^required}}hashCodeNullable({{name}}){{/required}}{{#required}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/required}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}, additionalProperties{{/additionalPropertiesType}}); + {{/useReflectionEqualsHashCode}} + }{{#openApiNullable}} + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + }{{/openApiNullable}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}} + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + {{/parent}} + {{#vars}} + {{#vendorExtensions.x-log}} + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); + {{/vendorExtensions.x-log}} + {{#vendorExtensions.x-log-count}} + {{^required}} + sb.append(" {{name}}: ").append(!{{name}}.isPresent() || {{name}}.get() == null ? "null" : {{name}}.get().size() + " entries").append("\n"); + {{/required}} + {{#required}} + sb.append(" {{name}}: ").append({{name}} == null ? "null" : {{name}}.size() + " entries").append("\n"); + {{/required}} + {{/vendorExtensions.x-log-count}} + {{/vars}} + {{#additionalPropertiesType}} + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + {{/additionalPropertiesType}} + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private{{#jsonb}} static{{/jsonb}} String toIndentedString(Object o) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } +{{#supportUrlQuery}} + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + {{#allVars}} + // add `{{baseName}}` to the URL query string + {{#isArray}} + {{#items.isPrimitiveType}} + {{#uniqueItems}} + if ({{getter}}() != null) { + int i = 0; + for ({{{items.datatypeWithEnum}}} _item : {{getter}}()) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(String.valueOf(_item), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + i++; + } + {{/uniqueItems}} + {{^uniqueItems}} + if ({{getter}}() != null) { + for (int i = 0; i < {{getter}}().size(); i++) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(String.valueOf({{getter}}().get(i)), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + } + {{/uniqueItems}} + {{/items.isPrimitiveType}} + {{^items.isPrimitiveType}} + {{#items.isModel}} + {{#uniqueItems}} + if ({{getter}}() != null) { + int i = 0; + for ({{{items.dataType}}} _item : {{getter}}()) { + if (_item != null) { + joiner.add(_item.toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + i++; + } + {{/uniqueItems}} + {{^uniqueItems}} + if ({{getter}}() != null) { + for (int i = 0; i < {{getter}}().size(); i++) { + if ({{getter}}().get(i) != null) { + joiner.add({{getter}}().get(i).toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + {{/uniqueItems}} + {{/items.isModel}} + {{^items.isModel}} + {{#uniqueItems}} + if ({{getter}}() != null) { + int i = 0; + for ({{{items.dataType}}} _item : {{getter}}()) { + if (_item != null) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(String.valueOf(_item), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + i++; + } + } + {{/uniqueItems}} + {{^uniqueItems}} + if ({{getter}}() != null) { + for (int i = 0; i < {{getter}}().size(); i++) { + if ({{getter}}().get(i) != null) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + URLEncoder.encode(String.valueOf({{getter}}().get(i)), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + } + } + {{/uniqueItems}} + {{/items.isModel}} + {{/items.isPrimitiveType}} + {{/isArray}} + {{^isArray}} + {{#isMap}} + {{^items.isModel}} + if ({{getter}}() != null) { + for (String _key : {{getter}}().keySet()) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, _key, containerSuffix), + {{getter}}().get(_key), URLEncoder.encode(String.valueOf({{getter}}().get(_key)), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + } + {{/items.isModel}} + {{#items.isModel}} + if ({{getter}}() != null) { + for (String _key : {{getter}}().keySet()) { + if ({{getter}}().get(_key) != null) { + joiner.add({{getter}}().get(_key).toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, _key, containerSuffix)))); + } + } + } + {{/items.isModel}} + {{/isMap}} + {{^isMap}} + {{#isPrimitiveType}} + if ({{getter}}() != null) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{{baseName}}}%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf({{{getter}}}()), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isModel}} + if ({{getter}}() != null) { + joiner.add({{getter}}().toUrlQueryString(prefix + "{{{baseName}}}" + suffix)); + } + {{/isModel}} + {{^isModel}} + if ({{getter}}() != null) { + try { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{{baseName}}}%s=%s", prefix, suffix, URLEncoder.encode(String.valueOf({{{getter}}}()), "UTF-8").replaceAll("\\+", "%20"))); + } catch (UnsupportedEncodingException e) { + // Should never happen, UTF-8 is always supported + throw new RuntimeException(e); + } + } + {{/isModel}} + {{/isPrimitiveType}} + {{/isMap}} + {{/isArray}} + + {{/allVars}} + return joiner.toString(); + } +{{/supportUrlQuery}} +{{#parcelableModel}} + + public void writeToParcel(Parcel out, int flags) { +{{#model}} +{{#isArray}} + out.writeList(this); +{{/isArray}} +{{^isArray}} +{{#parent}} + super.writeToParcel(out, flags); +{{/parent}} +{{#vars}} + out.writeValue({{name}}); +{{/vars}} +{{/isArray}} +{{/model}} + } + + {{classname}}(Parcel in) { +{{#isArray}} + in.readTypedList(this, {{arrayModelType}}.CREATOR); +{{/isArray}} +{{^isArray}} +{{#parent}} + super(in); +{{/parent}} +{{#vars}} +{{#isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); +{{/isPrimitiveType}} +{{^isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue({{complexType}}.class.getClassLoader()); +{{/isPrimitiveType}} +{{/vars}} +{{/isArray}} + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator<{{classname}}> CREATOR = new Parcelable.Creator<{{classname}}>() { + public {{classname}} createFromParcel(Parcel in) { +{{#model}} +{{#isArray}} + {{classname}} result = new {{classname}}(); + result.addAll(in.readArrayList({{arrayModelType}}.class.getClassLoader())); + return result; +{{/isArray}} +{{^isArray}} + return new {{classname}}(in); +{{/isArray}} +{{/model}} + } + public {{classname}}[] newArray(int size) { + return new {{classname}}[size]; + } + }; +{{/parcelableModel}} +{{#generateBuilders}} + + {{>javaBuilder}}{{! prevent indent}} +{{/generateBuilders}} + +} diff --git a/sdk/kotlin-okhttp/.gitignore b/sdk/kotlin-okhttp/.gitignore new file mode 100644 index 0000000..d919f54 --- /dev/null +++ b/sdk/kotlin-okhttp/.gitignore @@ -0,0 +1,2 @@ +# OpenApiGenerator generated meta files +.openapi-generator diff --git a/sdk/kotlin-okhttp/.openapi-generator-ignore b/sdk/kotlin-okhttp/.openapi-generator-ignore new file mode 100644 index 0000000..f5a15f2 --- /dev/null +++ b/sdk/kotlin-okhttp/.openapi-generator-ignore @@ -0,0 +1,8 @@ +build.gradle +src/test/** +docs/** +gradle/** +gradlew +gradlew.bat +settings.gradle +README.md diff --git a/sdk/kotlin-okhttp/build.gradle b/sdk/kotlin-okhttp/build.gradle new file mode 100644 index 0000000..734a5a1 --- /dev/null +++ b/sdk/kotlin-okhttp/build.gradle @@ -0,0 +1,65 @@ +plugins { + id 'java-library' + alias(libs.plugins.kotlin.jvm) + alias(libs.plugins.openapi) +} +repositories { + mavenCentral() +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(25) + } + withSourcesJar() + withJavadocJar() +} + +kotlin { + jvmToolchain(25) +} + +dependencies { + implementation libs.kotlin.stdlib + implementation libs.kotlin.reflect + implementation libs.kotlinx.coroutines.core + implementation libs.gson + implementation libs.okhttp + + testImplementation libs.junit.jupiter.api + testRuntimeOnly libs.junit.jupiter.engine + testRuntimeOnly libs.junit.platform.launcher +} + +test { + useJUnitPlatform() +} + +def cleanOpenApiGenerateTask = tasks.register('cleanOpenApiGenerate', Delete) { + delete fileTree("$projectDir/src/main/kotlin") +} + +openApiGenerate { + generatorName = 'kotlin' + outputDir = "$projectDir" + configOptions = [ + library : 'jvm-okhttp4', + omitGradleWrapper : 'true', + packageName : 'com.timr.api', + enumPropertyNaming : 'UPPERCASE', + useCoroutines : 'true', + serializationLibrary: 'gson' + ] +} + +tasks.named('openApiGenerate').configure { task -> + task.dependsOn(cleanOpenApiGenerateTask) +} + +// Generated sources are committed into this module's source set, so everything that reads them runs +// after generation; `build` on its own would otherwise quietly compile the previous generation's output. +tasks.matching { + it.name in ['compileKotlin', 'compileTestKotlin', 'processResources', 'processTestResources', 'sourcesJar', 'javadoc'] +}.configureEach { + dependsOn tasks.named('openApiGenerate') +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/CarApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/CarApi.kt new file mode 100644 index 0000000..814627d --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/CarApi.kt @@ -0,0 +1,399 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Car +import com.timr.api.models.CarCreate +import com.timr.api.models.CarUpdate +import com.timr.api.models.CarsPage +import com.timr.api.models.CarsSortColumn +import com.timr.api.models.Error +import com.timr.api.models.SortDirection + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class CarApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * POST /cars + * Create a Car + * Creates a Car from the data in the request body. + * @param carCreate Car entity + * @return Car + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createCar(carCreate: CarCreate) : Car = withContext(Dispatchers.IO) { + val localVarResponse = createCarWithHttpInfo(carCreate = carCreate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Car + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * POST /cars + * Create a Car + * Creates a Car from the data in the request body. + * @param carCreate Car entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createCarWithHttpInfo(carCreate: CarCreate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createCarRequestConfig(carCreate = carCreate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createCar + * + * @param carCreate Car entity + * @return RequestConfig + */ + fun createCarRequestConfig(carCreate: CarCreate) : RequestConfig { + val localVariableBody = carCreate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/cars", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /cars + * List Cars + * Lists the Cars the authenticated user or API token can access. + * @param nameOrPlate Only return Cars whose name or plate contains this text. (optional) + * @param usable Only return Cars that are usable (true) or not usable (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return CarsPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchCars(nameOrPlate: kotlin.String? = null, usable: kotlin.Boolean? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: CarsSortColumn? = null) : CarsPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchCarsWithHttpInfo(nameOrPlate = nameOrPlate, usable = usable, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as CarsPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /cars + * List Cars + * Lists the Cars the authenticated user or API token can access. + * @param nameOrPlate Only return Cars whose name or plate contains this text. (optional) + * @param usable Only return Cars that are usable (true) or not usable (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchCarsWithHttpInfo(nameOrPlate: kotlin.String?, usable: kotlin.Boolean?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: CarsSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchCarsRequestConfig(nameOrPlate = nameOrPlate, usable = usable, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchCars + * + * @param nameOrPlate Only return Cars whose name or plate contains this text. (optional) + * @param usable Only return Cars that are usable (true) or not usable (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchCarsRequestConfig(nameOrPlate: kotlin.String?, usable: kotlin.Boolean?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: CarsSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (nameOrPlate != null) { + put("name_or_plate", listOf(nameOrPlate.toString())) + } + if (usable != null) { + put("usable", listOf(usable.toString())) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/cars", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /cars/{id} + * Get a Car + * Returns a single Car by its ID. + * @param id ID of the Car. + * @return Car + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getCar(id: kotlin.String) : Car = withContext(Dispatchers.IO) { + val localVarResponse = getCarWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Car + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /cars/{id} + * Get a Car + * Returns a single Car by its ID. + * @param id ID of the Car. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getCarWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getCarRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getCar + * + * @param id ID of the Car. + * @return RequestConfig + */ + fun getCarRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/cars/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PATCH /cars/{id} + * Update a Car + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Car. + * @param carUpdate Car entity + * @return Car + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun updateCar(id: kotlin.String, carUpdate: CarUpdate) : Car = withContext(Dispatchers.IO) { + val localVarResponse = updateCarWithHttpInfo(id = id, carUpdate = carUpdate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Car + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PATCH /cars/{id} + * Update a Car + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Car. + * @param carUpdate Car entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun updateCarWithHttpInfo(id: kotlin.String, carUpdate: CarUpdate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = updateCarRequestConfig(id = id, carUpdate = carUpdate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateCar + * + * @param id ID of the Car. + * @param carUpdate Car entity + * @return RequestConfig + */ + fun updateCarRequestConfig(id: kotlin.String, carUpdate: CarUpdate) : RequestConfig { + val localVariableBody = carUpdate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PATCH, + path = "/cars/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/DriveLogApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/DriveLogApi.kt new file mode 100644 index 0000000..25ae84f --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/DriveLogApi.kt @@ -0,0 +1,623 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.DeletedEntryPage +import com.timr.api.models.DeletedEntrySortColumn +import com.timr.api.models.DriveLog +import com.timr.api.models.DriveLogCreate +import com.timr.api.models.DriveLogStatus +import com.timr.api.models.DriveLogUpdate +import com.timr.api.models.DriveLogsPage +import com.timr.api.models.DriveLogsSortColumn +import com.timr.api.models.Error +import com.timr.api.models.SortDirection + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class DriveLogApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * POST /drive-logs + * Create a Drive Log + * Creates a Drive Log from the data in the request body. + * @param driveLogCreate Drive Log entity + * @return DriveLog + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createDriveLog(driveLogCreate: DriveLogCreate) : DriveLog = withContext(Dispatchers.IO) { + val localVarResponse = createDriveLogWithHttpInfo(driveLogCreate = driveLogCreate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DriveLog + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * POST /drive-logs + * Create a Drive Log + * Creates a Drive Log from the data in the request body. + * @param driveLogCreate Drive Log entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createDriveLogWithHttpInfo(driveLogCreate: DriveLogCreate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createDriveLogRequestConfig(driveLogCreate = driveLogCreate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createDriveLog + * + * @param driveLogCreate Drive Log entity + * @return RequestConfig + */ + fun createDriveLogRequestConfig(driveLogCreate: DriveLogCreate) : RequestConfig { + val localVariableBody = driveLogCreate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/drive-logs", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /drive-logs/{id} + * Delete a Drive Log + * Deletes the Drive Log, including its Track. + * @param id ID of the Drive Log. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteDriveLog(id: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteDriveLogWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /drive-logs/{id} + * Delete a Drive Log + * Deletes the Drive Log, including its Track. + * @param id ID of the Drive Log. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteDriveLogWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteDriveLogRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteDriveLog + * + * @param id ID of the Drive Log. + * @return RequestConfig + */ + fun deleteDriveLogRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/drive-logs/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /drive-logs:deleted + * List deleted Drive Logs + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return DeletedEntryPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchDeletedDriveLogs(lastModifiedAfter: java.time.OffsetDateTime? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: DeletedEntrySortColumn? = null) : DeletedEntryPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchDeletedDriveLogsWithHttpInfo(lastModifiedAfter = lastModifiedAfter, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DeletedEntryPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /drive-logs:deleted + * List deleted Drive Logs + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchDeletedDriveLogsWithHttpInfo(lastModifiedAfter: java.time.OffsetDateTime?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DeletedEntrySortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchDeletedDriveLogsRequestConfig(lastModifiedAfter = lastModifiedAfter, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchDeletedDriveLogs + * + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchDeletedDriveLogsRequestConfig(lastModifiedAfter: java.time.OffsetDateTime?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DeletedEntrySortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (lastModifiedAfter != null) { + put("last_modified_after", listOf(parseDateToQueryString(lastModifiedAfter))) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/drive-logs:deleted", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /drive-logs + * List Drive Logs + * Lists the Drive Logs the authenticated user or API token can access. + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param cars Only return entries recorded for these Cars. (optional) + * @param driveLogCategories Only return entries in these Drive Log Categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param details Only return Drive Logs whose route, purpose or visited contains this text. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param hasTrack Only return Drive Logs that have a Track (true) or have none (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return DriveLogsPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchDriveLogs(startFrom: java.time.LocalDate? = null, startTo: java.time.LocalDate? = null, lastModifiedAfter: java.time.OffsetDateTime? = null, cars: kotlin.collections.List? = null, driveLogCategories: kotlin.collections.List? = null, statuses: kotlin.collections.List? = null, users: kotlin.collections.List? = null, details: kotlin.String? = null, changed: kotlin.Boolean? = null, hasTrack: kotlin.Boolean? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: DriveLogsSortColumn? = null) : DriveLogsPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchDriveLogsWithHttpInfo(startFrom = startFrom, startTo = startTo, lastModifiedAfter = lastModifiedAfter, cars = cars, driveLogCategories = driveLogCategories, statuses = statuses, users = users, details = details, changed = changed, hasTrack = hasTrack, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DriveLogsPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /drive-logs + * List Drive Logs + * Lists the Drive Logs the authenticated user or API token can access. + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param cars Only return entries recorded for these Cars. (optional) + * @param driveLogCategories Only return entries in these Drive Log Categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param details Only return Drive Logs whose route, purpose or visited contains this text. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param hasTrack Only return Drive Logs that have a Track (true) or have none (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchDriveLogsWithHttpInfo(startFrom: java.time.LocalDate?, startTo: java.time.LocalDate?, lastModifiedAfter: java.time.OffsetDateTime?, cars: kotlin.collections.List?, driveLogCategories: kotlin.collections.List?, statuses: kotlin.collections.List?, users: kotlin.collections.List?, details: kotlin.String?, changed: kotlin.Boolean?, hasTrack: kotlin.Boolean?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DriveLogsSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchDriveLogsRequestConfig(startFrom = startFrom, startTo = startTo, lastModifiedAfter = lastModifiedAfter, cars = cars, driveLogCategories = driveLogCategories, statuses = statuses, users = users, details = details, changed = changed, hasTrack = hasTrack, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchDriveLogs + * + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param cars Only return entries recorded for these Cars. (optional) + * @param driveLogCategories Only return entries in these Drive Log Categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param details Only return Drive Logs whose route, purpose or visited contains this text. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param hasTrack Only return Drive Logs that have a Track (true) or have none (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchDriveLogsRequestConfig(startFrom: java.time.LocalDate?, startTo: java.time.LocalDate?, lastModifiedAfter: java.time.OffsetDateTime?, cars: kotlin.collections.List?, driveLogCategories: kotlin.collections.List?, statuses: kotlin.collections.List?, users: kotlin.collections.List?, details: kotlin.String?, changed: kotlin.Boolean?, hasTrack: kotlin.Boolean?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DriveLogsSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (startFrom != null) { + put("start_from", listOf(parseDateToQueryString(startFrom))) + } + if (startTo != null) { + put("start_to", listOf(parseDateToQueryString(startTo))) + } + if (lastModifiedAfter != null) { + put("last_modified_after", listOf(parseDateToQueryString(lastModifiedAfter))) + } + if (cars != null) { + put("cars", toMultiValue(cars.toList(), "multi")) + } + if (driveLogCategories != null) { + put("drive_log_categories", toMultiValue(driveLogCategories.toList(), "multi")) + } + if (statuses != null) { + put("statuses", toMultiValue(statuses.toList(), "multi")) + } + if (users != null) { + put("users", toMultiValue(users.toList(), "multi")) + } + if (details != null) { + put("details", listOf(details.toString())) + } + if (changed != null) { + put("changed", listOf(changed.toString())) + } + if (hasTrack != null) { + put("has_track", listOf(hasTrack.toString())) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/drive-logs", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /drive-logs/{id} + * Get a Drive Log + * Returns a single Drive Log by its ID. + * @param id ID of the Drive Log. + * @return DriveLog + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getDriveLog(id: kotlin.String) : DriveLog = withContext(Dispatchers.IO) { + val localVarResponse = getDriveLogWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DriveLog + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /drive-logs/{id} + * Get a Drive Log + * Returns a single Drive Log by its ID. + * @param id ID of the Drive Log. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getDriveLogWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getDriveLogRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getDriveLog + * + * @param id ID of the Drive Log. + * @return RequestConfig + */ + fun getDriveLogRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/drive-logs/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PATCH /drive-logs/{id} + * Update a Drive Log + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Drive Log. + * @param driveLogUpdate Drive Log entity + * @return DriveLog + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun updateDriveLog(id: kotlin.String, driveLogUpdate: DriveLogUpdate) : DriveLog = withContext(Dispatchers.IO) { + val localVarResponse = updateDriveLogWithHttpInfo(id = id, driveLogUpdate = driveLogUpdate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DriveLog + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PATCH /drive-logs/{id} + * Update a Drive Log + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Drive Log. + * @param driveLogUpdate Drive Log entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun updateDriveLogWithHttpInfo(id: kotlin.String, driveLogUpdate: DriveLogUpdate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = updateDriveLogRequestConfig(id = id, driveLogUpdate = driveLogUpdate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateDriveLog + * + * @param id ID of the Drive Log. + * @param driveLogUpdate Drive Log entity + * @return RequestConfig + */ + fun updateDriveLogRequestConfig(id: kotlin.String, driveLogUpdate: DriveLogUpdate) : RequestConfig { + val localVariableBody = driveLogUpdate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PATCH, + path = "/drive-logs/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/DriveLogCategoryApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/DriveLogCategoryApi.kt new file mode 100644 index 0000000..98061db --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/DriveLogCategoryApi.kt @@ -0,0 +1,234 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.DriveLogCategoriesPage +import com.timr.api.models.DriveLogCategoriesSortColumn +import com.timr.api.models.DriveLogCategory +import com.timr.api.models.Error +import com.timr.api.models.SortDirection + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class DriveLogCategoryApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * GET /drive-log-categories + * List Drive Log Categories + * Lists the Drive Log Categories the authenticated user or API token can access. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return DriveLogCategoriesPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchDriveLogCategories(pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: DriveLogCategoriesSortColumn? = null) : DriveLogCategoriesPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchDriveLogCategoriesWithHttpInfo(pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DriveLogCategoriesPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /drive-log-categories + * List Drive Log Categories + * Lists the Drive Log Categories the authenticated user or API token can access. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchDriveLogCategoriesWithHttpInfo(pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DriveLogCategoriesSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchDriveLogCategoriesRequestConfig(pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchDriveLogCategories + * + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchDriveLogCategoriesRequestConfig(pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DriveLogCategoriesSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/drive-log-categories", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /drive-log-categories/{id} + * Get a Drive Log Category + * Returns a single Drive Log Category by its ID. + * @param id ID of the Drive Log Category. + * @return DriveLogCategory + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getDriveLogCategory(id: kotlin.String) : DriveLogCategory = withContext(Dispatchers.IO) { + val localVarResponse = getDriveLogCategoryWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DriveLogCategory + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /drive-log-categories/{id} + * Get a Drive Log Category + * Returns a single Drive Log Category by its ID. + * @param id ID of the Drive Log Category. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getDriveLogCategoryWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getDriveLogCategoryRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getDriveLogCategory + * + * @param id ID of the Drive Log Category. + * @return RequestConfig + */ + fun getDriveLogCategoryRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/drive-log-categories/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/HolidayCalendarApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/HolidayCalendarApi.kt new file mode 100644 index 0000000..739699d --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/HolidayCalendarApi.kt @@ -0,0 +1,335 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Error +import com.timr.api.models.HolidayCalendarPartial +import com.timr.api.models.HolidayCalendarsPage +import com.timr.api.models.HolidayCalendarsSortColumn +import com.timr.api.models.HolidaysPage +import com.timr.api.models.HolidaysSortColumn +import com.timr.api.models.SortDirection + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class HolidayCalendarApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * GET /holiday-calendars + * List Holiday Calendars + * Lists the Holiday Calendars the authenticated user or API token can access. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return HolidayCalendarsPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchHolidayCalendars(pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: HolidayCalendarsSortColumn? = null) : HolidayCalendarsPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchHolidayCalendarsWithHttpInfo(pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as HolidayCalendarsPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /holiday-calendars + * List Holiday Calendars + * Lists the Holiday Calendars the authenticated user or API token can access. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchHolidayCalendarsWithHttpInfo(pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: HolidayCalendarsSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchHolidayCalendarsRequestConfig(pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchHolidayCalendars + * + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchHolidayCalendarsRequestConfig(pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: HolidayCalendarsSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/holiday-calendars", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /holiday-calendars/{id}/holidays + * List Holidays + * Lists the Holidays in the Holiday Calendar. + * @param id ID of the Holiday Calendar. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return HolidaysPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchHolidays(id: kotlin.String, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: HolidaysSortColumn? = null) : HolidaysPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchHolidaysWithHttpInfo(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as HolidaysPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /holiday-calendars/{id}/holidays + * List Holidays + * Lists the Holidays in the Holiday Calendar. + * @param id ID of the Holiday Calendar. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchHolidaysWithHttpInfo(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: HolidaysSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchHolidaysRequestConfig(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchHolidays + * + * @param id ID of the Holiday Calendar. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchHolidaysRequestConfig(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: HolidaysSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/holiday-calendars/{id}/holidays".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /holiday-calendars/{id} + * Get a Holiday Calendar + * Returns a single Holiday Calendar by its ID. + * @param id ID of the Holiday Calendar. + * @return HolidayCalendarPartial + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getHolidayCalendar(id: kotlin.String) : HolidayCalendarPartial = withContext(Dispatchers.IO) { + val localVarResponse = getHolidayCalendarWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as HolidayCalendarPartial + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /holiday-calendars/{id} + * Get a Holiday Calendar + * Returns a single Holiday Calendar by its ID. + * @param id ID of the Holiday Calendar. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getHolidayCalendarWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getHolidayCalendarRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getHolidayCalendar + * + * @param id ID of the Holiday Calendar. + * @return RequestConfig + */ + fun getHolidayCalendarRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/holiday-calendars/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/ProjectTimeApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/ProjectTimeApi.kt new file mode 100644 index 0000000..c826ca4 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/ProjectTimeApi.kt @@ -0,0 +1,623 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.DeletedEntrySortColumn +import com.timr.api.models.DeletedEntryWithMetadataPage +import com.timr.api.models.Error +import com.timr.api.models.ProjectTime +import com.timr.api.models.ProjectTimeCreate +import com.timr.api.models.ProjectTimeStatus +import com.timr.api.models.ProjectTimeUpdate +import com.timr.api.models.ProjectTimesPage +import com.timr.api.models.ProjectTimesSortColumn +import com.timr.api.models.SortDirection + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class ProjectTimeApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * POST /project-times + * Create a Project Time + * Creates a Project Time from the data in the request body. + * @param projectTimeCreate Project Time entity + * @return ProjectTime + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createProjectTime(projectTimeCreate: ProjectTimeCreate) : ProjectTime = withContext(Dispatchers.IO) { + val localVarResponse = createProjectTimeWithHttpInfo(projectTimeCreate = projectTimeCreate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as ProjectTime + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * POST /project-times + * Create a Project Time + * Creates a Project Time from the data in the request body. + * @param projectTimeCreate Project Time entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createProjectTimeWithHttpInfo(projectTimeCreate: ProjectTimeCreate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createProjectTimeRequestConfig(projectTimeCreate = projectTimeCreate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createProjectTime + * + * @param projectTimeCreate Project Time entity + * @return RequestConfig + */ + fun createProjectTimeRequestConfig(projectTimeCreate: ProjectTimeCreate) : RequestConfig { + val localVariableBody = projectTimeCreate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/project-times", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /project-times/{id} + * Delete a Project Time + * Deletes the Project Time. + * @param id ID of the Project Time. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteProjectTime(id: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteProjectTimeWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /project-times/{id} + * Delete a Project Time + * Deletes the Project Time. + * @param id ID of the Project Time. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteProjectTimeWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteProjectTimeRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteProjectTime + * + * @param id ID of the Project Time. + * @return RequestConfig + */ + fun deleteProjectTimeRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/project-times/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /project-times:deleted + * List deleted Project Times + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return DeletedEntryWithMetadataPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchDeletedProjectTimes(lastModifiedAfter: java.time.OffsetDateTime? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: DeletedEntrySortColumn? = null) : DeletedEntryWithMetadataPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchDeletedProjectTimesWithHttpInfo(lastModifiedAfter = lastModifiedAfter, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DeletedEntryWithMetadataPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /project-times:deleted + * List deleted Project Times + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchDeletedProjectTimesWithHttpInfo(lastModifiedAfter: java.time.OffsetDateTime?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DeletedEntrySortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchDeletedProjectTimesRequestConfig(lastModifiedAfter = lastModifiedAfter, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchDeletedProjectTimes + * + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchDeletedProjectTimesRequestConfig(lastModifiedAfter: java.time.OffsetDateTime?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DeletedEntrySortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (lastModifiedAfter != null) { + put("last_modified_after", listOf(parseDateToQueryString(lastModifiedAfter))) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/project-times:deleted", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /project-times + * List Project Times + * Lists the Project Times the authenticated user or API token can access. + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param task Only return entries recorded on the Task with this ID. (optional) + * @param traverseTaskTree Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ProjectTimesPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchProjectTimes(notes: kotlin.String? = null, startFrom: java.time.LocalDate? = null, startTo: java.time.LocalDate? = null, lastModifiedAfter: java.time.OffsetDateTime? = null, task: kotlin.String? = null, traverseTaskTree: kotlin.Boolean? = true, billable: kotlin.Boolean? = null, statuses: kotlin.collections.List? = null, users: kotlin.collections.List? = null, changed: kotlin.Boolean? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: ProjectTimesSortColumn? = null) : ProjectTimesPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchProjectTimesWithHttpInfo(notes = notes, startFrom = startFrom, startTo = startTo, lastModifiedAfter = lastModifiedAfter, task = task, traverseTaskTree = traverseTaskTree, billable = billable, statuses = statuses, users = users, changed = changed, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as ProjectTimesPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /project-times + * List Project Times + * Lists the Project Times the authenticated user or API token can access. + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param task Only return entries recorded on the Task with this ID. (optional) + * @param traverseTaskTree Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchProjectTimesWithHttpInfo(notes: kotlin.String?, startFrom: java.time.LocalDate?, startTo: java.time.LocalDate?, lastModifiedAfter: java.time.OffsetDateTime?, task: kotlin.String?, traverseTaskTree: kotlin.Boolean?, billable: kotlin.Boolean?, statuses: kotlin.collections.List?, users: kotlin.collections.List?, changed: kotlin.Boolean?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: ProjectTimesSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchProjectTimesRequestConfig(notes = notes, startFrom = startFrom, startTo = startTo, lastModifiedAfter = lastModifiedAfter, task = task, traverseTaskTree = traverseTaskTree, billable = billable, statuses = statuses, users = users, changed = changed, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchProjectTimes + * + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param task Only return entries recorded on the Task with this ID. (optional) + * @param traverseTaskTree Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchProjectTimesRequestConfig(notes: kotlin.String?, startFrom: java.time.LocalDate?, startTo: java.time.LocalDate?, lastModifiedAfter: java.time.OffsetDateTime?, task: kotlin.String?, traverseTaskTree: kotlin.Boolean?, billable: kotlin.Boolean?, statuses: kotlin.collections.List?, users: kotlin.collections.List?, changed: kotlin.Boolean?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: ProjectTimesSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (notes != null) { + put("notes", listOf(notes.toString())) + } + if (startFrom != null) { + put("start_from", listOf(parseDateToQueryString(startFrom))) + } + if (startTo != null) { + put("start_to", listOf(parseDateToQueryString(startTo))) + } + if (lastModifiedAfter != null) { + put("last_modified_after", listOf(parseDateToQueryString(lastModifiedAfter))) + } + if (task != null) { + put("task", listOf(task.toString())) + } + if (traverseTaskTree != null) { + put("traverse_task_tree", listOf(traverseTaskTree.toString())) + } + if (billable != null) { + put("billable", listOf(billable.toString())) + } + if (statuses != null) { + put("statuses", toMultiValue(statuses.toList(), "multi")) + } + if (users != null) { + put("users", toMultiValue(users.toList(), "multi")) + } + if (changed != null) { + put("changed", listOf(changed.toString())) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/project-times", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /project-times/{id} + * Get a Project Time + * Returns a single Project Time by its ID. + * @param id ID of the Project Time. + * @return ProjectTime + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getProjectTime(id: kotlin.String) : ProjectTime = withContext(Dispatchers.IO) { + val localVarResponse = getProjectTimeWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as ProjectTime + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /project-times/{id} + * Get a Project Time + * Returns a single Project Time by its ID. + * @param id ID of the Project Time. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getProjectTimeWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getProjectTimeRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getProjectTime + * + * @param id ID of the Project Time. + * @return RequestConfig + */ + fun getProjectTimeRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/project-times/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PATCH /project-times/{id} + * Update a Project Time + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Project Time. + * @param projectTimeUpdate Project Time entity + * @return ProjectTime + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun updateProjectTime(id: kotlin.String, projectTimeUpdate: ProjectTimeUpdate) : ProjectTime = withContext(Dispatchers.IO) { + val localVarResponse = updateProjectTimeWithHttpInfo(id = id, projectTimeUpdate = projectTimeUpdate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as ProjectTime + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PATCH /project-times/{id} + * Update a Project Time + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Project Time. + * @param projectTimeUpdate Project Time entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun updateProjectTimeWithHttpInfo(id: kotlin.String, projectTimeUpdate: ProjectTimeUpdate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = updateProjectTimeRequestConfig(id = id, projectTimeUpdate = projectTimeUpdate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateProjectTime + * + * @param id ID of the Project Time. + * @param projectTimeUpdate Project Time entity + * @return RequestConfig + */ + fun updateProjectTimeRequestConfig(id: kotlin.String, projectTimeUpdate: ProjectTimeUpdate) : RequestConfig { + val localVariableBody = projectTimeUpdate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PATCH, + path = "/project-times/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskApi.kt new file mode 100644 index 0000000..1e7b73e --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskApi.kt @@ -0,0 +1,559 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Error +import com.timr.api.models.SortDirection +import com.timr.api.models.Task +import com.timr.api.models.TaskCreate +import com.timr.api.models.TaskUpdate +import com.timr.api.models.TasksPage +import com.timr.api.models.TasksReducedPage +import com.timr.api.models.TasksSortColumn + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class TaskApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * POST /tasks + * Create a Task + * Creates a Task from the data in the request body. + * @param taskCreate Project Time entity + * @return Task + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createTask(taskCreate: TaskCreate) : Task = withContext(Dispatchers.IO) { + val localVarResponse = createTaskWithHttpInfo(taskCreate = taskCreate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Task + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * POST /tasks + * Create a Task + * Creates a Task from the data in the request body. + * @param taskCreate Project Time entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createTaskWithHttpInfo(taskCreate: TaskCreate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createTaskRequestConfig(taskCreate = taskCreate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createTask + * + * @param taskCreate Project Time entity + * @return RequestConfig + */ + fun createTaskRequestConfig(taskCreate: TaskCreate) : RequestConfig { + val localVariableBody = taskCreate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/tasks", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /tasks + * List Tasks + * Lists the Tasks the authenticated user or API token can access. + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return TasksPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchTasks(parentTaskId: kotlin.String? = null, traverseTaskTree: kotlin.Boolean? = true, name: kotlin.String? = null, bookable: kotlin.Boolean? = null, billable: kotlin.Boolean? = null, activeAt: java.time.LocalDate? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: TasksSortColumn? = null) : TasksPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchTasksWithHttpInfo(parentTaskId = parentTaskId, traverseTaskTree = traverseTaskTree, name = name, bookable = bookable, billable = billable, activeAt = activeAt, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TasksPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /tasks + * List Tasks + * Lists the Tasks the authenticated user or API token can access. + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchTasksWithHttpInfo(parentTaskId: kotlin.String?, traverseTaskTree: kotlin.Boolean?, name: kotlin.String?, bookable: kotlin.Boolean?, billable: kotlin.Boolean?, activeAt: java.time.LocalDate?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TasksSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchTasksRequestConfig(parentTaskId = parentTaskId, traverseTaskTree = traverseTaskTree, name = name, bookable = bookable, billable = billable, activeAt = activeAt, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchTasks + * + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchTasksRequestConfig(parentTaskId: kotlin.String?, traverseTaskTree: kotlin.Boolean?, name: kotlin.String?, bookable: kotlin.Boolean?, billable: kotlin.Boolean?, activeAt: java.time.LocalDate?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TasksSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (parentTaskId != null) { + put("parent_task_id", listOf(parentTaskId.toString())) + } + if (traverseTaskTree != null) { + put("traverse_task_tree", listOf(traverseTaskTree.toString())) + } + if (name != null) { + put("name", listOf(name.toString())) + } + if (bookable != null) { + put("bookable", listOf(bookable.toString())) + } + if (billable != null) { + put("billable", listOf(billable.toString())) + } + if (activeAt != null) { + put("active_at", listOf(activeAt.toString())) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/tasks", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /users/{id}/tasks + * List a User's Tasks + * Lists the Tasks the User is assigned to and may record on. + * @param id ID of the User. + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return TasksReducedPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchUserTasks(id: kotlin.String, parentTaskId: kotlin.String? = null, traverseTaskTree: kotlin.Boolean? = true, name: kotlin.String? = null, bookable: kotlin.Boolean? = null, billable: kotlin.Boolean? = null, activeAt: java.time.LocalDate? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: TasksSortColumn? = null) : TasksReducedPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchUserTasksWithHttpInfo(id = id, parentTaskId = parentTaskId, traverseTaskTree = traverseTaskTree, name = name, bookable = bookable, billable = billable, activeAt = activeAt, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TasksReducedPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /users/{id}/tasks + * List a User's Tasks + * Lists the Tasks the User is assigned to and may record on. + * @param id ID of the User. + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchUserTasksWithHttpInfo(id: kotlin.String, parentTaskId: kotlin.String?, traverseTaskTree: kotlin.Boolean?, name: kotlin.String?, bookable: kotlin.Boolean?, billable: kotlin.Boolean?, activeAt: java.time.LocalDate?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TasksSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchUserTasksRequestConfig(id = id, parentTaskId = parentTaskId, traverseTaskTree = traverseTaskTree, name = name, bookable = bookable, billable = billable, activeAt = activeAt, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchUserTasks + * + * @param id ID of the User. + * @param parentTaskId Only return Tasks whose parent is the Task with this ID. (optional) + * @param traverseTaskTree Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + * @param name Only return Users whose name contains this text. (optional) + * @param bookable Only return entries that are billable (true) or not billable (false). (optional) + * @param billable Only return entries that are billable (true) or not billable (false). (optional) + * @param activeAt Only return Tasks that are active on this day. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchUserTasksRequestConfig(id: kotlin.String, parentTaskId: kotlin.String?, traverseTaskTree: kotlin.Boolean?, name: kotlin.String?, bookable: kotlin.Boolean?, billable: kotlin.Boolean?, activeAt: java.time.LocalDate?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TasksSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (parentTaskId != null) { + put("parent_task_id", listOf(parentTaskId.toString())) + } + if (traverseTaskTree != null) { + put("traverse_task_tree", listOf(traverseTaskTree.toString())) + } + if (name != null) { + put("name", listOf(name.toString())) + } + if (bookable != null) { + put("bookable", listOf(bookable.toString())) + } + if (billable != null) { + put("billable", listOf(billable.toString())) + } + if (activeAt != null) { + put("active_at", listOf(activeAt.toString())) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/users/{id}/tasks".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /tasks/{id} + * Get a Task + * Returns a single Task by its ID. + * @param id ID of the Task. + * @return Task + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getTask(id: kotlin.String) : Task = withContext(Dispatchers.IO) { + val localVarResponse = getTaskWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Task + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /tasks/{id} + * Get a Task + * Returns a single Task by its ID. + * @param id ID of the Task. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getTaskWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getTaskRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getTask + * + * @param id ID of the Task. + * @return RequestConfig + */ + fun getTaskRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/tasks/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PATCH /tasks/{id} + * Update a Task + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Task. + * @param taskUpdate Task entity + * @return Task + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun updateTask(id: kotlin.String, taskUpdate: TaskUpdate) : Task = withContext(Dispatchers.IO) { + val localVarResponse = updateTaskWithHttpInfo(id = id, taskUpdate = taskUpdate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Task + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PATCH /tasks/{id} + * Update a Task + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Task. + * @param taskUpdate Task entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun updateTaskWithHttpInfo(id: kotlin.String, taskUpdate: TaskUpdate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = updateTaskRequestConfig(id = id, taskUpdate = taskUpdate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateTask + * + * @param id ID of the Task. + * @param taskUpdate Task entity + * @return RequestConfig + */ + fun updateTaskRequestConfig(id: kotlin.String, taskUpdate: TaskUpdate) : RequestConfig { + val localVariableBody = taskUpdate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PATCH, + path = "/tasks/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskToLeaderAssignmentApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskToLeaderAssignmentApi.kt new file mode 100644 index 0000000..f891e99 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskToLeaderAssignmentApi.kt @@ -0,0 +1,390 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Error +import com.timr.api.models.SortDirection +import com.timr.api.models.TaskToLeaderAssignment +import com.timr.api.models.TaskToLeaderAssignmentsPage +import com.timr.api.models.TaskToLeaderAssignmentsSortColumn + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class TaskToLeaderAssignmentApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * PUT /tasks/{task_id}/leaders/{user_id} + * Create a Task to Leader Assignment + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return TaskToLeaderAssignment + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createTaskToLeaderAssignment(taskId: kotlin.String, userId: kotlin.String) : TaskToLeaderAssignment = withContext(Dispatchers.IO) { + val localVarResponse = createTaskToLeaderAssignmentWithHttpInfo(taskId = taskId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TaskToLeaderAssignment + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PUT /tasks/{task_id}/leaders/{user_id} + * Create a Task to Leader Assignment + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createTaskToLeaderAssignmentWithHttpInfo(taskId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createTaskToLeaderAssignmentRequestConfig(taskId = taskId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createTaskToLeaderAssignment + * + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return RequestConfig + */ + fun createTaskToLeaderAssignmentRequestConfig(taskId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PUT, + path = "/tasks/{task_id}/leaders/{user_id}".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /tasks/{task_id}/leaders/{user_id} + * Delete a Task to Leader Assignment + * Removes the User's leader assignment to the Task. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteTaskToLeaderAssignment(taskId: kotlin.String, userId: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteTaskToLeaderAssignmentWithHttpInfo(taskId = taskId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /tasks/{task_id}/leaders/{user_id} + * Delete a Task to Leader Assignment + * Removes the User's leader assignment to the Task. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteTaskToLeaderAssignmentWithHttpInfo(taskId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteTaskToLeaderAssignmentRequestConfig(taskId = taskId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteTaskToLeaderAssignment + * + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return RequestConfig + */ + fun deleteTaskToLeaderAssignmentRequestConfig(taskId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/tasks/{task_id}/leaders/{user_id}".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /tasks/{task_id}/leaders + * List Task to Leader Assignments + * Lists the Users assigned to the Task as leaders. + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return TaskToLeaderAssignmentsPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchTaskToLeaderAssignments(taskId: kotlin.String, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: TaskToLeaderAssignmentsSortColumn? = null) : TaskToLeaderAssignmentsPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchTaskToLeaderAssignmentsWithHttpInfo(taskId = taskId, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TaskToLeaderAssignmentsPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /tasks/{task_id}/leaders + * List Task to Leader Assignments + * Lists the Users assigned to the Task as leaders. + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchTaskToLeaderAssignmentsWithHttpInfo(taskId: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TaskToLeaderAssignmentsSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchTaskToLeaderAssignmentsRequestConfig(taskId = taskId, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchTaskToLeaderAssignments + * + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchTaskToLeaderAssignmentsRequestConfig(taskId: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TaskToLeaderAssignmentsSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/tasks/{task_id}/leaders".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /tasks/{task_id}/leaders/{user_id} + * Get a Task to Leader Assignment + * Returns the leader assignment of a single User to the Task. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return TaskToLeaderAssignment + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getTaskToLeaderAssignment(taskId: kotlin.String, userId: kotlin.String) : TaskToLeaderAssignment = withContext(Dispatchers.IO) { + val localVarResponse = getTaskToLeaderAssignmentWithHttpInfo(taskId = taskId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TaskToLeaderAssignment + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /tasks/{task_id}/leaders/{user_id} + * Get a Task to Leader Assignment + * Returns the leader assignment of a single User to the Task. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getTaskToLeaderAssignmentWithHttpInfo(taskId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getTaskToLeaderAssignmentRequestConfig(taskId = taskId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getTaskToLeaderAssignment + * + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return RequestConfig + */ + fun getTaskToLeaderAssignmentRequestConfig(taskId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/tasks/{task_id}/leaders/{user_id}".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskToTeamAssignmentApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskToTeamAssignmentApi.kt new file mode 100644 index 0000000..7e3fc2d --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskToTeamAssignmentApi.kt @@ -0,0 +1,390 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Error +import com.timr.api.models.SortDirection +import com.timr.api.models.TaskToTeamAssignment +import com.timr.api.models.TaskToTeamAssignmentsPage +import com.timr.api.models.TaskToTeamAssignmentsSortColumn + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class TaskToTeamAssignmentApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * PUT /tasks/{task_id}/teams/{team_id} + * Create a Task to Team Assignment + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return TaskToTeamAssignment + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createTaskToTeamAssignment(taskId: kotlin.String, teamId: kotlin.String) : TaskToTeamAssignment = withContext(Dispatchers.IO) { + val localVarResponse = createTaskToTeamAssignmentWithHttpInfo(taskId = taskId, teamId = teamId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TaskToTeamAssignment + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PUT /tasks/{task_id}/teams/{team_id} + * Create a Task to Team Assignment + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createTaskToTeamAssignmentWithHttpInfo(taskId: kotlin.String, teamId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createTaskToTeamAssignmentRequestConfig(taskId = taskId, teamId = teamId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createTaskToTeamAssignment + * + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return RequestConfig + */ + fun createTaskToTeamAssignmentRequestConfig(taskId: kotlin.String, teamId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PUT, + path = "/tasks/{task_id}/teams/{team_id}".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())).replace("{"+"team_id"+"}", encodeURIComponent(teamId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /tasks/{task_id}/teams/{team_id} + * Delete a Task to Team Assignment + * Removes the Team's assignment to the Task. + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteTaskToTeamAssignment(taskId: kotlin.String, teamId: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteTaskToTeamAssignmentWithHttpInfo(taskId = taskId, teamId = teamId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /tasks/{task_id}/teams/{team_id} + * Delete a Task to Team Assignment + * Removes the Team's assignment to the Task. + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteTaskToTeamAssignmentWithHttpInfo(taskId: kotlin.String, teamId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteTaskToTeamAssignmentRequestConfig(taskId = taskId, teamId = teamId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteTaskToTeamAssignment + * + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return RequestConfig + */ + fun deleteTaskToTeamAssignmentRequestConfig(taskId: kotlin.String, teamId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/tasks/{task_id}/teams/{team_id}".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())).replace("{"+"team_id"+"}", encodeURIComponent(teamId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /tasks/{task_id}/teams + * List Task to Team Assignments + * Lists the Teams assigned to the Task. + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return TaskToTeamAssignmentsPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchTaskToTeamAssignments(taskId: kotlin.String, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: TaskToTeamAssignmentsSortColumn? = null) : TaskToTeamAssignmentsPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchTaskToTeamAssignmentsWithHttpInfo(taskId = taskId, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TaskToTeamAssignmentsPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /tasks/{task_id}/teams + * List Task to Team Assignments + * Lists the Teams assigned to the Task. + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchTaskToTeamAssignmentsWithHttpInfo(taskId: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TaskToTeamAssignmentsSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchTaskToTeamAssignmentsRequestConfig(taskId = taskId, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchTaskToTeamAssignments + * + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchTaskToTeamAssignmentsRequestConfig(taskId: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TaskToTeamAssignmentsSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/tasks/{task_id}/teams".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /tasks/{task_id}/teams/{team_id} + * Get a Task to Team Assignment + * Returns the assignment of a single Team to the Task. + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return TaskToTeamAssignment + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getTaskToTeamAssignment(taskId: kotlin.String, teamId: kotlin.String) : TaskToTeamAssignment = withContext(Dispatchers.IO) { + val localVarResponse = getTaskToTeamAssignmentWithHttpInfo(taskId = taskId, teamId = teamId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TaskToTeamAssignment + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /tasks/{task_id}/teams/{team_id} + * Get a Task to Team Assignment + * Returns the assignment of a single Team to the Task. + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getTaskToTeamAssignmentWithHttpInfo(taskId: kotlin.String, teamId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getTaskToTeamAssignmentRequestConfig(taskId = taskId, teamId = teamId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getTaskToTeamAssignment + * + * @param taskId ID of the Task. + * @param teamId ID of the Team. + * @return RequestConfig + */ + fun getTaskToTeamAssignmentRequestConfig(taskId: kotlin.String, teamId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/tasks/{task_id}/teams/{team_id}".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())).replace("{"+"team_id"+"}", encodeURIComponent(teamId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskToUserAssignmentApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskToUserAssignmentApi.kt new file mode 100644 index 0000000..bc6f8cb --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskToUserAssignmentApi.kt @@ -0,0 +1,395 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Error +import com.timr.api.models.SortDirection +import com.timr.api.models.TaskToUserAssignment +import com.timr.api.models.TaskToUserAssignmentUpsert +import com.timr.api.models.TaskToUserAssignmentsPage +import com.timr.api.models.TaskToUserAssignmentsSortColumn + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class TaskToUserAssignmentApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * DELETE /tasks/{task_id}/users/{user_id} + * Delete a Task to User Assignment + * Removes the User's assignment to the Task. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteTaskToUserAssignment(taskId: kotlin.String, userId: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteTaskToUserAssignmentWithHttpInfo(taskId = taskId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /tasks/{task_id}/users/{user_id} + * Delete a Task to User Assignment + * Removes the User's assignment to the Task. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteTaskToUserAssignmentWithHttpInfo(taskId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteTaskToUserAssignmentRequestConfig(taskId = taskId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteTaskToUserAssignment + * + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return RequestConfig + */ + fun deleteTaskToUserAssignmentRequestConfig(taskId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/tasks/{task_id}/users/{user_id}".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /tasks/{task_id}/users + * List Task to User Assignments + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return TaskToUserAssignmentsPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchTaskToUserAssignments(taskId: kotlin.String, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: TaskToUserAssignmentsSortColumn? = null) : TaskToUserAssignmentsPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchTaskToUserAssignmentsWithHttpInfo(taskId = taskId, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TaskToUserAssignmentsPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /tasks/{task_id}/users + * List Task to User Assignments + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchTaskToUserAssignmentsWithHttpInfo(taskId: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TaskToUserAssignmentsSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchTaskToUserAssignmentsRequestConfig(taskId = taskId, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchTaskToUserAssignments + * + * @param taskId ID of the Task. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchTaskToUserAssignmentsRequestConfig(taskId: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TaskToUserAssignmentsSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/tasks/{task_id}/users".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /tasks/{task_id}/users/{user_id} + * Get a Task to User Assignment + * Returns the assignment of a single User to the Task. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return TaskToUserAssignment + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getTaskToUserAssignment(taskId: kotlin.String, userId: kotlin.String) : TaskToUserAssignment = withContext(Dispatchers.IO) { + val localVarResponse = getTaskToUserAssignmentWithHttpInfo(taskId = taskId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TaskToUserAssignment + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /tasks/{task_id}/users/{user_id} + * Get a Task to User Assignment + * Returns the assignment of a single User to the Task. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getTaskToUserAssignmentWithHttpInfo(taskId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getTaskToUserAssignmentRequestConfig(taskId = taskId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getTaskToUserAssignment + * + * @param taskId ID of the Task. + * @param userId ID of the User. + * @return RequestConfig + */ + fun getTaskToUserAssignmentRequestConfig(taskId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/tasks/{task_id}/users/{user_id}".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PUT /tasks/{task_id}/users/{user_id} + * Create or update a Task to User Assignment + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @param taskToUserAssignmentUpsert Task to User Assignment entity + * @return TaskToUserAssignment + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun upsertTaskToUserAssignment(taskId: kotlin.String, userId: kotlin.String, taskToUserAssignmentUpsert: TaskToUserAssignmentUpsert) : TaskToUserAssignment = withContext(Dispatchers.IO) { + val localVarResponse = upsertTaskToUserAssignmentWithHttpInfo(taskId = taskId, userId = userId, taskToUserAssignmentUpsert = taskToUserAssignmentUpsert) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TaskToUserAssignment + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PUT /tasks/{task_id}/users/{user_id} + * Create or update a Task to User Assignment + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + * @param taskId ID of the Task. + * @param userId ID of the User. + * @param taskToUserAssignmentUpsert Task to User Assignment entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun upsertTaskToUserAssignmentWithHttpInfo(taskId: kotlin.String, userId: kotlin.String, taskToUserAssignmentUpsert: TaskToUserAssignmentUpsert) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = upsertTaskToUserAssignmentRequestConfig(taskId = taskId, userId = userId, taskToUserAssignmentUpsert = taskToUserAssignmentUpsert) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation upsertTaskToUserAssignment + * + * @param taskId ID of the Task. + * @param userId ID of the User. + * @param taskToUserAssignmentUpsert Task to User Assignment entity + * @return RequestConfig + */ + fun upsertTaskToUserAssignmentRequestConfig(taskId: kotlin.String, userId: kotlin.String, taskToUserAssignmentUpsert: TaskToUserAssignmentUpsert) : RequestConfig { + val localVariableBody = taskToUserAssignmentUpsert + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PUT, + path = "/tasks/{task_id}/users/{user_id}".replace("{"+"task_id"+"}", encodeURIComponent(taskId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TeamApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TeamApi.kt new file mode 100644 index 0000000..82ad25f --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TeamApi.kt @@ -0,0 +1,1117 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Error +import com.timr.api.models.SortDirection +import com.timr.api.models.Team +import com.timr.api.models.TeamCreate +import com.timr.api.models.TeamUpdate +import com.timr.api.models.TeamsPage +import com.timr.api.models.TeamsSortColumn +import com.timr.api.models.UserPartial +import com.timr.api.models.UsersPartialPage +import com.timr.api.models.UsersSortColumn + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class TeamApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * PUT /teams/{team_id}/leaders/{user_id} + * Add a Team Leader + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun addTeamLeader(teamId: kotlin.String, userId: kotlin.String) : UserPartial = withContext(Dispatchers.IO) { + val localVarResponse = addTeamLeaderWithHttpInfo(teamId = teamId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as UserPartial + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PUT /teams/{team_id}/leaders/{user_id} + * Add a Team Leader + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun addTeamLeaderWithHttpInfo(teamId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = addTeamLeaderRequestConfig(teamId = teamId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation addTeamLeader + * + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return RequestConfig + */ + fun addTeamLeaderRequestConfig(teamId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PUT, + path = "/teams/{team_id}/leaders/{user_id}".replace("{"+"team_id"+"}", encodeURIComponent(teamId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PUT /teams/{team_id}/members/{user_id} + * Add a Team Member + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun addTeamMember(teamId: kotlin.String, userId: kotlin.String) : UserPartial = withContext(Dispatchers.IO) { + val localVarResponse = addTeamMemberWithHttpInfo(teamId = teamId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as UserPartial + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PUT /teams/{team_id}/members/{user_id} + * Add a Team Member + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun addTeamMemberWithHttpInfo(teamId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = addTeamMemberRequestConfig(teamId = teamId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation addTeamMember + * + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return RequestConfig + */ + fun addTeamMemberRequestConfig(teamId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PUT, + path = "/teams/{team_id}/members/{user_id}".replace("{"+"team_id"+"}", encodeURIComponent(teamId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * POST /teams + * Create a Team + * Creates a Team from the data in the request body. + * @param teamCreate Team entity + * @return Team + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createTeam(teamCreate: TeamCreate) : Team = withContext(Dispatchers.IO) { + val localVarResponse = createTeamWithHttpInfo(teamCreate = teamCreate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Team + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * POST /teams + * Create a Team + * Creates a Team from the data in the request body. + * @param teamCreate Team entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createTeamWithHttpInfo(teamCreate: TeamCreate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createTeamRequestConfig(teamCreate = teamCreate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createTeam + * + * @param teamCreate Team entity + * @return RequestConfig + */ + fun createTeamRequestConfig(teamCreate: TeamCreate) : RequestConfig { + val localVariableBody = teamCreate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/teams", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /teams/{id} + * Delete a Team + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + * @param id ID of the Team. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteTeam(id: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteTeamWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /teams/{id} + * Delete a Team + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + * @param id ID of the Team. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteTeamWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteTeamRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteTeam + * + * @param id ID of the Team. + * @return RequestConfig + */ + fun deleteTeamRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/teams/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /teams/{id}/leaders + * List Team Leaders + * Lists the Users who lead the Team. + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return UsersPartialPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchTeamLeaders(id: kotlin.String, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: UsersSortColumn? = null) : UsersPartialPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchTeamLeadersWithHttpInfo(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as UsersPartialPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /teams/{id}/leaders + * List Team Leaders + * Lists the Users who lead the Team. + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchTeamLeadersWithHttpInfo(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: UsersSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchTeamLeadersRequestConfig(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchTeamLeaders + * + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchTeamLeadersRequestConfig(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: UsersSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/teams/{id}/leaders".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /teams/{id}/members + * List Team Members + * Lists the Users who are members of the Team. + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return UsersPartialPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchTeamMembers(id: kotlin.String, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: UsersSortColumn? = null) : UsersPartialPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchTeamMembersWithHttpInfo(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as UsersPartialPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /teams/{id}/members + * List Team Members + * Lists the Users who are members of the Team. + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchTeamMembersWithHttpInfo(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: UsersSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchTeamMembersRequestConfig(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchTeamMembers + * + * @param id ID of the Team. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchTeamMembersRequestConfig(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: UsersSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/teams/{id}/members".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /teams + * List Teams + * Lists the Teams the authenticated user or API token can access. + * @param name Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return TeamsPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchTeams(name: kotlin.String? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: TeamsSortColumn? = null) : TeamsPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchTeamsWithHttpInfo(name = name, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TeamsPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /teams + * List Teams + * Lists the Teams the authenticated user or API token can access. + * @param name Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchTeamsWithHttpInfo(name: kotlin.String?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TeamsSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchTeamsRequestConfig(name = name, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchTeams + * + * @param name Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchTeamsRequestConfig(name: kotlin.String?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TeamsSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (name != null) { + put("name", listOf(name.toString())) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/teams", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /teams/{id} + * Get a Team + * Returns a single Team by its ID. + * @param id ID of the Team. + * @return Team + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getTeam(id: kotlin.String) : Team = withContext(Dispatchers.IO) { + val localVarResponse = getTeamWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Team + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /teams/{id} + * Get a Team + * Returns a single Team by its ID. + * @param id ID of the Team. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getTeamWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getTeamRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getTeam + * + * @param id ID of the Team. + * @return RequestConfig + */ + fun getTeamRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/teams/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /teams/{team_id}/leaders/{user_id} + * Get a Team Leader + * Returns the leadership of a single User in the Team. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getTeamLeader(teamId: kotlin.String, userId: kotlin.String) : UserPartial = withContext(Dispatchers.IO) { + val localVarResponse = getTeamLeaderWithHttpInfo(teamId = teamId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as UserPartial + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /teams/{team_id}/leaders/{user_id} + * Get a Team Leader + * Returns the leadership of a single User in the Team. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getTeamLeaderWithHttpInfo(teamId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getTeamLeaderRequestConfig(teamId = teamId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getTeamLeader + * + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return RequestConfig + */ + fun getTeamLeaderRequestConfig(teamId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/teams/{team_id}/leaders/{user_id}".replace("{"+"team_id"+"}", encodeURIComponent(teamId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /teams/{team_id}/members/{user_id} + * Get a Team Member + * Returns the membership of a single User in the Team. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return UserPartial + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getTeamMember(teamId: kotlin.String, userId: kotlin.String) : UserPartial = withContext(Dispatchers.IO) { + val localVarResponse = getTeamMemberWithHttpInfo(teamId = teamId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as UserPartial + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /teams/{team_id}/members/{user_id} + * Get a Team Member + * Returns the membership of a single User in the Team. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getTeamMemberWithHttpInfo(teamId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getTeamMemberRequestConfig(teamId = teamId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getTeamMember + * + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return RequestConfig + */ + fun getTeamMemberRequestConfig(teamId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/teams/{team_id}/members/{user_id}".replace("{"+"team_id"+"}", encodeURIComponent(teamId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /teams/{team_id}/leaders/{user_id} + * Remove a Team Leader + * Removes the User's leadership of the Team. The User itself is not deleted. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun removeTeamLeader(teamId: kotlin.String, userId: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = removeTeamLeaderWithHttpInfo(teamId = teamId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /teams/{team_id}/leaders/{user_id} + * Remove a Team Leader + * Removes the User's leadership of the Team. The User itself is not deleted. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun removeTeamLeaderWithHttpInfo(teamId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = removeTeamLeaderRequestConfig(teamId = teamId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation removeTeamLeader + * + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return RequestConfig + */ + fun removeTeamLeaderRequestConfig(teamId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/teams/{team_id}/leaders/{user_id}".replace("{"+"team_id"+"}", encodeURIComponent(teamId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /teams/{team_id}/members/{user_id} + * Remove a Team Member + * Removes the User's membership in the Team. The User itself is not deleted. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun removeTeamMember(teamId: kotlin.String, userId: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = removeTeamMemberWithHttpInfo(teamId = teamId, userId = userId) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /teams/{team_id}/members/{user_id} + * Remove a Team Member + * Removes the User's membership in the Team. The User itself is not deleted. + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun removeTeamMemberWithHttpInfo(teamId: kotlin.String, userId: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = removeTeamMemberRequestConfig(teamId = teamId, userId = userId) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation removeTeamMember + * + * @param teamId ID of the Team. + * @param userId ID of the User. + * @return RequestConfig + */ + fun removeTeamMemberRequestConfig(teamId: kotlin.String, userId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/teams/{team_id}/members/{user_id}".replace("{"+"team_id"+"}", encodeURIComponent(teamId.toString())).replace("{"+"user_id"+"}", encodeURIComponent(userId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PATCH /teams/{id} + * Update a Team + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Team. + * @param teamUpdate Team entity + * @return Team + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun updateTeam(id: kotlin.String, teamUpdate: TeamUpdate) : Team = withContext(Dispatchers.IO) { + val localVarResponse = updateTeamWithHttpInfo(id = id, teamUpdate = teamUpdate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Team + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PATCH /teams/{id} + * Update a Team + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Team. + * @param teamUpdate Team entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun updateTeamWithHttpInfo(id: kotlin.String, teamUpdate: TeamUpdate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = updateTeamRequestConfig(id = id, teamUpdate = teamUpdate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateTeam + * + * @param id ID of the Team. + * @param teamUpdate Team entity + * @return RequestConfig + */ + fun updateTeamRequestConfig(id: kotlin.String, teamUpdate: TeamUpdate) : RequestConfig { + val localVariableBody = teamUpdate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PATCH, + path = "/teams/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TimeAccountApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TimeAccountApi.kt new file mode 100644 index 0000000..8a12b84 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TimeAccountApi.kt @@ -0,0 +1,214 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Accounts +import com.timr.api.models.Error + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class TimeAccountApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * GET /users/{id}/accounts/{date} + * Get a User's accounts + * Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + * @param id ID of the User. + * @param date Day to return the balances for. + * @return Accounts + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getUserAccounts(id: kotlin.String, date: java.time.LocalDate) : Accounts = withContext(Dispatchers.IO) { + val localVarResponse = getUserAccountsWithHttpInfo(id = id, date = date) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Accounts + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /users/{id}/accounts/{date} + * Get a User's accounts + * Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + * @param id ID of the User. + * @param date Day to return the balances for. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getUserAccountsWithHttpInfo(id: kotlin.String, date: java.time.LocalDate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getUserAccountsRequestConfig(id = id, date = date) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getUserAccounts + * + * @param id ID of the User. + * @param date Day to return the balances for. + * @return RequestConfig + */ + fun getUserAccountsRequestConfig(id: kotlin.String, date: java.time.LocalDate) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/users/{id}/accounts/{date}".replace("{"+"id"+"}", encodeURIComponent(id.toString())).replace("{"+"date"+"}", encodeURIComponent(date.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /users/{id}/working-time-accounts/{date} + * Get a User's working time accounts + * Returns the User's working time account balances as of the given day. + * @param id ID of the User. + * @param date Day to return the balances for. + * @return Accounts + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getUserWorkingTimeAccounts(id: kotlin.String, date: java.time.LocalDate) : Accounts = withContext(Dispatchers.IO) { + val localVarResponse = getUserWorkingTimeAccountsWithHttpInfo(id = id, date = date) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Accounts + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /users/{id}/working-time-accounts/{date} + * Get a User's working time accounts + * Returns the User's working time account balances as of the given day. + * @param id ID of the User. + * @param date Day to return the balances for. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getUserWorkingTimeAccountsWithHttpInfo(id: kotlin.String, date: java.time.LocalDate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getUserWorkingTimeAccountsRequestConfig(id = id, date = date) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getUserWorkingTimeAccounts + * + * @param id ID of the User. + * @param date Day to return the balances for. + * @return RequestConfig + */ + fun getUserWorkingTimeAccountsRequestConfig(id: kotlin.String, date: java.time.LocalDate) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/users/{id}/working-time-accounts/{date}".replace("{"+"id"+"}", encodeURIComponent(id.toString())).replace("{"+"date"+"}", encodeURIComponent(date.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TrackApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TrackApi.kt new file mode 100644 index 0000000..a2f1bfa --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TrackApi.kt @@ -0,0 +1,360 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Error +import com.timr.api.models.Waypoint + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class TrackApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * POST /drive-logs/{id}/track + * Create a Drive Log's Track + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + * @param id drive log id + * @param waypoint Working Time Date Span entity + * @return kotlin.collections.List + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createTrack(id: kotlin.String, waypoint: kotlin.collections.List) : kotlin.collections.List = withContext(Dispatchers.IO) { + val localVarResponse = createTrackWithHttpInfo(id = id, waypoint = waypoint) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * POST /drive-logs/{id}/track + * Create a Drive Log's Track + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + * @param id drive log id + * @param waypoint Working Time Date Span entity + * @return ApiResponse?> + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createTrackWithHttpInfo(id: kotlin.String, waypoint: kotlin.collections.List) : ApiResponse?> = withContext(Dispatchers.IO) { + val localVariableConfig = createTrackRequestConfig(id = id, waypoint = waypoint) + + return@withContext request, kotlin.collections.List>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createTrack + * + * @param id drive log id + * @param waypoint Working Time Date Span entity + * @return RequestConfig + */ + fun createTrackRequestConfig(id: kotlin.String, waypoint: kotlin.collections.List) : RequestConfig> { + val localVariableBody = waypoint + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/drive-logs/{id}/track".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /drive-logs/{id}/track + * Delete a Drive Log's Track + * Deletes the Drive Log's Track. The Drive Log itself is kept. + * @param id drive log id + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteTrack(id: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteTrackWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /drive-logs/{id}/track + * Delete a Drive Log's Track + * Deletes the Drive Log's Track. The Drive Log itself is kept. + * @param id drive log id + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteTrackWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteTrackRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteTrack + * + * @param id drive log id + * @return RequestConfig + */ + fun deleteTrackRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/drive-logs/{id}/track".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /drive-logs/{id}/track + * Get a Drive Log's Track + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + * @param id drive log id + * @return kotlin.collections.List + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getTrack(id: kotlin.String) : kotlin.collections.List = withContext(Dispatchers.IO) { + val localVarResponse = getTrackWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /drive-logs/{id}/track + * Get a Drive Log's Track + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + * @param id drive log id + * @return ApiResponse?> + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getTrackWithHttpInfo(id: kotlin.String) : ApiResponse?> = withContext(Dispatchers.IO) { + val localVariableConfig = getTrackRequestConfig(id = id) + + return@withContext request>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getTrack + * + * @param id drive log id + * @return RequestConfig + */ + fun getTrackRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/drive-logs/{id}/track".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PUT /drive-logs/{id}/track + * Replace a Drive Log's Track + * Replaces the Drive Log's Track with the waypoints in the request body. + * @param id drive log id + * @param waypoint working time date span entity + * @return kotlin.collections.List + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun updateTrack(id: kotlin.String, waypoint: kotlin.collections.List) : kotlin.collections.List = withContext(Dispatchers.IO) { + val localVarResponse = updateTrackWithHttpInfo(id = id, waypoint = waypoint) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PUT /drive-logs/{id}/track + * Replace a Drive Log's Track + * Replaces the Drive Log's Track with the waypoints in the request body. + * @param id drive log id + * @param waypoint working time date span entity + * @return ApiResponse?> + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun updateTrackWithHttpInfo(id: kotlin.String, waypoint: kotlin.collections.List) : ApiResponse?> = withContext(Dispatchers.IO) { + val localVariableConfig = updateTrackRequestConfig(id = id, waypoint = waypoint) + + return@withContext request, kotlin.collections.List>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateTrack + * + * @param id drive log id + * @param waypoint working time date span entity + * @return RequestConfig + */ + fun updateTrackRequestConfig(id: kotlin.String, waypoint: kotlin.collections.List) : RequestConfig> { + val localVariableBody = waypoint + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PUT, + path = "/drive-logs/{id}/track".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/UserApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/UserApi.kt new file mode 100644 index 0000000..7e32e08 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/UserApi.kt @@ -0,0 +1,703 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Error +import com.timr.api.models.SortDirection +import com.timr.api.models.TeamsPartialPage +import com.timr.api.models.TeamsSortColumn +import com.timr.api.models.User +import com.timr.api.models.UserCreate +import com.timr.api.models.UserUpdate +import com.timr.api.models.UsersPage +import com.timr.api.models.UsersSortColumn +import com.timr.api.models.WorkScheduleModel + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class UserApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * POST /users + * Create a User + * Creates a User from the data in the request body. + * @param userCreate User entity + * @return User + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createUser(userCreate: UserCreate) : User = withContext(Dispatchers.IO) { + val localVarResponse = createUserWithHttpInfo(userCreate = userCreate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as User + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * POST /users + * Create a User + * Creates a User from the data in the request body. + * @param userCreate User entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createUserWithHttpInfo(userCreate: UserCreate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createUserRequestConfig(userCreate = userCreate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createUser + * + * @param userCreate User entity + * @return RequestConfig + */ + fun createUserRequestConfig(userCreate: UserCreate) : RequestConfig { + val localVariableBody = userCreate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/users", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /users/{id}/team-leaderships + * List a User's Team leaderships + * Lists the Teams the User leads. + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return TeamsPartialPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchUserTeamLeaderships(id: kotlin.String, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: TeamsSortColumn? = null) : TeamsPartialPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchUserTeamLeadershipsWithHttpInfo(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TeamsPartialPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /users/{id}/team-leaderships + * List a User's Team leaderships + * Lists the Teams the User leads. + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchUserTeamLeadershipsWithHttpInfo(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TeamsSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchUserTeamLeadershipsRequestConfig(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchUserTeamLeaderships + * + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchUserTeamLeadershipsRequestConfig(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TeamsSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/users/{id}/team-leaderships".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /users/{id}/team-memberships + * List a User's Team memberships + * Lists the Teams the User is a member of. + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return TeamsPartialPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchUserTeamMemberships(id: kotlin.String, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: TeamsSortColumn? = null) : TeamsPartialPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchUserTeamMembershipsWithHttpInfo(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as TeamsPartialPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /users/{id}/team-memberships + * List a User's Team memberships + * Lists the Teams the User is a member of. + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchUserTeamMembershipsWithHttpInfo(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TeamsSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchUserTeamMembershipsRequestConfig(id = id, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchUserTeamMemberships + * + * @param id ID of the User. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchUserTeamMembershipsRequestConfig(id: kotlin.String, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: TeamsSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/users/{id}/team-memberships".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /users + * List Users + * Lists the Users the authenticated user or API token can access. + * @param name Only return Users whose name contains this text. (optional) + * @param entryDateFrom Only return Users whose entry date is on or after this day. (optional) + * @param entryDateTo Only return Users whose entry date is on or before this day. (optional) + * @param resignDateFrom Only return Users whose resignation date is on or after this day. (optional) + * @param resignDateTo Only return Users whose resignation date is on or before this day. (optional) + * @param resigned Only return Users who have resigned (true) or have not resigned (false). (optional) + * @param employeeNumber Only return Users with this employee number. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return UsersPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchUsers(name: kotlin.String? = null, entryDateFrom: java.time.LocalDate? = null, entryDateTo: java.time.LocalDate? = null, resignDateFrom: java.time.LocalDate? = null, resignDateTo: java.time.LocalDate? = null, resigned: kotlin.Boolean? = null, employeeNumber: kotlin.String? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: UsersSortColumn? = null) : UsersPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchUsersWithHttpInfo(name = name, entryDateFrom = entryDateFrom, entryDateTo = entryDateTo, resignDateFrom = resignDateFrom, resignDateTo = resignDateTo, resigned = resigned, employeeNumber = employeeNumber, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as UsersPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /users + * List Users + * Lists the Users the authenticated user or API token can access. + * @param name Only return Users whose name contains this text. (optional) + * @param entryDateFrom Only return Users whose entry date is on or after this day. (optional) + * @param entryDateTo Only return Users whose entry date is on or before this day. (optional) + * @param resignDateFrom Only return Users whose resignation date is on or after this day. (optional) + * @param resignDateTo Only return Users whose resignation date is on or before this day. (optional) + * @param resigned Only return Users who have resigned (true) or have not resigned (false). (optional) + * @param employeeNumber Only return Users with this employee number. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchUsersWithHttpInfo(name: kotlin.String?, entryDateFrom: java.time.LocalDate?, entryDateTo: java.time.LocalDate?, resignDateFrom: java.time.LocalDate?, resignDateTo: java.time.LocalDate?, resigned: kotlin.Boolean?, employeeNumber: kotlin.String?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: UsersSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchUsersRequestConfig(name = name, entryDateFrom = entryDateFrom, entryDateTo = entryDateTo, resignDateFrom = resignDateFrom, resignDateTo = resignDateTo, resigned = resigned, employeeNumber = employeeNumber, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchUsers + * + * @param name Only return Users whose name contains this text. (optional) + * @param entryDateFrom Only return Users whose entry date is on or after this day. (optional) + * @param entryDateTo Only return Users whose entry date is on or before this day. (optional) + * @param resignDateFrom Only return Users whose resignation date is on or after this day. (optional) + * @param resignDateTo Only return Users whose resignation date is on or before this day. (optional) + * @param resigned Only return Users who have resigned (true) or have not resigned (false). (optional) + * @param employeeNumber Only return Users with this employee number. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchUsersRequestConfig(name: kotlin.String?, entryDateFrom: java.time.LocalDate?, entryDateTo: java.time.LocalDate?, resignDateFrom: java.time.LocalDate?, resignDateTo: java.time.LocalDate?, resigned: kotlin.Boolean?, employeeNumber: kotlin.String?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: UsersSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (name != null) { + put("name", listOf(name.toString())) + } + if (entryDateFrom != null) { + put("entry_date_from", listOf(parseDateToQueryString(entryDateFrom))) + } + if (entryDateTo != null) { + put("entry_date_to", listOf(parseDateToQueryString(entryDateTo))) + } + if (resignDateFrom != null) { + put("resign_date_from", listOf(parseDateToQueryString(resignDateFrom))) + } + if (resignDateTo != null) { + put("resign_date_to", listOf(parseDateToQueryString(resignDateTo))) + } + if (resigned != null) { + put("resigned", listOf(resigned.toString())) + } + if (employeeNumber != null) { + put("employee_number", listOf(employeeNumber.toString())) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/users", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /users/{id} + * Get a User + * Returns a single User by its ID. + * @param id ID of the User. + * @return User + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getUser(id: kotlin.String) : User = withContext(Dispatchers.IO) { + val localVarResponse = getUserWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as User + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /users/{id} + * Get a User + * Returns a single User by its ID. + * @param id ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getUserWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getUserRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getUser + * + * @param id ID of the User. + * @return RequestConfig + */ + fun getUserRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/users/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /users/{id}/work-schedule-model + * Get a User's Work Schedule Model + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + * @param id ID of the User. + * @return WorkScheduleModel + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getUserWorkScheduleModel(id: kotlin.String) : WorkScheduleModel = withContext(Dispatchers.IO) { + val localVarResponse = getUserWorkScheduleModelWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkScheduleModel + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /users/{id}/work-schedule-model + * Get a User's Work Schedule Model + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + * @param id ID of the User. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getUserWorkScheduleModelWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getUserWorkScheduleModelRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getUserWorkScheduleModel + * + * @param id ID of the User. + * @return RequestConfig + */ + fun getUserWorkScheduleModelRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/users/{id}/work-schedule-model".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PATCH /users/{id} + * Update a User + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the User. + * @param userUpdate User entity + * @return User + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun updateUser(id: kotlin.String, userUpdate: UserUpdate) : User = withContext(Dispatchers.IO) { + val localVarResponse = updateUserWithHttpInfo(id = id, userUpdate = userUpdate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as User + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PATCH /users/{id} + * Update a User + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the User. + * @param userUpdate User entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun updateUserWithHttpInfo(id: kotlin.String, userUpdate: UserUpdate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = updateUserRequestConfig(id = id, userUpdate = userUpdate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateUser + * + * @param id ID of the User. + * @param userUpdate User entity + * @return RequestConfig + */ + fun updateUserRequestConfig(id: kotlin.String, userUpdate: UserUpdate) : RequestConfig { + val localVariableBody = userUpdate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PATCH, + path = "/users/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkScheduleModelApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkScheduleModelApi.kt new file mode 100644 index 0000000..d21a17e --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkScheduleModelApi.kt @@ -0,0 +1,305 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.Error +import com.timr.api.models.SortDirection +import com.timr.api.models.WorkScheduleModel +import com.timr.api.models.WorkScheduleModelSortColumn +import com.timr.api.models.WorkScheduleModelsPage + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class WorkScheduleModelApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * DELETE /work-schedule-models/{id} + * Delete a Work Schedule Model + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + * @param id ID of the Work Schedule Model. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteWorkScheduleModel(id: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteWorkScheduleModelWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /work-schedule-models/{id} + * Delete a Work Schedule Model + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + * @param id ID of the Work Schedule Model. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteWorkScheduleModelWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteWorkScheduleModelRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteWorkScheduleModel + * + * @param id ID of the Work Schedule Model. + * @return RequestConfig + */ + fun deleteWorkScheduleModelRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/work-schedule-models/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /work-schedule-models + * List Work Schedule Models + * Lists the Work Schedule Models the authenticated user or API token can access. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return WorkScheduleModelsPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchWorkScheduleModels(pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: WorkScheduleModelSortColumn? = null) : WorkScheduleModelsPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchWorkScheduleModelsWithHttpInfo(pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkScheduleModelsPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /work-schedule-models + * List Work Schedule Models + * Lists the Work Schedule Models the authenticated user or API token can access. + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchWorkScheduleModelsWithHttpInfo(pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: WorkScheduleModelSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchWorkScheduleModelsRequestConfig(pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchWorkScheduleModels + * + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchWorkScheduleModelsRequestConfig(pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: WorkScheduleModelSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/work-schedule-models", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /work-schedule-models/{id} + * Get a Work Schedule Model + * Returns a single Work Schedule Model by its ID. + * @param id ID of the Work Schedule Model. + * @return WorkScheduleModel + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getWorkScheduleModel(id: kotlin.String) : WorkScheduleModel = withContext(Dispatchers.IO) { + val localVarResponse = getWorkScheduleModelWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkScheduleModel + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /work-schedule-models/{id} + * Get a Work Schedule Model + * Returns a single Work Schedule Model by its ID. + * @param id ID of the Work Schedule Model. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getWorkScheduleModelWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getWorkScheduleModelRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getWorkScheduleModel + * + * @param id ID of the Work Schedule Model. + * @return RequestConfig + */ + fun getWorkScheduleModelRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/work-schedule-models/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkingTimeApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkingTimeApi.kt new file mode 100644 index 0000000..a80f59b --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkingTimeApi.kt @@ -0,0 +1,618 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.DeletedEntrySortColumn +import com.timr.api.models.DeletedEntryWithMetadataPage +import com.timr.api.models.Error +import com.timr.api.models.SortDirection +import com.timr.api.models.WorkingTime +import com.timr.api.models.WorkingTimeCreate +import com.timr.api.models.WorkingTimeStatus +import com.timr.api.models.WorkingTimeTypeCategory +import com.timr.api.models.WorkingTimeUpdate +import com.timr.api.models.WorkingTimesPage +import com.timr.api.models.WorkingTimesSortColumn + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class WorkingTimeApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * POST /working-times + * Create a Working Time + * Creates a Working Time from the data in the request body. + * @param workingTimeCreate Working Time entity + * @return WorkingTime + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createWorkingTime(workingTimeCreate: WorkingTimeCreate) : WorkingTime = withContext(Dispatchers.IO) { + val localVarResponse = createWorkingTimeWithHttpInfo(workingTimeCreate = workingTimeCreate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTime + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * POST /working-times + * Create a Working Time + * Creates a Working Time from the data in the request body. + * @param workingTimeCreate Working Time entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createWorkingTimeWithHttpInfo(workingTimeCreate: WorkingTimeCreate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createWorkingTimeRequestConfig(workingTimeCreate = workingTimeCreate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createWorkingTime + * + * @param workingTimeCreate Working Time entity + * @return RequestConfig + */ + fun createWorkingTimeRequestConfig(workingTimeCreate: WorkingTimeCreate) : RequestConfig { + val localVariableBody = workingTimeCreate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/working-times", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /working-times/{id} + * Delete a Working Time + * Deletes the Working Time. + * @param id ID of the Working Time. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteWorkingTime(id: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteWorkingTimeWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /working-times/{id} + * Delete a Working Time + * Deletes the Working Time. + * @param id ID of the Working Time. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteWorkingTimeWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteWorkingTimeRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteWorkingTime + * + * @param id ID of the Working Time. + * @return RequestConfig + */ + fun deleteWorkingTimeRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/working-times/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /working-times:deleted + * List deleted Working Times + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return DeletedEntryWithMetadataPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchDeletedWorkingTimes(lastModifiedAfter: java.time.OffsetDateTime? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: DeletedEntrySortColumn? = null) : DeletedEntryWithMetadataPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchDeletedWorkingTimesWithHttpInfo(lastModifiedAfter = lastModifiedAfter, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DeletedEntryWithMetadataPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /working-times:deleted + * List deleted Working Times + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchDeletedWorkingTimesWithHttpInfo(lastModifiedAfter: java.time.OffsetDateTime?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DeletedEntrySortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchDeletedWorkingTimesRequestConfig(lastModifiedAfter = lastModifiedAfter, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchDeletedWorkingTimes + * + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchDeletedWorkingTimesRequestConfig(lastModifiedAfter: java.time.OffsetDateTime?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DeletedEntrySortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (lastModifiedAfter != null) { + put("last_modified_after", listOf(parseDateToQueryString(lastModifiedAfter))) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/working-times:deleted", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /working-times + * List Working Times + * Lists the Working Times the authenticated user or API token can access. + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param workingTimeTypeCategories Only return entries whose Working Time Type is in one of these categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return WorkingTimesPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchWorkingTimes(notes: kotlin.String? = null, startFrom: java.time.LocalDate? = null, startTo: java.time.LocalDate? = null, lastModifiedAfter: java.time.OffsetDateTime? = null, workingTimeTypes: kotlin.collections.List? = null, workingTimeTypeCategories: kotlin.collections.List? = null, statuses: kotlin.collections.List? = null, users: kotlin.collections.List? = null, changed: kotlin.Boolean? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: WorkingTimesSortColumn? = null) : WorkingTimesPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchWorkingTimesWithHttpInfo(notes = notes, startFrom = startFrom, startTo = startTo, lastModifiedAfter = lastModifiedAfter, workingTimeTypes = workingTimeTypes, workingTimeTypeCategories = workingTimeTypeCategories, statuses = statuses, users = users, changed = changed, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTimesPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /working-times + * List Working Times + * Lists the Working Times the authenticated user or API token can access. + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param workingTimeTypeCategories Only return entries whose Working Time Type is in one of these categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchWorkingTimesWithHttpInfo(notes: kotlin.String?, startFrom: java.time.LocalDate?, startTo: java.time.LocalDate?, lastModifiedAfter: java.time.OffsetDateTime?, workingTimeTypes: kotlin.collections.List?, workingTimeTypeCategories: kotlin.collections.List?, statuses: kotlin.collections.List?, users: kotlin.collections.List?, changed: kotlin.Boolean?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: WorkingTimesSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchWorkingTimesRequestConfig(notes = notes, startFrom = startFrom, startTo = startTo, lastModifiedAfter = lastModifiedAfter, workingTimeTypes = workingTimeTypes, workingTimeTypeCategories = workingTimeTypeCategories, statuses = statuses, users = users, changed = changed, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchWorkingTimes + * + * @param notes Only return entries whose notes contain this text. (optional) + * @param startFrom Only return entries starting on or after this day. (optional) + * @param startTo Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param workingTimeTypeCategories Only return entries whose Working Time Type is in one of these categories. (optional) + * @param statuses Only return entries in one of these statuses. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param changed Only return entries that were changed by the user (true) or left unchanged (false). (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchWorkingTimesRequestConfig(notes: kotlin.String?, startFrom: java.time.LocalDate?, startTo: java.time.LocalDate?, lastModifiedAfter: java.time.OffsetDateTime?, workingTimeTypes: kotlin.collections.List?, workingTimeTypeCategories: kotlin.collections.List?, statuses: kotlin.collections.List?, users: kotlin.collections.List?, changed: kotlin.Boolean?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: WorkingTimesSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (notes != null) { + put("notes", listOf(notes.toString())) + } + if (startFrom != null) { + put("start_from", listOf(parseDateToQueryString(startFrom))) + } + if (startTo != null) { + put("start_to", listOf(parseDateToQueryString(startTo))) + } + if (lastModifiedAfter != null) { + put("last_modified_after", listOf(parseDateToQueryString(lastModifiedAfter))) + } + if (workingTimeTypes != null) { + put("working_time_types", toMultiValue(workingTimeTypes.toList(), "multi")) + } + if (workingTimeTypeCategories != null) { + put("working_time_type_categories", toMultiValue(workingTimeTypeCategories.toList(), "multi")) + } + if (statuses != null) { + put("statuses", toMultiValue(statuses.toList(), "multi")) + } + if (users != null) { + put("users", toMultiValue(users.toList(), "multi")) + } + if (changed != null) { + put("changed", listOf(changed.toString())) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/working-times", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /working-times/{id} + * Get a Working Time + * Returns a single Working Time by its ID. + * @param id ID of the Working Time. + * @return WorkingTime + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getWorkingTime(id: kotlin.String) : WorkingTime = withContext(Dispatchers.IO) { + val localVarResponse = getWorkingTimeWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTime + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /working-times/{id} + * Get a Working Time + * Returns a single Working Time by its ID. + * @param id ID of the Working Time. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getWorkingTimeWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getWorkingTimeRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getWorkingTime + * + * @param id ID of the Working Time. + * @return RequestConfig + */ + fun getWorkingTimeRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/working-times/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PATCH /working-times/{id} + * Update a Working Time + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Working Time. + * @param workingTimeUpdate Working Time entity + * @return WorkingTime + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun updateWorkingTime(id: kotlin.String, workingTimeUpdate: WorkingTimeUpdate) : WorkingTime = withContext(Dispatchers.IO) { + val localVarResponse = updateWorkingTimeWithHttpInfo(id = id, workingTimeUpdate = workingTimeUpdate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTime + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PATCH /working-times/{id} + * Update a Working Time + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + * @param id ID of the Working Time. + * @param workingTimeUpdate Working Time entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun updateWorkingTimeWithHttpInfo(id: kotlin.String, workingTimeUpdate: WorkingTimeUpdate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = updateWorkingTimeRequestConfig(id = id, workingTimeUpdate = workingTimeUpdate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateWorkingTime + * + * @param id ID of the Working Time. + * @param workingTimeUpdate Working Time entity + * @return RequestConfig + */ + fun updateWorkingTimeRequestConfig(id: kotlin.String, workingTimeUpdate: WorkingTimeUpdate) : RequestConfig { + val localVariableBody = workingTimeUpdate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PATCH, + path = "/working-times/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkingTimeDateSpanApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkingTimeDateSpanApi.kt new file mode 100644 index 0000000..4397b11 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkingTimeDateSpanApi.kt @@ -0,0 +1,592 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.DeletedEntrySortColumn +import com.timr.api.models.DeletedEntryWithMetadataPage +import com.timr.api.models.Error +import com.timr.api.models.SortDirection +import com.timr.api.models.WorkingTimeDateSpan +import com.timr.api.models.WorkingTimeDateSpanCreate +import com.timr.api.models.WorkingTimeDateSpanPage +import com.timr.api.models.WorkingTimeDateSpanUpdate +import com.timr.api.models.WorkingTimeDateSpansSortColumn + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class WorkingTimeDateSpanApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * POST /working-time-date-spans + * Create a Working Time Date Span + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + * @param workingTimeDateSpanCreate Working Time Date Span entity + * @return WorkingTimeDateSpan + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun createWorkingTimeDateSpan(workingTimeDateSpanCreate: WorkingTimeDateSpanCreate) : WorkingTimeDateSpan = withContext(Dispatchers.IO) { + val localVarResponse = createWorkingTimeDateSpanWithHttpInfo(workingTimeDateSpanCreate = workingTimeDateSpanCreate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTimeDateSpan + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * POST /working-time-date-spans + * Create a Working Time Date Span + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + * @param workingTimeDateSpanCreate Working Time Date Span entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun createWorkingTimeDateSpanWithHttpInfo(workingTimeDateSpanCreate: WorkingTimeDateSpanCreate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = createWorkingTimeDateSpanRequestConfig(workingTimeDateSpanCreate = workingTimeDateSpanCreate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createWorkingTimeDateSpan + * + * @param workingTimeDateSpanCreate Working Time Date Span entity + * @return RequestConfig + */ + fun createWorkingTimeDateSpanRequestConfig(workingTimeDateSpanCreate: WorkingTimeDateSpanCreate) : RequestConfig { + val localVariableBody = workingTimeDateSpanCreate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/working-time-date-spans", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * DELETE /working-time-date-spans/{id} + * Delete a Working Time Date Span + * Deletes the Working Time Date Span together with the Working Times it covers. + * @param id ID of the Working Time Date Span. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteWorkingTimeDateSpan(id: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteWorkingTimeDateSpanWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /working-time-date-spans/{id} + * Delete a Working Time Date Span + * Deletes the Working Time Date Span together with the Working Times it covers. + * @param id ID of the Working Time Date Span. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteWorkingTimeDateSpanWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteWorkingTimeDateSpanRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteWorkingTimeDateSpan + * + * @param id ID of the Working Time Date Span. + * @return RequestConfig + */ + fun deleteWorkingTimeDateSpanRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/working-time-date-spans/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /working-time-date-spans:deleted + * List deleted Working Time Date Spans + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return DeletedEntryWithMetadataPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchDeletedWorkingTimeDateSpans(lastModifiedAfter: java.time.OffsetDateTime? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: DeletedEntrySortColumn? = null) : DeletedEntryWithMetadataPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchDeletedWorkingTimeDateSpansWithHttpInfo(lastModifiedAfter = lastModifiedAfter, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as DeletedEntryWithMetadataPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /working-time-date-spans:deleted + * List deleted Working Time Date Spans + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchDeletedWorkingTimeDateSpansWithHttpInfo(lastModifiedAfter: java.time.OffsetDateTime?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DeletedEntrySortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchDeletedWorkingTimeDateSpansRequestConfig(lastModifiedAfter = lastModifiedAfter, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchDeletedWorkingTimeDateSpans + * + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchDeletedWorkingTimeDateSpansRequestConfig(lastModifiedAfter: java.time.OffsetDateTime?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: DeletedEntrySortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (lastModifiedAfter != null) { + put("last_modified_after", listOf(parseDateToQueryString(lastModifiedAfter))) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/working-time-date-spans:deleted", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /working-time-date-spans + * List Working Time Date Spans + * Lists the Working Time Date Spans the authenticated user or API token can access. + * @param from Only return Working Time Date Spans that end on or after this day. (optional) + * @param to Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return WorkingTimeDateSpanPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchWorkingTimeDateSpans(from: java.time.LocalDate? = null, to: java.time.LocalDate? = null, lastModifiedAfter: java.time.OffsetDateTime? = null, workingTimeTypes: kotlin.collections.List? = null, users: kotlin.collections.List? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: WorkingTimeDateSpansSortColumn? = null) : WorkingTimeDateSpanPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchWorkingTimeDateSpansWithHttpInfo(from = from, to = to, lastModifiedAfter = lastModifiedAfter, workingTimeTypes = workingTimeTypes, users = users, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTimeDateSpanPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /working-time-date-spans + * List Working Time Date Spans + * Lists the Working Time Date Spans the authenticated user or API token can access. + * @param from Only return Working Time Date Spans that end on or after this day. (optional) + * @param to Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchWorkingTimeDateSpansWithHttpInfo(from: java.time.LocalDate?, to: java.time.LocalDate?, lastModifiedAfter: java.time.OffsetDateTime?, workingTimeTypes: kotlin.collections.List?, users: kotlin.collections.List?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: WorkingTimeDateSpansSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchWorkingTimeDateSpansRequestConfig(from = from, to = to, lastModifiedAfter = lastModifiedAfter, workingTimeTypes = workingTimeTypes, users = users, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchWorkingTimeDateSpans + * + * @param from Only return Working Time Date Spans that end on or after this day. (optional) + * @param to Only return entries starting on or before this day. (optional) + * @param lastModifiedAfter Only return entries modified after this instant. (optional) + * @param workingTimeTypes Only return entries of these Working Time Types. (optional) + * @param users Only return entries belonging to these users. (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchWorkingTimeDateSpansRequestConfig(from: java.time.LocalDate?, to: java.time.LocalDate?, lastModifiedAfter: java.time.OffsetDateTime?, workingTimeTypes: kotlin.collections.List?, users: kotlin.collections.List?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: WorkingTimeDateSpansSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (from != null) { + put("from", listOf(parseDateToQueryString(from))) + } + if (to != null) { + put("to", listOf(parseDateToQueryString(to))) + } + if (lastModifiedAfter != null) { + put("last_modified_after", listOf(parseDateToQueryString(lastModifiedAfter))) + } + if (workingTimeTypes != null) { + put("working_time_types", toMultiValue(workingTimeTypes.toList(), "multi")) + } + if (users != null) { + put("users", toMultiValue(users.toList(), "multi")) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/working-time-date-spans", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /working-time-date-spans/{id} + * Get a Working Time Date Span + * Returns a single Working Time Date Span by its ID. + * @param id ID of the Working Time Date Span. + * @return WorkingTimeDateSpan + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getWorkingTimeDateSpan(id: kotlin.String) : WorkingTimeDateSpan = withContext(Dispatchers.IO) { + val localVarResponse = getWorkingTimeDateSpanWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTimeDateSpan + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /working-time-date-spans/{id} + * Get a Working Time Date Span + * Returns a single Working Time Date Span by its ID. + * @param id ID of the Working Time Date Span. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getWorkingTimeDateSpanWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getWorkingTimeDateSpanRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getWorkingTimeDateSpan + * + * @param id ID of the Working Time Date Span. + * @return RequestConfig + */ + fun getWorkingTimeDateSpanRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/working-time-date-spans/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * PATCH /working-time-date-spans/{id} + * Update a Working Time Date Span + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + * @param id ID of the Working Time Date Span. + * @param workingTimeDateSpanUpdate working time date span entity + * @return WorkingTimeDateSpan + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun updateWorkingTimeDateSpan(id: kotlin.String, workingTimeDateSpanUpdate: WorkingTimeDateSpanUpdate) : WorkingTimeDateSpan = withContext(Dispatchers.IO) { + val localVarResponse = updateWorkingTimeDateSpanWithHttpInfo(id = id, workingTimeDateSpanUpdate = workingTimeDateSpanUpdate) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTimeDateSpan + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * PATCH /working-time-date-spans/{id} + * Update a Working Time Date Span + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + * @param id ID of the Working Time Date Span. + * @param workingTimeDateSpanUpdate working time date span entity + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun updateWorkingTimeDateSpanWithHttpInfo(id: kotlin.String, workingTimeDateSpanUpdate: WorkingTimeDateSpanUpdate) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = updateWorkingTimeDateSpanRequestConfig(id = id, workingTimeDateSpanUpdate = workingTimeDateSpanUpdate) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateWorkingTimeDateSpan + * + * @param id ID of the Working Time Date Span. + * @param workingTimeDateSpanUpdate working time date span entity + * @return RequestConfig + */ + fun updateWorkingTimeDateSpanRequestConfig(id: kotlin.String, workingTimeDateSpanUpdate: WorkingTimeDateSpanUpdate) : RequestConfig { + val localVariableBody = workingTimeDateSpanUpdate + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.PATCH, + path = "/working-time-date-spans/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkingTimeTypeApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkingTimeTypeApi.kt new file mode 100644 index 0000000..ccba1d9 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/WorkingTimeTypeApi.kt @@ -0,0 +1,357 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.apis + +import java.io.IOException +import okhttp3.Call +import okhttp3.HttpUrl + +import com.timr.api.models.DurationUnit +import com.timr.api.models.Error +import com.timr.api.models.RecordingModeUser +import com.timr.api.models.SortDirection +import com.timr.api.models.WorkingTimeType +import com.timr.api.models.WorkingTimeTypeCategory +import com.timr.api.models.WorkingTimeTypeSubCategory +import com.timr.api.models.WorkingTimeTypesPage +import com.timr.api.models.WorkingTimeTypesSortColumn + +import com.google.gson.annotations.SerializedName + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import com.timr.api.infrastructure.ApiClient +import com.timr.api.infrastructure.ApiResponse +import com.timr.api.infrastructure.ClientException +import com.timr.api.infrastructure.ClientError +import com.timr.api.infrastructure.ServerException +import com.timr.api.infrastructure.ServerError +import com.timr.api.infrastructure.MultiValueMap +import com.timr.api.infrastructure.PartConfig +import com.timr.api.infrastructure.RequestConfig +import com.timr.api.infrastructure.RequestMethod +import com.timr.api.infrastructure.ResponseType +import com.timr.api.infrastructure.Success +import com.timr.api.infrastructure.toMultiValue + +open class WorkingTimeTypeApi(basePath: kotlin.String = defaultBasePath, client: Call.Factory = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.BASE_URL_KEY, "https://api.timr.com/v1") + } + } + + /** + * DELETE /working-time-types/{id} + * Delete a Working Time Type + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + * @param id ID of the Working Time Type. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteWorkingTimeType(id: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteWorkingTimeTypeWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /working-time-types/{id} + * Delete a Working Time Type + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + * @param id ID of the Working Time Type. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteWorkingTimeTypeWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteWorkingTimeTypeRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteWorkingTimeType + * + * @param id ID of the Working Time Type. + * @return RequestConfig + */ + fun deleteWorkingTimeTypeRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/working-time-types/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /working-time-types + * List Working Time Types + * Lists the Working Time Types the authenticated user or API token can access. + * @param name Only return entries whose name contains this text. (optional) + * @param shortName filter by short name (optional) + * @param description filter by description (optional) + * @param categories filter by WorkingTimeTypeCategory (optional) + * @param subCategories filter by WorkingTimeTypeSubCategory (optional) + * @param editUnits filter by WorkingTimeType's DurationUnit (optional) + * @param archived Only return entries that are archived (true) or not archived (false). (optional) + * @param recordingModes filter entries bAWS on their RecordingMode (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return WorkingTimeTypesPage + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun fetchWorkingTimeTypes(name: kotlin.String? = null, shortName: kotlin.String? = null, description: kotlin.String? = null, categories: kotlin.collections.List? = null, subCategories: kotlin.collections.List? = null, editUnits: kotlin.collections.List? = null, archived: kotlin.Boolean? = null, recordingModes: kotlin.collections.List? = null, pageToken: kotlin.String? = null, limit: kotlin.Int? = 20, sortDirection: SortDirection? = null, sortBy: WorkingTimeTypesSortColumn? = null) : WorkingTimeTypesPage = withContext(Dispatchers.IO) { + val localVarResponse = fetchWorkingTimeTypesWithHttpInfo(name = name, shortName = shortName, description = description, categories = categories, subCategories = subCategories, editUnits = editUnits, archived = archived, recordingModes = recordingModes, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTimeTypesPage + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /working-time-types + * List Working Time Types + * Lists the Working Time Types the authenticated user or API token can access. + * @param name Only return entries whose name contains this text. (optional) + * @param shortName filter by short name (optional) + * @param description filter by description (optional) + * @param categories filter by WorkingTimeTypeCategory (optional) + * @param subCategories filter by WorkingTimeTypeSubCategory (optional) + * @param editUnits filter by WorkingTimeType's DurationUnit (optional) + * @param archived Only return entries that are archived (true) or not archived (false). (optional) + * @param recordingModes filter entries bAWS on their RecordingMode (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun fetchWorkingTimeTypesWithHttpInfo(name: kotlin.String?, shortName: kotlin.String?, description: kotlin.String?, categories: kotlin.collections.List?, subCategories: kotlin.collections.List?, editUnits: kotlin.collections.List?, archived: kotlin.Boolean?, recordingModes: kotlin.collections.List?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: WorkingTimeTypesSortColumn?) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = fetchWorkingTimeTypesRequestConfig(name = name, shortName = shortName, description = description, categories = categories, subCategories = subCategories, editUnits = editUnits, archived = archived, recordingModes = recordingModes, pageToken = pageToken, limit = limit, sortDirection = sortDirection, sortBy = sortBy) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation fetchWorkingTimeTypes + * + * @param name Only return entries whose name contains this text. (optional) + * @param shortName filter by short name (optional) + * @param description filter by description (optional) + * @param categories filter by WorkingTimeTypeCategory (optional) + * @param subCategories filter by WorkingTimeTypeSubCategory (optional) + * @param editUnits filter by WorkingTimeType's DurationUnit (optional) + * @param archived Only return entries that are archived (true) or not archived (false). (optional) + * @param recordingModes filter entries bAWS on their RecordingMode (optional) + * @param pageToken Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + * @param limit Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + * @param sortDirection Direction to sort the entries in. (optional) + * @param sortBy Property to sort the entries by. (optional) + * @return RequestConfig + */ + fun fetchWorkingTimeTypesRequestConfig(name: kotlin.String?, shortName: kotlin.String?, description: kotlin.String?, categories: kotlin.collections.List?, subCategories: kotlin.collections.List?, editUnits: kotlin.collections.List?, archived: kotlin.Boolean?, recordingModes: kotlin.collections.List?, pageToken: kotlin.String?, limit: kotlin.Int?, sortDirection: SortDirection?, sortBy: WorkingTimeTypesSortColumn?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + if (name != null) { + put("name", listOf(name.toString())) + } + if (shortName != null) { + put("short_name", listOf(shortName.toString())) + } + if (description != null) { + put("description", listOf(description.toString())) + } + if (categories != null) { + put("categories", toMultiValue(categories.toList(), "multi")) + } + if (subCategories != null) { + put("sub_categories", toMultiValue(subCategories.toList(), "multi")) + } + if (editUnits != null) { + put("edit_units", toMultiValue(editUnits.toList(), "multi")) + } + if (archived != null) { + put("archived", listOf(archived.toString())) + } + if (recordingModes != null) { + put("recording_modes", toMultiValue(recordingModes.toList(), "multi")) + } + if (pageToken != null) { + put("page_token", listOf(pageToken.toString())) + } + if (limit != null) { + put("limit", listOf(limit.toString())) + } + if (sortDirection != null) { + put("sort_direction", listOf(sortDirection.toString())) + } + if (sortBy != null) { + put("sort_by", listOf(sortBy.toString())) + } + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/working-time-types", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * GET /working-time-types/{id} + * Get a Working Time Type + * Returns a single Working Time Type by its ID. + * @param id ID of the Working Time Type. + * @return WorkingTimeType + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun getWorkingTimeType(id: kotlin.String) : WorkingTimeType = withContext(Dispatchers.IO) { + val localVarResponse = getWorkingTimeTypeWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as WorkingTimeType + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * GET /working-time-types/{id} + * Get a Working Time Type + * Returns a single Working Time Type by its ID. + * @param id ID of the Working Time Type. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + suspend fun getWorkingTimeTypeWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = getWorkingTimeTypeRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getWorkingTimeType + * + * @param id ID of the Working Time Type. + * @return RequestConfig + */ + fun getWorkingTimeTypeRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json, application/problem+json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/working-time-types/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ApiAbstractions.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ApiAbstractions.kt new file mode 100644 index 0000000..7374b7c --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package com.timr.api.infrastructure + +typealias MultiValueMap = MutableMap> + +fun collectionDelimiter(collectionFormat: String): String = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List + = toMultiValue(items.asIterable(), collectionFormat, map) + +fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { + return when(collectionFormat) { + "multi" -> items.map(map) + else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) + } +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ApiClient.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ApiClient.kt new file mode 100644 index 0000000..528343b --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ApiClient.kt @@ -0,0 +1,495 @@ +package com.timr.api.infrastructure + +import okhttp3.OkHttpClient +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.asRequestBody +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.FormBody +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.ResponseBody +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.Request +import okhttp3.Headers +import okhttp3.Headers.Builder +import okhttp3.Headers.Companion.toHeaders +import okhttp3.MultipartBody +import okhttp3.Call +import okhttp3.Callback +import okhttp3.Response +import java.io.BufferedWriter +import java.io.File +import java.io.FileWriter +import java.io.IOException +import java.net.URLConnection +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime +import java.util.Locale +import java.util.regex.Pattern +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlinx.coroutines.suspendCancellableCoroutine +import com.google.gson.reflect.TypeToken + +val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + +open class ApiClient(val baseUrl: String, val client: Call.Factory = defaultClient) { + companion object { + protected const val CONTENT_TYPE: String = "Content-Type" + @Deprecated( + message = "Please use the capitalized constant `CONTENT_TYPE` instead.", + replaceWith = ReplaceWith("CONTENT_TYPE") + ) + protected const val ContentType: String = CONTENT_TYPE + + protected const val ACCEPT: String = "Accept" + @Deprecated( + message = "Please use the capitalized constant `ACCEPT` instead.", + replaceWith = ReplaceWith("ACCEPT") + ) + protected const val Accept: String = ACCEPT + + protected const val AUTHORIZATION: String = "Authorization" + @Deprecated( + message = "Please use the capitalized constant `AUTHORIZATION` instead.", + replaceWith = ReplaceWith("AUTHORIZATION") + ) + protected const val Authorization: String = AUTHORIZATION + + protected const val JSON_MEDIA_TYPE: String = "application/json" + @Deprecated( + message = "Please use the capitalized constant `JSON_MEDIA_TYPE` instead.", + replaceWith = ReplaceWith("JSON_MEDIA_TYPE") + ) + protected const val JsonMediaType: String = JSON_MEDIA_TYPE + + protected const val FORM_DATA_MEDIA_TYPE: String = "multipart/form-data" + @Deprecated( + message = "Please use the capitalized constant `FORM_DATA_MEDIA_TYPE` instead.", + replaceWith = ReplaceWith("FORM_DATA_MEDIA_TYPE") + ) + protected const val FormDataMediaType: String = FORM_DATA_MEDIA_TYPE + + protected const val FORM_URL_ENC_MEDIA_TYPE: String = "application/x-www-form-urlencoded" + @Deprecated( + message = "Please use the capitalized constant `FORM_URL_ENC_MEDIA_TYPE` instead.", + replaceWith = ReplaceWith("FORM_URL_ENC_MEDIA_TYPE") + ) + protected const val FormUrlEncMediaType: String = FORM_URL_ENC_MEDIA_TYPE + + protected const val XML_MEDIA_TYPE: String = "application/xml" + @Deprecated( + message = "Please use the capitalized constant `XML_MEDIA_TYPE` instead.", + replaceWith = ReplaceWith("XML_MEDIA_TYPE") + ) + protected const val XmlMediaType: String = XML_MEDIA_TYPE + + protected const val OCTET_MEDIA_TYPE: String = "application/octet-stream" + @Deprecated( + message = "Please use the capitalized constant `OCTET_MEDIA_TYPE` instead.", + replaceWith = ReplaceWith("OCTET_MEDIA_TYPE") + ) + protected const val OctetMediaType: String = OCTET_MEDIA_TYPE + + protected const val TEXT_MEDIA_TYPE: String = "text/plain" + @Deprecated( + message = "Please use the capitalized constant `TEXT_MEDIA_TYPE` instead.", + replaceWith = ReplaceWith("TEXT_MEDIA_TYPE") + ) + protected const val TextMediaType: String = TEXT_MEDIA_TYPE + + const val BASE_URL_KEY: String = "com.timr.api.baseUrl" + @Deprecated( + message = "Please use the capitalized constant `BASE_URL_KEY` instead.", + replaceWith = ReplaceWith("BASE_URL_KEY") + ) + const val baseUrlKey: String = BASE_URL_KEY + + val apiKey: MutableMap = mutableMapOf() + val apiKeyPrefix: MutableMap = mutableMapOf() + var username: String? = null + var password: String? = null + var accessToken: String? = null + + @JvmStatic + val defaultClient: OkHttpClient by lazy { + builder.build() + } + + @JvmStatic + val builder: OkHttpClient.Builder = OkHttpClient.Builder() + } + + /** + * Guess Content-Type header from the given byteArray (defaults to "application/octet-stream"). + * + * @param byteArray The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromByteArray(byteArray: ByteArray): String { + val contentType = try { + URLConnection.guessContentTypeFromStream(byteArray.inputStream()) + } catch (_: IOException) { + "application/octet-stream" + } + return contentType + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + /** + * Builds headers for a multipart form-data part. + * OkHttp requires Content-Type to be passed via the RequestBody parameter, not in headers. + * This function filters out Content-Type and builds the appropriate Content-Disposition header. + * + * @param name The field name + * @param headers The headers from the PartConfig (may include Content-Type) + * @param filename Optional filename for file uploads + * @return Headers object ready for addPart() + */ + protected fun buildPartHeaders(name: String, headers: Map, filename: String? = null): Headers { + val disposition = if (filename != null) { + "form-data; name=\"$name\"; filename=\"$filename\"" + } else { + "form-data; name=\"$name\"" + } + return (headers.filterKeys { it != "Content-Type" } + ("Content-Disposition" to disposition)).toHeaders() + } + + /** + * Adds a File to a MultipartBody.Builder + * Defined a helper in the requestBody method to not duplicate code + * It will be used when the content is a `FORM_DATA_MEDIA_TYPE` and the body of the PartConfig is a File + * + * @param name The field name to add in the request + * @param headers The headers that are in the PartConfig + * @param file The file that will be added as the field value + * @return The method returns Unit but the new Part is added to the Builder that the extension function is applying on + * @see requestBody + */ + protected fun MultipartBody.Builder.addPartToMultiPart(name: String, headers: Map, file: File) { + val fileMediaType = guessContentTypeFromFile(file).toMediaTypeOrNull() + addPart( + buildPartHeaders(name, headers, file.name), + file.asRequestBody(fileMediaType) + ) + } + + /** + * Serializes a multipart body part based on its content type. + * Uses JSON serialization for application/json content types, otherwise converts to string. + * + * @param obj The object to serialize + * @param contentType The Content-Type header value, if any + * @param serializer Optional custom serializer (used for kotlinx.serialization to preserve type info) + * @return The serialized string representation + */ + protected fun serializePartBody(obj: Any?, contentType: String?, serializer: ((Any?) -> String)?): String { + // Use custom serializer if provided (for kotlinx.serialization with captured type info) + if (serializer != null) { + return serializer(obj) + } + + return if (contentType?.contains("json") == true) { + Serializer.gson.toJson(obj) + } else { + parameterToString(obj) + } + } + + /** + * Adds any type to a MultipartBody.Builder + * Defined a helper in the requestBody method to not duplicate code + * It will be used when the content is a `FORM_DATA_MEDIA_TYPE` and the body of the PartConfig is not a File. + * + * @param name The field name to add in the request + * @param headers The headers that are in the PartConfig + * @param obj The field name to add in the request + * @param serializer Optional custom serializer for this part + * @return The method returns Unit but the new Part is added to the Builder that the extension function is applying on + * @see requestBody + */ + protected fun MultipartBody.Builder.addPartToMultiPart(name: String, headers: Map, obj: Any?, serializer: ((Any?) -> String)? = null) { + val partContentType = headers["Content-Type"] + val partMediaType = partContentType?.toMediaTypeOrNull() + val partBody = serializePartBody(obj, partContentType, serializer) + addPart( + buildPartHeaders(name, headers), + partBody.toRequestBody(partMediaType) + ) + } + + protected inline fun requestBody(content: T, mediaType: String?): RequestBody = + when { + content is ByteArray -> content.toRequestBody((mediaType ?: guessContentTypeFromByteArray(content)).toMediaTypeOrNull()) + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) + mediaType == FORM_DATA_MEDIA_TYPE -> + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map> + @Suppress("UNCHECKED_CAST") + (content as Map>).forEach { (name, part) -> + when (part.body) { + is File -> addPartToMultiPart(name, part.headers, part.body) + is List<*> -> { + part.body.forEach { + if (it is File) { + addPartToMultiPart(name, part.headers, it) + } else { + addPartToMultiPart(name, part.headers, it, part.serializer) + } + } + } + else -> addPartToMultiPart(name, part.headers, part.body, part.serializer) + } + } + }.build() + mediaType == FORM_URL_ENC_MEDIA_TYPE -> { + FormBody.Builder().apply { + // content's type *must* be Map> + @Suppress("UNCHECKED_CAST") + (content as Map>).forEach { (name, part) -> + add(name, parameterToString(part.body)) + } + }.build() + } + mediaType == null || mediaType.startsWith("application/") && mediaType.endsWith("json") -> + if (content == null) { + EMPTY_REQUEST + } else { + Serializer.gson.toJson(content, T::class.java) + .toRequestBody((mediaType ?: JSON_MEDIA_TYPE).toMediaTypeOrNull()) + } + mediaType == XML_MEDIA_TYPE -> throw UnsupportedOperationException("xml not currently supported.") + mediaType == TEXT_MEDIA_TYPE -> { + val textualContent = when (content) { + is Char, is CharSequence -> content.toString() + is Number -> content.toString() + is Boolean -> content.toString() + else -> throw UnsupportedOperationException("requestBody currently only supports text body containing primitive types: characters, numbers, or booleans.") + } + textualContent.toRequestBody(mediaType.toMediaTypeOrNull()) + } + // TODO: this should be extended with other serializers + else -> throw UnsupportedOperationException("requestBody currently only supports JSON body, text body, byte body and File body.") + } + + protected inline fun responseBody(response: Response, mediaType: String? = JSON_MEDIA_TYPE): T? { + val body = response.body ?: return null + + if (T::class.java == Unit::class.java) { + // No need to parse the body when we're not interested in the body + // Useful when API is returning other Content-Type + return null + } else if (T::class.java == File::class.java) { + // return tempFile + val contentDisposition = response.header("Content-Disposition") + + val fileName = if (contentDisposition != null) { + // Get filename from the Content-Disposition header. + val pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?") + val matcher = pattern.matcher(contentDisposition) + if (matcher.find()) { + matcher.group(1) + ?.replace(".*[/\\\\]", "") + ?.replace(";", "") + } else { + null + } + } else { + null + } + + var prefix: String? + val suffix: String? + if (fileName == null) { + prefix = "download" + suffix = "" + } else { + val pos = fileName.lastIndexOf(".") + if (pos == -1) { + prefix = fileName + suffix = null + } else { + prefix = fileName.substring(0, pos) + suffix = fileName.substring(pos) + } + // Files.createTempFile requires the prefix to be at least three characters long + if (prefix.length < 3) { + prefix = "download" + } + } + + // Attention: if you are developing an android app that supports API Level 25 and below, please check flag supportAndroidApiLevel25AndBelow in https://openapi-generator.tech/docs/generators/kotlin#config-options + val tempFile = java.nio.file.Files.createTempFile(prefix, suffix).toFile() + tempFile.deleteOnExit() + body.byteStream().use { inputStream -> + tempFile.outputStream().use { tempFileOutputStream -> + inputStream.copyTo(tempFileOutputStream) + } + } + return tempFile as T + } + + return when { + mediaType == null || (mediaType.startsWith("application/") && mediaType.endsWith("json")) -> { + val bodyContent = body.string() + if (bodyContent.isEmpty()) { + return null + } + Serializer.gson.fromJson(bodyContent, (object: TypeToken(){}).getType()) + } + mediaType == OCTET_MEDIA_TYPE -> body.bytes() as? T + mediaType == TEXT_MEDIA_TYPE -> body.string() as? T + else -> throw UnsupportedOperationException("responseBody currently only supports JSON body, text body and byte body.") + } + } + + protected fun updateAuthParams(requestConfig: RequestConfig) { + if (requestConfig.headers[AUTHORIZATION].isNullOrEmpty()) { + accessToken?.let { accessToken -> + requestConfig.headers[AUTHORIZATION] = "Bearer $accessToken " + } + } + if (requestConfig.headers[AUTHORIZATION].isNullOrEmpty()) { + accessToken?.let { accessToken -> + requestConfig.headers[AUTHORIZATION] = "Bearer $accessToken " + } + } + } + + protected suspend inline fun request(requestConfig: RequestConfig): ApiResponse { + val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") + + // take authMethod from operation + updateAuthParams(requestConfig) + + val url = httpUrl.newBuilder() + .addEncodedPathSegments(requestConfig.path.trimStart('/')) + .apply { + requestConfig.query.forEach { query -> + query.value.forEach { queryValue -> + addQueryParameter(query.key, queryValue) + } + } + }.build() + + // take content-type/accept from spec or set to default (application/json) if not defined + if (requestConfig.body != null && requestConfig.headers[CONTENT_TYPE].isNullOrEmpty()) { + requestConfig.headers[CONTENT_TYPE] = JSON_MEDIA_TYPE + } + if (requestConfig.headers[ACCEPT].isNullOrEmpty()) { + requestConfig.headers[ACCEPT] = JSON_MEDIA_TYPE + } + val headers = requestConfig.headers + + if (headers[ACCEPT].isNullOrEmpty()) { + throw kotlin.IllegalStateException("Missing ACCEPT header. This is required.") + } + + val contentType = if (headers[CONTENT_TYPE] != null) { + // TODO: support multiple contentType options here. + (headers[CONTENT_TYPE] as String).substringBefore(";").lowercase(Locale.US) + } else { + null + } + + val request = when (requestConfig.method) { + RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) + RequestMethod.GET -> Request.Builder().url(url) + RequestMethod.HEAD -> Request.Builder().url(url).head() + RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(requestConfig.body, contentType)) + RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(requestConfig.body, contentType)) + RequestMethod.POST -> Request.Builder().url(url).post(requestBody(requestConfig.body, contentType)) + RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null) + }.apply { + val headersBuilder = Headers.Builder() + headers.forEach { header -> + headersBuilder.add(header.key, header.value) + } + this.headers(headersBuilder.build()) + }.build() + + val response: Response = suspendCancellableCoroutine { continuation -> + val call = client.newCall(request) + continuation.invokeOnCancellation { call.cancel() } + call.enqueue(object : Callback { + override fun onFailure(call: Call, e: IOException) { + continuation.resumeWithException(e) + } + override fun onResponse(call: Call, response: Response) { + continuation.resume(response) + } + }) + } + + val accept = response.header(CONTENT_TYPE)?.substringBefore(";")?.lowercase(Locale.US) + + // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") + return response.use { + when { + it.isRedirect -> Redirection( + it.code, + it.headers.toMultimap() + ) + it.isInformational -> Informational( + it.message, + it.code, + it.headers.toMultimap() + ) + it.isSuccessful -> Success( + responseBody(it, accept), + it.code, + it.headers.toMultimap() + ) + it.isClientError -> ClientError( + it.message, + it.body?.string(), + it.code, + it.headers.toMultimap() + ) + else -> ServerError( + it.message, + it.body?.string(), + it.code, + it.headers.toMultimap() + ) + } + } + } + + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime -> parseDateToQueryString(value) + is OffsetTime -> parseDateToQueryString(value) + is LocalDateTime -> parseDateToQueryString(value) + is LocalDate -> parseDateToQueryString(value) + is LocalTime -> parseDateToQueryString(value) + else -> value.toString() + } + + protected inline fun parseDateToQueryString(value : T): String { + /* + .replace("\"", "") converts the json object string to an actual string for the query parameter. + The moshi or gson adapter allows a more generic solution instead of trying to use a native + formatter. It also easily allows to provide a simple way to define a custom date format pattern + inside a gson/moshi adapter. + */ + return Serializer.gson.toJson(value, T::class.java).replace("\"", "") + } +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ApiResponse.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ApiResponse.kt new file mode 100644 index 0000000..8b70765 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ApiResponse.kt @@ -0,0 +1,43 @@ +package com.timr.api.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiResponse(val responseType: ResponseType): Response { + abstract val statusCode: Int + abstract val headers: Map> +} + +class Success( + val data: T, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +): ApiResponse(ResponseType.Success) + +class Informational( + val statusText: String, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiResponse(ResponseType.Informational) + +class Redirection( + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiResponse(ResponseType.Redirection) + +class ClientError( + val message: String? = null, + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiResponse(ResponseType.ClientError) + +class ServerError( + val message: String? = null, + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +): ApiResponse(ResponseType.ServerError) diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ByteArrayAdapter.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 0000000..5209d96 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ByteArrayAdapter.kt @@ -0,0 +1,33 @@ +package com.timr.api.infrastructure + +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonWriter +import com.google.gson.stream.JsonToken.NULL +import java.io.IOException + +class ByteArrayAdapter : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: ByteArray?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(String(value)) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): ByteArray? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return out.nextString().toByteArray() + } + } + } +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/Errors.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/Errors.kt new file mode 100644 index 0000000..a8a7024 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/Errors.kt @@ -0,0 +1,18 @@ +@file:Suppress("unused") +package com.timr.api.infrastructure + +import java.lang.RuntimeException + +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/LocalDateAdapter.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/LocalDateAdapter.kt new file mode 100644 index 0000000..d504714 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/LocalDateAdapter.kt @@ -0,0 +1,35 @@ +package com.timr.api.infrastructure + +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonWriter +import com.google.gson.stream.JsonToken.NULL +import java.io.IOException +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class LocalDateAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE) : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: LocalDate?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(formatter.format(value)) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): LocalDate? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return LocalDate.parse(out.nextString(), formatter) + } + } + } +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/LocalDateTimeAdapter.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 0000000..b17acd5 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/LocalDateTimeAdapter.kt @@ -0,0 +1,35 @@ +package com.timr.api.infrastructure + +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonWriter +import com.google.gson.stream.JsonToken.NULL +import java.io.IOException +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +class LocalDateTimeAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME) : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: LocalDateTime?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(formatter.format(value)) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): LocalDateTime? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return LocalDateTime.parse(out.nextString(), formatter) + } + } + } +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/OffsetDateTimeAdapter.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 0000000..bc23de8 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,35 @@ +package com.timr.api.infrastructure + +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonWriter +import com.google.gson.stream.JsonToken.NULL +import java.io.IOException +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME) : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: OffsetDateTime?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(formatter.format(value)) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): OffsetDateTime? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return OffsetDateTime.parse(out.nextString(), formatter) + } + } + } +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/PartConfig.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/PartConfig.kt new file mode 100644 index 0000000..8963569 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/PartConfig.kt @@ -0,0 +1,19 @@ +package com.timr.api.infrastructure + +/** + * Defines a config object for a given part of a multi-part request. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + * + * @property headers The headers for this part + * @property body The body content for this part + * @property serializer Optional custom serializer for JSON content. When provided, this will be + * used instead of the default serialization for parts with application/json + * content-type. This allows capturing type information at the call site to + * avoid issues with type erasure in kotlinx.serialization. + */ +data class PartConfig( + val headers: MutableMap = mutableMapOf(), + val body: T? = null, + val serializer: ((Any?) -> String)? = null +) diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/RequestConfig.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/RequestConfig.kt new file mode 100644 index 0000000..223e7e1 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/RequestConfig.kt @@ -0,0 +1,19 @@ +package com.timr.api.infrastructure + +/** + * Defines a config object for a given request. + * NOTE: This object doesn't include 'body' because it + * allows for caching of the constructed object + * for many request definitions. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class RequestConfig( + val method: RequestMethod, + val path: String, + val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), + val query: MutableMap> = mutableMapOf(), + val requiresAuthentication: Boolean, + val body: T? = null +) diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/RequestMethod.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/RequestMethod.kt new file mode 100644 index 0000000..f4537e7 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package com.timr.api.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ResponseExtensions.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ResponseExtensions.kt new file mode 100644 index 0000000..6b6e4d5 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +package com.timr.api.infrastructure + +import okhttp3.Response + +/** + * Provides an extension to evaluation whether the response is a 1xx code + */ +val Response.isInformational : Boolean get() = this.code in 100..199 + +/** + * Provides an extension to evaluation whether the response is a 3xx code + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +val Response.isRedirect : Boolean get() = this.code in 300..399 + +/** + * Provides an extension to evaluation whether the response is a 4xx code + */ +val Response.isClientError : Boolean get() = this.code in 400..499 + +/** + * Provides an extension to evaluation whether the response is a 5xx (Standard) through 999 (non-standard) code + */ +val Response.isServerError : Boolean get() = this.code in 500..999 diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/Serializer.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/Serializer.kt new file mode 100644 index 0000000..92a2ac6 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/infrastructure/Serializer.kt @@ -0,0 +1,22 @@ +package com.timr.api.infrastructure + +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.OffsetDateTime +import java.util.UUID + +object Serializer { + @JvmStatic + val gsonBuilder: GsonBuilder = GsonBuilder() + .registerTypeAdapter(OffsetDateTime::class.java, OffsetDateTimeAdapter()) + .registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter()) + .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter()) + .registerTypeAdapter(ByteArray::class.java, ByteArrayAdapter()) + + @JvmStatic + val gson: Gson by lazy { + gsonBuilder.create() + } +} diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Accounts.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Accounts.kt new file mode 100644 index 0000000..a936f8a --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Accounts.kt @@ -0,0 +1,61 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.OvertimeSurchargeAccounts +import com.timr.api.models.TimeAccount +import com.timr.api.models.VacationAccount + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param lastBalanceDate date of last balance + * @param timeAccount + * @param overtimeSurchargeAccounts + * @param vacationAccount + */ + + +data class Accounts ( + + /* date of last balance */ + @SerializedName("last_balance_date") + val lastBalanceDate: java.time.LocalDate?, + + @SerializedName("time_account") + val timeAccount: TimeAccount? = null, + + @SerializedName("overtime_surcharge_accounts") + val overtimeSurchargeAccounts: kotlin.collections.List? = null, + + @SerializedName("vacation_account") + val vacationAccount: VacationAccount? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTime.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTime.kt new file mode 100644 index 0000000..d6cae96 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTime.kt @@ -0,0 +1,58 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeAutomatic +import com.timr.api.models.BreakTimeManual +import com.timr.api.models.BreakTimeOngoing +import com.timr.api.models.BreakTimeType + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param type + * @param durationMinutes Duration of break in minutes + * @param start RFC 3339 date-time (ISO-8601) + * @param end RFC 3339 date-time (ISO-8601) + */ + + +interface BreakTime { + + @get:SerializedName("type") + val type: BreakTimeType + /* Duration of break in minutes */ + @get:SerializedName("duration_minutes") + val durationMinutes: kotlin.Int + /* RFC 3339 date-time (ISO-8601) */ + @get:SerializedName("start") + val start: java.time.OffsetDateTime? + /* RFC 3339 date-time (ISO-8601) */ + @get:SerializedName("end") + val end: java.time.OffsetDateTime? + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeAutomatic.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeAutomatic.kt new file mode 100644 index 0000000..d431c38 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeAutomatic.kt @@ -0,0 +1,61 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeType + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param type + * @param durationMinutes Duration of break in minutes + * @param start RFC 3339 date-time (ISO-8601) + * @param end RFC 3339 date-time (ISO-8601) + */ + + +data class BreakTimeAutomatic ( + + @SerializedName("type") + val type: BreakTimeType, + + /* Duration of break in minutes */ + @SerializedName("duration_minutes") + val durationMinutes: kotlin.Int, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime?, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeBase.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeBase.kt new file mode 100644 index 0000000..eb98964 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeBase.kt @@ -0,0 +1,46 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeType + +import com.google.gson.annotations.SerializedName + +/** + * Members shared by every kind of break time, including the discriminator. + * + * @param type + */ + + +data class BreakTimeBase ( + + @SerializedName("type") + val type: BreakTimeType + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeManual.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeManual.kt new file mode 100644 index 0000000..0ba2399 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeManual.kt @@ -0,0 +1,61 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeType + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param type + * @param durationMinutes Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. + * @param start start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + * @param end start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + */ + + +data class BreakTimeManual ( + + @SerializedName("type") + val type: BreakTimeType, + + /* Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. */ + @SerializedName("duration_minutes") + val durationMinutes: kotlin.Int, + + /* start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. */ + @SerializedName("start") + val start: java.time.OffsetDateTime? = null, + + /* start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeOngoing.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeOngoing.kt new file mode 100644 index 0000000..519bed1 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeOngoing.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeType + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param type + * @param start RFC 3339 date-time (ISO-8601) + */ + + +data class BreakTimeOngoing ( + + @SerializedName("type") + val type: BreakTimeType, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeType.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeType.kt new file mode 100644 index 0000000..c1e24f0 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeType.kt @@ -0,0 +1,72 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Kind of break. `manual` was entered by the user, `automatic` was deducted by timr, `ongoing` is a break that has started and not yet ended. + * + * Values: MANUAL,ONGOING,AUTOMATIC + */ + +enum class BreakTimeType(val value: kotlin.String) { + + @SerializedName(value = "manual") + MANUAL("manual"), + + @SerializedName(value = "ongoing") + ONGOING("ongoing"), + + @SerializedName(value = "automatic") + AUTOMATIC("automatic"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is BreakTimeType) "$data" else null + + /** + * Returns a valid [BreakTimeType] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): BreakTimeType? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeUpdate.kt new file mode 100644 index 0000000..f5bfafe --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BreakTimeUpdate.kt @@ -0,0 +1,57 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeManual +import com.timr.api.models.BreakTimeOngoing +import com.timr.api.models.BreakTimeType + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param type + * @param durationMinutes Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. + * @param start RFC 3339 date-time (ISO-8601) + * @param end start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + */ + + +interface BreakTimeUpdate { + + @get:SerializedName("type") + val type: BreakTimeType + /* Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. */ + @get:SerializedName("duration_minutes") + val durationMinutes: kotlin.Int + /* RFC 3339 date-time (ISO-8601) */ + @get:SerializedName("start") + val start: java.time.OffsetDateTime + /* start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. */ + @get:SerializedName("end") + val end: java.time.OffsetDateTime? + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BudgetPlanningType.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BudgetPlanningType.kt new file mode 100644 index 0000000..453f4b7 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BudgetPlanningType.kt @@ -0,0 +1,75 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set for the remaining two types all budget properties are supported + * + * Values: NONE,TASK_HOURLY_RATE,USER_HOURLY_RATE,FIXED_PRICE + */ + +enum class BudgetPlanningType(val value: kotlin.String) { + + @SerializedName(value = "none") + NONE("none"), + + @SerializedName(value = "task_hourly_rate") + TASK_HOURLY_RATE("task_hourly_rate"), + + @SerializedName(value = "user_hourly_rate") + USER_HOURLY_RATE("user_hourly_rate"), + + @SerializedName(value = "fixed_price") + FIXED_PRICE("fixed_price"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is BudgetPlanningType) "$data" else null + + /** + * Returns a valid [BudgetPlanningType] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): BudgetPlanningType? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BudgetPlanningTypeRequest.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BudgetPlanningTypeRequest.kt new file mode 100644 index 0000000..5e5c38a --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/BudgetPlanningTypeRequest.kt @@ -0,0 +1,78 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set * inherited: budget settings are inherited from the parent task for the remaining two types all budget properties are supported + * + * Values: NONE,TASK_HOURLY_RATE,USER_HOURLY_RATE,FIXED_PRICE,INHERITED + */ + +enum class BudgetPlanningTypeRequest(val value: kotlin.String) { + + @SerializedName(value = "none") + NONE("none"), + + @SerializedName(value = "task_hourly_rate") + TASK_HOURLY_RATE("task_hourly_rate"), + + @SerializedName(value = "user_hourly_rate") + USER_HOURLY_RATE("user_hourly_rate"), + + @SerializedName(value = "fixed_price") + FIXED_PRICE("fixed_price"), + + @SerializedName(value = "inherited") + INHERITED("inherited"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is BudgetPlanningTypeRequest) "$data" else null + + /** + * Returns a valid [BudgetPlanningTypeRequest] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): BudgetPlanningTypeRequest? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Car.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Car.kt new file mode 100644 index 0000000..c169987 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Car.kt @@ -0,0 +1,67 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * A vehicle identified by `name` and license `plate`. `usable` says whether it can currently be selected. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param plate + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param usable + * @param metadata + */ + + +data class Car ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + @SerializedName("plate") + val plate: kotlin.String, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String?, + + @SerializedName("usable") + val usable: kotlin.Boolean, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarCreate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarCreate.kt new file mode 100644 index 0000000..12f6f70 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarCreate.kt @@ -0,0 +1,62 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param name + * @param plate + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param usable + * @param metadata + */ + + +data class CarCreate ( + + @SerializedName("name") + val name: kotlin.String, + + @SerializedName("plate") + val plate: kotlin.String, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? = null, + + @SerializedName("usable") + val usable: kotlin.Boolean? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarPartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarPartial.kt new file mode 100644 index 0000000..1eec812 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarPartial.kt @@ -0,0 +1,59 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param plate + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + */ + + +data class CarPartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + @SerializedName("plate") + val plate: kotlin.String, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarUpdate.kt new file mode 100644 index 0000000..598085f --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarUpdate.kt @@ -0,0 +1,62 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param name + * @param plate + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param usable + * @param metadata + */ + + +data class CarUpdate ( + + @SerializedName("name") + val name: kotlin.String? = null, + + @SerializedName("plate") + val plate: kotlin.String? = null, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? = null, + + @SerializedName("usable") + val usable: kotlin.Boolean? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarsPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarsPage.kt new file mode 100644 index 0000000..3fbaafb --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarsPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.Car + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class CarsPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarsSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarsSortColumn.kt new file mode 100644 index 0000000..49a0890 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/CarsSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Cars. + * + * Values: NAME + */ + +enum class CarsSortColumn(val value: kotlin.String) { + + @SerializedName(value = "name") + NAME("name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is CarsSortColumn) "$data" else null + + /** + * Returns a valid [CarsSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): CarsSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DailyWorkSchedule.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DailyWorkSchedule.kt new file mode 100644 index 0000000..ac8c3f1 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DailyWorkSchedule.kt @@ -0,0 +1,52 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.NormalWorkingTimes + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param targetDurationMinutes value in minutes + * @param normalWorkingTimes this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set + */ + + +data class DailyWorkSchedule ( + + /* value in minutes */ + @SerializedName("target_duration_minutes") + val targetDurationMinutes: kotlin.Long, + + /* this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set */ + @SerializedName("normal_working_times") + val normalWorkingTimes: kotlin.collections.List? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryPage.kt new file mode 100644 index 0000000..b3d9943 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DeletedEntryPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class DeletedEntryPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryPartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryPartial.kt new file mode 100644 index 0000000..2de2376 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryPartial.kt @@ -0,0 +1,57 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.UserPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param lastModified Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @param lastModifiedBy Read-only. The User who last modified the entry, or null if the change was not made in a user context. + */ + + +data class DeletedEntryPartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + /* Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + @SerializedName("last_modified") + val lastModified: java.time.OffsetDateTime, + + /* Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + @SerializedName("last_modified_by") + val lastModifiedBy: UserPartial? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntrySortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntrySortColumn.kt new file mode 100644 index 0000000..6e5d22c --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntrySortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for deleted entries. + * + * Values: LAST_MODIFIED + */ + +enum class DeletedEntrySortColumn(val value: kotlin.String) { + + @SerializedName(value = "last_modified") + LAST_MODIFIED("last_modified"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is DeletedEntrySortColumn) "$data" else null + + /** + * Returns a valid [DeletedEntrySortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): DeletedEntrySortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryWithMetadata.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryWithMetadata.kt new file mode 100644 index 0000000..77d4c31 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryWithMetadata.kt @@ -0,0 +1,61 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.UserPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param lastModified Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @param lastModifiedBy Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @param metadata + */ + + +data class DeletedEntryWithMetadata ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + /* Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + @SerializedName("last_modified") + val lastModified: java.time.OffsetDateTime, + + /* Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + @SerializedName("last_modified_by") + val lastModifiedBy: UserPartial?, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryWithMetadataPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryWithMetadataPage.kt new file mode 100644 index 0000000..a7b721f --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DeletedEntryWithMetadataPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DeletedEntryWithMetadata + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class DeletedEntryWithMetadataPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLog.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLog.kt new file mode 100644 index 0000000..382cde2 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLog.kt @@ -0,0 +1,155 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.CarPartial +import com.timr.api.models.DriveLogCategoryPartial +import com.timr.api.models.DriveLogStatus +import com.timr.api.models.Duration +import com.timr.api.models.Location +import com.timr.api.models.Platform +import com.timr.api.models.UserPartial +import com.timr.api.models.VenuePartial + +import com.google.gson.annotations.SerializedName + +/** + * One trip in a `car`: `start` and `end`, `start_mileage` and `end_mileage` with the resulting `distance`, the `purpose`, the places `visited`, and its `drive_log_category`. May include a recorded GPS `route`. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param start RFC 3339 date-time (ISO-8601) + * @param end RFC 3339 date-time (ISO-8601) + * @param duration + * @param changed + * @param startMileage + * @param endMileage + * @param distance Driven distance in kilometers + * @param route + * @param purpose + * @param visited + * @param user + * @param car + * @param driveLogCategory + * @param startVenue + * @param endVenue + * @param hasTrack + * @param startLocation + * @param endLocation + * @param startPlatform + * @param endPlatform + * @param lastModified Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @param lastModifiedBy Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @param status + * @param metadata + */ + + +data class DriveLog ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime?, + + @SerializedName("duration") + val duration: Duration?, + + @SerializedName("changed") + val changed: kotlin.Boolean, + + @SerializedName("start_mileage") + val startMileage: kotlin.Long, + + @SerializedName("end_mileage") + val endMileage: kotlin.Long?, + + /* Driven distance in kilometers */ + @SerializedName("distance") + val distance: kotlin.Long?, + + @SerializedName("route") + val route: kotlin.String?, + + @SerializedName("purpose") + val purpose: kotlin.String?, + + @SerializedName("visited") + val visited: kotlin.String?, + + @SerializedName("user") + val user: UserPartial, + + @SerializedName("car") + val car: CarPartial, + + @SerializedName("drive_log_category") + val driveLogCategory: DriveLogCategoryPartial, + + @SerializedName("start_venue") + val startVenue: VenuePartial?, + + @SerializedName("end_venue") + val endVenue: VenuePartial?, + + @SerializedName("has_track") + val hasTrack: kotlin.Boolean, + + @SerializedName("start_location") + val startLocation: Location?, + + @SerializedName("end_location") + val endLocation: Location?, + + @SerializedName("start_platform") + val startPlatform: Platform?, + + @SerializedName("end_platform") + val endPlatform: Platform?, + + /* Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + @SerializedName("last_modified") + val lastModified: java.time.OffsetDateTime, + + /* Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + @SerializedName("last_modified_by") + val lastModifiedBy: UserPartial?, + + @SerializedName("status") + val status: DriveLogStatus, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategoriesPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategoriesPage.kt new file mode 100644 index 0000000..0cb56ea --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategoriesPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DriveLogCategory + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class DriveLogCategoriesPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategoriesSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategoriesSortColumn.kt new file mode 100644 index 0000000..91e7555 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategoriesSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Drive Log Categories. + * + * Values: NAME + */ + +enum class DriveLogCategoriesSortColumn(val value: kotlin.String) { + + @SerializedName(value = "name") + NAME("name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is DriveLogCategoriesSortColumn) "$data" else null + + /** + * Returns a valid [DriveLogCategoriesSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): DriveLogCategoriesSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategory.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategory.kt new file mode 100644 index 0000000..fe432b2 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategory.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.UserPartial + +import com.google.gson.annotations.SerializedName + +/** + * A drive log category with a `name` and a display `color`; `business` marks it as business travel. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param business + * @param color + * @param lastModified Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @param lastModifiedBy Read-only. The User who last modified the entry, or null if the change was not made in a user context. + */ + + +data class DriveLogCategory ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + @SerializedName("business") + val business: kotlin.Boolean, + + @SerializedName("color") + val color: kotlin.String, + + /* Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + @SerializedName("last_modified") + val lastModified: java.time.OffsetDateTime, + + /* Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + @SerializedName("last_modified_by") + val lastModifiedBy: UserPartial? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategoryPartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategoryPartial.kt new file mode 100644 index 0000000..d2898e2 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCategoryPartial.kt @@ -0,0 +1,58 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param business + * @param color + */ + + +data class DriveLogCategoryPartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + @SerializedName("business") + val business: kotlin.Boolean, + + @SerializedName("color") + val color: kotlin.String + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCreate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCreate.kt new file mode 100644 index 0000000..bf63338 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogCreate.kt @@ -0,0 +1,105 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DriveLogStatus +import com.timr.api.models.LocationCreate + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start RFC 3339 date-time (ISO-8601) + * @param changed + * @param startMileage + * @param driveLogCategoryId + * @param status + * @param userId + * @param carId + * @param end RFC 3339 date-time (ISO-8601) + * @param endMileage + * @param route + * @param purpose + * @param visited + * @param metadata + * @param startLocation + * @param endLocation + */ + + +data class DriveLogCreate ( + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime, + + @SerializedName("changed") + val changed: kotlin.Boolean, + + @SerializedName("start_mileage") + val startMileage: kotlin.Long, + + @SerializedName("drive_log_category_id") + val driveLogCategoryId: kotlin.String, + + @SerializedName("status") + val status: DriveLogStatus, + + @SerializedName("user_id") + val userId: kotlin.String, + + @SerializedName("car_id") + val carId: kotlin.String, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null, + + @SerializedName("end_mileage") + val endMileage: kotlin.Long? = null, + + @SerializedName("route") + val route: kotlin.String? = null, + + @SerializedName("purpose") + val purpose: kotlin.String? = null, + + @SerializedName("visited") + val visited: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null, + + @SerializedName("start_location") + val startLocation: LocationCreate? = null, + + @SerializedName("end_location") + val endLocation: LocationCreate? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogStatus.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogStatus.kt new file mode 100644 index 0000000..047cae7 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogStatus.kt @@ -0,0 +1,84 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Processing state of a Drive Log. `running` means the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + * + * Values: CHANGEABLE,LOCKED,APPROVED,CLEARED,CLOSED,ARCHIVED,RUNNING + */ + +enum class DriveLogStatus(val value: kotlin.String) { + + @SerializedName(value = "changeable") + CHANGEABLE("changeable"), + + @SerializedName(value = "locked") + LOCKED("locked"), + + @SerializedName(value = "approved") + APPROVED("approved"), + + @SerializedName(value = "cleared") + CLEARED("cleared"), + + @SerializedName(value = "closed") + CLOSED("closed"), + + @SerializedName(value = "archived") + ARCHIVED("archived"), + + @SerializedName(value = "running") + RUNNING("running"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is DriveLogStatus) "$data" else null + + /** + * Returns a valid [DriveLogStatus] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): DriveLogStatus? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogUpdate.kt new file mode 100644 index 0000000..e5e3b41 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogUpdate.kt @@ -0,0 +1,97 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DriveLogStatus +import com.timr.api.models.LocationUpdate + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start RFC 3339 date-time (ISO-8601) + * @param end RFC 3339 date-time (ISO-8601) + * @param changed + * @param startMileage + * @param endMileage + * @param route + * @param purpose + * @param visited + * @param driveLogCategoryId + * @param status + * @param metadata + * @param startLocation + * @param endLocation + */ + + +data class DriveLogUpdate ( + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime? = null, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null, + + @SerializedName("changed") + val changed: kotlin.Boolean? = null, + + @SerializedName("start_mileage") + val startMileage: kotlin.Long? = null, + + @SerializedName("end_mileage") + val endMileage: kotlin.Long? = null, + + @SerializedName("route") + val route: kotlin.String? = null, + + @SerializedName("purpose") + val purpose: kotlin.String? = null, + + @SerializedName("visited") + val visited: kotlin.String? = null, + + @SerializedName("drive_log_category_id") + val driveLogCategoryId: kotlin.String? = null, + + @SerializedName("status") + val status: DriveLogStatus? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null, + + @SerializedName("start_location") + val startLocation: LocationUpdate? = null, + + @SerializedName("end_location") + val endLocation: LocationUpdate? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogUpsert.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogUpsert.kt new file mode 100644 index 0000000..c241205 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogUpsert.kt @@ -0,0 +1,88 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DriveLogStatus + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start RFC 3339 date-time (ISO-8601) + * @param end RFC 3339 date-time (ISO-8601) + * @param changed + * @param startMileage + * @param endMileage + * @param route + * @param purpose + * @param visited + * @param driveLogCategoryId + * @param status + * @param metadata + */ + + +data class DriveLogUpsert ( + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime? = null, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null, + + @SerializedName("changed") + val changed: kotlin.Boolean? = null, + + @SerializedName("start_mileage") + val startMileage: kotlin.Long? = null, + + @SerializedName("end_mileage") + val endMileage: kotlin.Long? = null, + + @SerializedName("route") + val route: kotlin.String? = null, + + @SerializedName("purpose") + val purpose: kotlin.String? = null, + + @SerializedName("visited") + val visited: kotlin.String? = null, + + @SerializedName("drive_log_category_id") + val driveLogCategoryId: kotlin.String? = null, + + @SerializedName("status") + val status: DriveLogStatus? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogsPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogsPage.kt new file mode 100644 index 0000000..e7ab73b --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogsPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DriveLog + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class DriveLogsPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogsSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogsSortColumn.kt new file mode 100644 index 0000000..90c019b --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DriveLogsSortColumn.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Drive Logs. + * + * Values: START,LAST_MODIFIED + */ + +enum class DriveLogsSortColumn(val value: kotlin.String) { + + @SerializedName(value = "start") + START("start"), + + @SerializedName(value = "last_modified") + LAST_MODIFIED("last_modified"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is DriveLogsSortColumn) "$data" else null + + /** + * Returns a valid [DriveLogsSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): DriveLogsSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Duration.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Duration.kt new file mode 100644 index 0000000..12c8441 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Duration.kt @@ -0,0 +1,56 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DurationType + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param type + * @param minutes Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + * @param minutesRounded Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + */ + + +data class Duration ( + + @SerializedName("type") + val type: DurationType, + + /* Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User */ + @SerializedName("minutes") + val minutes: kotlin.Long, + + /* Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User */ + @SerializedName("minutes_rounded") + val minutesRounded: kotlin.Long + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DurationType.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DurationType.kt new file mode 100644 index 0000000..3bcbf43 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DurationType.kt @@ -0,0 +1,72 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * How the duration of a single recording is expressed. Not to be confused with `DurationUnit`, which states the unit a Working Time Type is recorded in. + * + * Values: MINUTES,FULL_DAY,HALF_DAY + */ + +enum class DurationType(val value: kotlin.String) { + + @SerializedName(value = "minutes") + MINUTES("minutes"), + + @SerializedName(value = "full_day") + FULL_DAY("full_day"), + + @SerializedName(value = "half_day") + HALF_DAY("half_day"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is DurationType) "$data" else null + + /** + * Returns a valid [DurationType] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): DurationType? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DurationUnit.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DurationUnit.kt new file mode 100644 index 0000000..7bf1567 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/DurationUnit.kt @@ -0,0 +1,72 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Unit a Working Time Type is recorded in. Not to be confused with `DurationType`, which states how an individual recording's duration is expressed. + * + * Values: MINUTES,HALF_DAYS,DAYS + */ + +enum class DurationUnit(val value: kotlin.String) { + + @SerializedName(value = "minutes") + MINUTES("minutes"), + + @SerializedName(value = "half_days") + HALF_DAYS("half_days"), + + @SerializedName(value = "days") + DAYS("days"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is DurationUnit) "$data" else null + + /** + * Returns a valid [DurationUnit] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): DurationUnit? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Error.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Error.kt new file mode 100644 index 0000000..c46193f --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Error.kt @@ -0,0 +1,74 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.ErrorEntry + +import com.google.gson.annotations.SerializedName + +/** + * TIMR error response body, extending the Problem Details base with `timestamp`, `trace_id` and per-field `errors[]` for validation, binding, constraint, request-body deserialization, and reference-not-found errors. The semantic identifier is encoded in the `type` URI (e.g. `https://errors.timr.com/conflict/resource-outdated`). Slugs in the `type` URI are lowercase kebab-case: a top-level category (`validation`, `reference-not-found`, `conflict`, `forbidden`, `internal`) optionally followed by a specific sub-slug (`conflict/resource-outdated`, `validation/end-time-required`, `reference-not-found/user`). + * + * @param type + * @param title + * @param status + * @param timestamp + * @param detail + * @param instance + * @param traceId + * @param errors + */ + + +data class Error ( + + @SerializedName("type") + val type: java.net.URI, + + @SerializedName("title") + val title: kotlin.String, + + @SerializedName("status") + val status: kotlin.Int, + + @SerializedName("timestamp") + val timestamp: java.time.OffsetDateTime, + + @SerializedName("detail") + val detail: kotlin.String? = null, + + @SerializedName("instance") + val instance: kotlin.String? = null, + + @SerializedName("trace_id") + val traceId: kotlin.String? = null, + + @SerializedName("errors") + val errors: kotlin.collections.List? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ErrorEntry.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ErrorEntry.kt new file mode 100644 index 0000000..ae50c46 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ErrorEntry.kt @@ -0,0 +1,53 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Field-level or sub-error entry, shaped like a sub-ProblemDetail. The `type` URI identifies the specific constraint or sub-error category (e.g. `validation/not-null` for a Bean Validation `@NotNull`, `validation/paused-working-time` for a TIMR custom validator code, `validation/type-mismatch` for a value that does not fit its target type, `validation/unknown-property` for a property the resource does not declare, `reference-not-found/user` for a `MappingException`). `field` is the JSONPath of the offending property in the request body, rooted at `$` — array elements included. An error about a query parameter names it plainly instead, without the `$.` prefix. + * + * @param type + * @param detail + * @param `field` + */ + + +data class ErrorEntry ( + + @SerializedName("type") + val type: java.net.URI, + + @SerializedName("detail") + val detail: kotlin.String, + + @SerializedName("field") + val `field`: kotlin.String? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/FlexTimeIndicator.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/FlexTimeIndicator.kt new file mode 100644 index 0000000..d2aac5d --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/FlexTimeIndicator.kt @@ -0,0 +1,72 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Traffic-light rating of the flex time balance. The thresholds are an account setting and are not part of this contract. + * + * Values: GREEN,YELLOW,RED + */ + +enum class FlexTimeIndicator(val value: kotlin.String) { + + @SerializedName(value = "green") + GREEN("green"), + + @SerializedName(value = "yellow") + YELLOW("yellow"), + + @SerializedName(value = "red") + RED("red"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is FlexTimeIndicator) "$data" else null + + /** + * Returns a valid [FlexTimeIndicator] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): FlexTimeIndicator? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Holiday.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Holiday.kt new file mode 100644 index 0000000..b870494 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Holiday.kt @@ -0,0 +1,54 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param date RFC 3339 date (ISO-8601) + * @param description + * @param halfDay + */ + + +data class Holiday ( + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("date") + val date: java.time.LocalDate, + + @SerializedName("description") + val description: kotlin.String, + + @SerializedName("half_day") + val halfDay: kotlin.Boolean + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidayCalendarPartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidayCalendarPartial.kt new file mode 100644 index 0000000..c0c96cc --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidayCalendarPartial.kt @@ -0,0 +1,50 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * A holiday calendar. Its holidays are either generated automatically or maintained manually. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param description + */ + + +data class HolidayCalendarPartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("description") + val description: kotlin.String + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidayCalendarsPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidayCalendarsPage.kt new file mode 100644 index 0000000..86a4718 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidayCalendarsPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.HolidayCalendarPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class HolidayCalendarsPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidayCalendarsSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidayCalendarsSortColumn.kt new file mode 100644 index 0000000..85c88bb --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidayCalendarsSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Holiday Calendars. + * + * Values: DESCRIPTION + */ + +enum class HolidayCalendarsSortColumn(val value: kotlin.String) { + + @SerializedName(value = "description") + DESCRIPTION("description"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is HolidayCalendarsSortColumn) "$data" else null + + /** + * Returns a valid [HolidayCalendarsSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): HolidayCalendarsSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidaysPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidaysPage.kt new file mode 100644 index 0000000..3a3356e --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidaysPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.Holiday + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class HolidaysPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidaysSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidaysSortColumn.kt new file mode 100644 index 0000000..7fca70e --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/HolidaysSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Holidays. + * + * Values: DATE + */ + +enum class HolidaysSortColumn(val value: kotlin.String) { + + @SerializedName(value = "date") + DATE("date"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is HolidaysSortColumn) "$data" else null + + /** + * Returns a valid [HolidaysSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): HolidaysSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Location.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Location.kt new file mode 100644 index 0000000..a2fd461 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Location.kt @@ -0,0 +1,65 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param lat Latitude in decimal degrees. + * @param lon Longitude in decimal degrees. + * @param accuracy Horizontal GPS accuracy in meters. + * @param timestamp RFC 3339 date-time (ISO-8601) + * @param formattedAddress + */ + + +data class Location ( + + /* Latitude in decimal degrees. */ + @SerializedName("lat") + val lat: kotlin.Float?, + + /* Longitude in decimal degrees. */ + @SerializedName("lon") + val lon: kotlin.Float?, + + /* Horizontal GPS accuracy in meters. */ + @SerializedName("accuracy") + val accuracy: kotlin.Float?, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("timestamp") + val timestamp: java.time.OffsetDateTime? = null, + + @SerializedName("formatted_address") + val formattedAddress: kotlin.String? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/LocationCreate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/LocationCreate.kt new file mode 100644 index 0000000..90ce757 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/LocationCreate.kt @@ -0,0 +1,65 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param lat Latitude in decimal degrees. + * @param lon Longitude in decimal degrees. + * @param timestamp RFC 3339 date-time (ISO-8601) + * @param formattedAddress + * @param accuracy Horizontal GPS accuracy in meters. + */ + + +data class LocationCreate ( + + /* Latitude in decimal degrees. */ + @SerializedName("lat") + val lat: kotlin.Float, + + /* Longitude in decimal degrees. */ + @SerializedName("lon") + val lon: kotlin.Float, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("timestamp") + val timestamp: java.time.OffsetDateTime? = null, + + @SerializedName("formatted_address") + val formattedAddress: kotlin.String? = null, + + /* Horizontal GPS accuracy in meters. */ + @SerializedName("accuracy") + val accuracy: kotlin.Float? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/LocationUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/LocationUpdate.kt new file mode 100644 index 0000000..b8377f4 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/LocationUpdate.kt @@ -0,0 +1,65 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param lat Latitude in decimal degrees. + * @param lon Longitude in decimal degrees. + * @param timestamp RFC 3339 date-time (ISO-8601) + * @param formattedAddress + * @param accuracy Horizontal GPS accuracy in meters. + */ + + +data class LocationUpdate ( + + /* Latitude in decimal degrees. */ + @SerializedName("lat") + val lat: kotlin.Float? = null, + + /* Longitude in decimal degrees. */ + @SerializedName("lon") + val lon: kotlin.Float? = null, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("timestamp") + val timestamp: java.time.OffsetDateTime? = null, + + @SerializedName("formatted_address") + val formattedAddress: kotlin.String? = null, + + /* Horizontal GPS accuracy in meters. */ + @SerializedName("accuracy") + val accuracy: kotlin.Float? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/NormalWorkingTimes.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/NormalWorkingTimes.kt new file mode 100644 index 0000000..8b9b2cd --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/NormalWorkingTimes.kt @@ -0,0 +1,49 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start + * @param end + */ + + +data class NormalWorkingTimes ( + + @SerializedName("start") + val start: kotlin.String? = null, + + @SerializedName("end") + val end: kotlin.String? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/OvertimeSurchargeAccount.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/OvertimeSurchargeAccount.kt new file mode 100644 index 0000000..73837b1 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/OvertimeSurchargeAccount.kt @@ -0,0 +1,53 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param balanceLastPeriodMinutes + * @param newMinutes + * @param balanceTotalMinutes + */ + + +data class OvertimeSurchargeAccount ( + + @SerializedName("balance_last_period_minutes") + val balanceLastPeriodMinutes: kotlin.Int?, + + @SerializedName("new_minutes") + val newMinutes: kotlin.Int?, + + @SerializedName("balance_total_minutes") + val balanceTotalMinutes: kotlin.Int? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/OvertimeSurchargeAccounts.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/OvertimeSurchargeAccounts.kt new file mode 100644 index 0000000..17cf924 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/OvertimeSurchargeAccounts.kt @@ -0,0 +1,59 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.OvertimeSurchargeAccount +import com.timr.api.models.OvertimeSurchargeRule + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param rule + * @param percentage + * @param overtime + * @param surcharge + */ + + +data class OvertimeSurchargeAccounts ( + + @SerializedName("rule") + val rule: OvertimeSurchargeRule, + + @SerializedName("percentage") + val percentage: java.math.BigDecimal?, + + @SerializedName("overtime") + val overtime: OvertimeSurchargeAccount, + + @SerializedName("surcharge") + val surcharge: OvertimeSurchargeAccount + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/OvertimeSurchargeRule.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/OvertimeSurchargeRule.kt new file mode 100644 index 0000000..6f0d4ef --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/OvertimeSurchargeRule.kt @@ -0,0 +1,54 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param shortName + */ + + +data class OvertimeSurchargeRule ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: java.util.UUID, + + @SerializedName("name") + val name: kotlin.String, + + @SerializedName("short_name") + val shortName: kotlin.String + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/PagingInformation.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/PagingInformation.kt new file mode 100644 index 0000000..5017866 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/PagingInformation.kt @@ -0,0 +1,46 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + */ + + +data class PagingInformation ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Platform.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Platform.kt new file mode 100644 index 0000000..2e294f8 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Platform.kt @@ -0,0 +1,81 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Platform the entry was recorded on. + * + * Values: TIMR_WEB,TIMR_MOBILE,TOUR_MOBILE,TIMR_TERMINAL,SYNC_API,TIMR_API + */ + +enum class Platform(val value: kotlin.String) { + + @SerializedName(value = "timr_web") + TIMR_WEB("timr_web"), + + @SerializedName(value = "timr_mobile") + TIMR_MOBILE("timr_mobile"), + + @SerializedName(value = "tour_mobile") + TOUR_MOBILE("tour_mobile"), + + @SerializedName(value = "timr_terminal") + TIMR_TERMINAL("timr_terminal"), + + @SerializedName(value = "sync_api") + SYNC_API("sync_api"), + + @SerializedName(value = "timr_api") + TIMR_API("timr_api"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is Platform) "$data" else null + + /** + * Returns a valid [Platform] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): Platform? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProblemDetail.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProblemDetail.kt new file mode 100644 index 0000000..9a66e86 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProblemDetail.kt @@ -0,0 +1,61 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * RFC 9457 Problem Details base members (`type`, `title`, `status`, `detail`, `instance`) — the common shape of all error response bodies. + * + * @param type + * @param title + * @param status + * @param detail + * @param instance + */ + + +data class ProblemDetail ( + + @SerializedName("type") + val type: java.net.URI, + + @SerializedName("title") + val title: kotlin.String, + + @SerializedName("status") + val status: kotlin.Int, + + @SerializedName("detail") + val detail: kotlin.String? = null, + + @SerializedName("instance") + val instance: kotlin.String? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTime.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTime.kt new file mode 100644 index 0000000..48aae02 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTime.kt @@ -0,0 +1,130 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTime +import com.timr.api.models.Duration +import com.timr.api.models.Location +import com.timr.api.models.Platform +import com.timr.api.models.ProjectTimeStatus +import com.timr.api.models.TaskPartial +import com.timr.api.models.UserPartial + +import com.google.gson.annotations.SerializedName + +/** + * One booking on a `task`, from `start` to `end`, optionally `billable`, with `break_times`, notes and locations. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param start RFC 3339 date-time (ISO-8601) + * @param end RFC 3339 date-time (ISO-8601) + * @param breakTimeTotalMinutes Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + * @param breakTimes + * @param duration + * @param changed + * @param notes + * @param user + * @param task + * @param billable + * @param startLocation + * @param endLocation + * @param startPlatform + * @param endPlatform + * @param lastModified Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @param lastModifiedBy Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @param status + * @param metadata + */ + + +data class ProjectTime ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime?, + + /* Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties */ + @SerializedName("break_time_total_minutes") + val breakTimeTotalMinutes: kotlin.Int, + + @SerializedName("break_times") + val breakTimes: kotlin.collections.List, + + @SerializedName("duration") + val duration: Duration?, + + @SerializedName("changed") + val changed: kotlin.Boolean, + + @SerializedName("notes") + val notes: kotlin.String?, + + @SerializedName("user") + val user: UserPartial, + + @SerializedName("task") + val task: TaskPartial, + + @SerializedName("billable") + val billable: kotlin.Boolean, + + @SerializedName("start_location") + val startLocation: Location?, + + @SerializedName("end_location") + val endLocation: Location?, + + @SerializedName("start_platform") + val startPlatform: Platform?, + + @SerializedName("end_platform") + val endPlatform: Platform?, + + /* Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + @SerializedName("last_modified") + val lastModified: java.time.OffsetDateTime, + + /* Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + @SerializedName("last_modified_by") + val lastModifiedBy: UserPartial?, + + @SerializedName("status") + val status: ProjectTimeStatus, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeCreate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeCreate.kt new file mode 100644 index 0000000..bad27c2 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeCreate.kt @@ -0,0 +1,94 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeUpdate +import com.timr.api.models.LocationCreate +import com.timr.api.models.ProjectTimeStatus + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start RFC 3339 date-time (ISO-8601) + * @param changed + * @param taskId + * @param status + * @param userId + * @param end RFC 3339 date-time (ISO-8601) + * @param breakTimes + * @param notes + * @param billable + * @param metadata + * @param startLocation + * @param endLocation + */ + + +data class ProjectTimeCreate ( + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime, + + @SerializedName("changed") + val changed: kotlin.Boolean, + + @SerializedName("task_id") + val taskId: kotlin.String, + + @SerializedName("status") + val status: ProjectTimeStatus, + + @SerializedName("user_id") + val userId: kotlin.String, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null, + + @SerializedName("break_times") + val breakTimes: kotlin.collections.List? = null, + + @SerializedName("notes") + val notes: kotlin.String? = null, + + @SerializedName("billable") + val billable: kotlin.Boolean? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null, + + @SerializedName("start_location") + val startLocation: LocationCreate? = null, + + @SerializedName("end_location") + val endLocation: LocationCreate? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeStatus.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeStatus.kt new file mode 100644 index 0000000..6efc0b0 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeStatus.kt @@ -0,0 +1,87 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Processing state of a Project Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + * + * Values: RUNNING,PAUSED,CHANGEABLE,LOCKED,APPROVED,CLEARED,CLOSED,ARCHIVED + */ + +enum class ProjectTimeStatus(val value: kotlin.String) { + + @SerializedName(value = "running") + RUNNING("running"), + + @SerializedName(value = "paused") + PAUSED("paused"), + + @SerializedName(value = "changeable") + CHANGEABLE("changeable"), + + @SerializedName(value = "locked") + LOCKED("locked"), + + @SerializedName(value = "approved") + APPROVED("approved"), + + @SerializedName(value = "cleared") + CLEARED("cleared"), + + @SerializedName(value = "closed") + CLOSED("closed"), + + @SerializedName(value = "archived") + ARCHIVED("archived"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is ProjectTimeStatus) "$data" else null + + /** + * Returns a valid [ProjectTimeStatus] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): ProjectTimeStatus? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeUpdate.kt new file mode 100644 index 0000000..0904d56 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeUpdate.kt @@ -0,0 +1,90 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeUpdate +import com.timr.api.models.LocationUpdate +import com.timr.api.models.ProjectTimeStatus + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start RFC 3339 date-time (ISO-8601) + * @param end RFC 3339 date-time (ISO-8601) + * @param breakTimes + * @param changed + * @param notes + * @param taskId + * @param billable + * @param status + * @param metadata + * @param startLocation + * @param endLocation + */ + + +data class ProjectTimeUpdate ( + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime? = null, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null, + + @SerializedName("break_times") + val breakTimes: kotlin.collections.List? = null, + + @SerializedName("changed") + val changed: kotlin.Boolean? = null, + + @SerializedName("notes") + val notes: kotlin.String? = null, + + @SerializedName("task_id") + val taskId: kotlin.String? = null, + + @SerializedName("billable") + val billable: kotlin.Boolean? = null, + + @SerializedName("status") + val status: ProjectTimeStatus? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null, + + @SerializedName("start_location") + val startLocation: LocationUpdate? = null, + + @SerializedName("end_location") + val endLocation: LocationUpdate? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeUpsert.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeUpsert.kt new file mode 100644 index 0000000..fd1ef72 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimeUpsert.kt @@ -0,0 +1,81 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeUpdate +import com.timr.api.models.ProjectTimeStatus + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start RFC 3339 date-time (ISO-8601) + * @param end RFC 3339 date-time (ISO-8601) + * @param breakTimes + * @param changed + * @param notes + * @param taskId + * @param billable + * @param status + * @param metadata + */ + + +data class ProjectTimeUpsert ( + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime? = null, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null, + + @SerializedName("break_times") + val breakTimes: kotlin.collections.List? = null, + + @SerializedName("changed") + val changed: kotlin.Boolean? = null, + + @SerializedName("notes") + val notes: kotlin.String? = null, + + @SerializedName("task_id") + val taskId: kotlin.String? = null, + + @SerializedName("billable") + val billable: kotlin.Boolean? = null, + + @SerializedName("status") + val status: ProjectTimeStatus? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimesPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimesPage.kt new file mode 100644 index 0000000..a8c6f4b --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimesPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.ProjectTime + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class ProjectTimesPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimesSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimesSortColumn.kt new file mode 100644 index 0000000..5d11f1d --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/ProjectTimesSortColumn.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Project Times. + * + * Values: START,LAST_MODIFIED + */ + +enum class ProjectTimesSortColumn(val value: kotlin.String) { + + @SerializedName(value = "start") + START("start"), + + @SerializedName(value = "last_modified") + LAST_MODIFIED("last_modified"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is ProjectTimesSortColumn) "$data" else null + + /** + * Returns a valid [ProjectTimesSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): ProjectTimesSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/RecordingLockType.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/RecordingLockType.kt new file mode 100644 index 0000000..56f158a --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/RecordingLockType.kt @@ -0,0 +1,75 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Whether the assigned User may record on the Task, and where the lock comes from. `recordable` allows recording; `locked_automatically` follows the Task's lock date; `locked_manually` and `unlocked_manually` are explicit overrides for this assignment. + * + * Values: RECORDABLE,LOCKED_AUTOMATICALLY,LOCKED_MANUALLY,UNLOCKED_MANUALLY + */ + +enum class RecordingLockType(val value: kotlin.String) { + + @SerializedName(value = "recordable") + RECORDABLE("recordable"), + + @SerializedName(value = "locked_automatically") + LOCKED_AUTOMATICALLY("locked_automatically"), + + @SerializedName(value = "locked_manually") + LOCKED_MANUALLY("locked_manually"), + + @SerializedName(value = "unlocked_manually") + UNLOCKED_MANUALLY("unlocked_manually"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is RecordingLockType) "$data" else null + + /** + * Returns a valid [RecordingLockType] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): RecordingLockType? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/RecordingModeUser.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/RecordingModeUser.kt new file mode 100644 index 0000000..7a2612d --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/RecordingModeUser.kt @@ -0,0 +1,72 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Whether a User may record this Working Time Type themselves. Only meaningful for day-based types. + * + * Values: NOT_ALLOWED,ALLOWED,BY_REQUEST + */ + +enum class RecordingModeUser(val value: kotlin.String) { + + @SerializedName(value = "not_allowed") + NOT_ALLOWED("not_allowed"), + + @SerializedName(value = "allowed") + ALLOWED("allowed"), + + @SerializedName(value = "by_request") + BY_REQUEST("by_request"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is RecordingModeUser) "$data" else null + + /** + * Returns a valid [RecordingModeUser] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): RecordingModeUser? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/SortDirection.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/SortDirection.kt new file mode 100644 index 0000000..791bca3 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/SortDirection.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort direction — `asc` for ascending, `dsc` for descending. + * + * Values: ASC,DSC + */ + +enum class SortDirection(val value: kotlin.String) { + + @SerializedName(value = "asc") + ASC("asc"), + + @SerializedName(value = "dsc") + DSC("dsc"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is SortDirection) "$data" else null + + /** + * Returns a valid [SortDirection] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): SortDirection? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Task.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Task.kt new file mode 100644 index 0000000..3d578bb --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Task.kt @@ -0,0 +1,174 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BudgetPlanningType +import com.timr.api.models.TaskLocation +import com.timr.api.models.TaskPartial + +import com.google.gson.annotations.SerializedName + +/** + * A task, placed in the tree by `parent_task`, with the full path from the root in `breadcrumbs`. `bookable` and `billable` control recording and invoicing; `lock_date`, time windows and location constrain what may be recorded. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param breadcrumbs Full path of the entry within its hierarchy, including its own name. + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param parentTask + * @param description + * @param descriptionExternal + * @param bookable + * @param billable + * @param projectTimeNotesRequired + * @param startDate RFC 3339 date (ISO-8601) + * @param endDate RFC 3339 date (ISO-8601) + * @param activeFrom RFC 3339 date (ISO-8601) + * @param activeTo RFC 3339 date (ISO-8601) + * @param customField1 + * @param customField2 + * @param customField3 + * @param lockDate RFC 3339 date (ISO-8601) + * @param earliestStartTime time of day (ISO-8601) + * @param latestEndTime time of day (ISO-8601) + * @param budgetInherited + * @param budgetPlanningType + * @param budgetHoursPlanned + * @param budgetHourlyRate + * @param budgetPlanned + * @param budgetIncludeNonBillableProjectTimes + * @param locationInherited + * @param location + * @param locationRestrictionRadiusMeters + * @param metadata + */ + + +data class Task ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + /* Full path of the entry within its hierarchy, including its own name. */ + @SerializedName("breadcrumbs") + val breadcrumbs: kotlin.String, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String?, + + @SerializedName("parent_task") + val parentTask: TaskPartial?, + + @SerializedName("description") + val description: kotlin.String?, + + @SerializedName("description_external") + val descriptionExternal: kotlin.String?, + + @SerializedName("bookable") + val bookable: kotlin.Boolean, + + @SerializedName("billable") + val billable: kotlin.Boolean, + + @SerializedName("project_time_notes_required") + val projectTimeNotesRequired: kotlin.Boolean, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("start_date") + val startDate: java.time.LocalDate?, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("end_date") + val endDate: java.time.LocalDate?, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("active_from") + val activeFrom: java.time.LocalDate?, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("active_to") + val activeTo: java.time.LocalDate?, + + @SerializedName("custom_field_1") + val customField1: kotlin.String?, + + @SerializedName("custom_field_2") + val customField2: kotlin.String?, + + @SerializedName("custom_field_3") + val customField3: kotlin.String?, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("lock_date") + val lockDate: java.time.LocalDate? = null, + + /* time of day (ISO-8601) */ + @SerializedName("earliest_start_time") + val earliestStartTime: kotlin.String? = null, + + /* time of day (ISO-8601) */ + @SerializedName("latest_end_time") + val latestEndTime: kotlin.String? = null, + + @SerializedName("budget_inherited") + val budgetInherited: kotlin.Boolean? = null, + + @SerializedName("budget_planning_type") + val budgetPlanningType: BudgetPlanningType? = null, + + @SerializedName("budget_hours_planned") + val budgetHoursPlanned: java.math.BigDecimal? = null, + + @SerializedName("budget_hourly_rate") + val budgetHourlyRate: java.math.BigDecimal? = null, + + @SerializedName("budget_planned") + val budgetPlanned: java.math.BigDecimal? = null, + + @SerializedName("budget_include_non_billable_project_times") + val budgetIncludeNonBillableProjectTimes: kotlin.Boolean? = null, + + @SerializedName("location_inherited") + val locationInherited: kotlin.Boolean? = null, + + @SerializedName("location") + val location: TaskLocation? = null, + + @SerializedName("location_restriction_radius_meters") + val locationRestrictionRadiusMeters: kotlin.Int? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskBase.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskBase.kt new file mode 100644 index 0000000..dc80163 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskBase.kt @@ -0,0 +1,162 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BudgetPlanningTypeRequest +import com.timr.api.models.TaskLocation + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param name + * @param parentTaskId returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param description + * @param descriptionExternal + * @param bookable when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @param billable + * @param projectTimeNotesRequired depending on this property project times booked on this task have to include notes or not + * @param startDate the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @param endDate the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @param lockDate with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + * @param earliestStartTime set this property to limit the task so that it cannot be booked before this time + * @param latestEndTime set this property to limit the task so that it cannot be booked after this time + * @param budgetPlanningType when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * @param budgetHoursPlanned how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @param budgetHourlyRate depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * @param budgetPlanned the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @param budgetIncludeNonBillableProjectTimes set this property to true, if you want to include not billable hours for all project times booked on this task + * @param locationInherited set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @param location + * @param locationRestrictionRadiusMeters set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @param customField1 you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @param customField2 you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @param customField3 you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @param metadata + */ + + +data class TaskBase ( + + @SerializedName("name") + val name: kotlin.String? = null, + + /* returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. */ + @SerializedName("parent_task_id") + val parentTaskId: kotlin.String? = null, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? = null, + + @SerializedName("description") + val description: kotlin.String? = null, + + @SerializedName("description_external") + val descriptionExternal: kotlin.String? = null, + + /* when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. */ + @SerializedName("bookable") + val bookable: kotlin.Boolean? = null, + + @SerializedName("billable") + val billable: kotlin.Boolean? = null, + + /* depending on this property project times booked on this task have to include notes or not */ + @SerializedName("project_time_notes_required") + val projectTimeNotesRequired: kotlin.Boolean? = null, + + /* the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + @SerializedName("start_date") + val startDate: java.time.LocalDate? = null, + + /* the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + @SerializedName("end_date") + val endDate: java.time.LocalDate? = null, + + /* with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later */ + @SerializedName("lock_date") + val lockDate: java.time.LocalDate? = null, + + /* set this property to limit the task so that it cannot be booked before this time */ + @SerializedName("earliest_start_time") + val earliestStartTime: kotlin.String? = null, + + /* set this property to limit the task so that it cannot be booked after this time */ + @SerializedName("latest_end_time") + val latestEndTime: kotlin.String? = null, + + /* when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. */ + @SerializedName("budget_planning_type") + val budgetPlanningType: BudgetPlanningTypeRequest? = null, + + /* how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + @SerializedName("budget_hours_planned") + val budgetHoursPlanned: java.math.BigDecimal? = null, + + /* depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value */ + @SerializedName("budget_hourly_rate") + val budgetHourlyRate: java.math.BigDecimal? = null, + + /* the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + @SerializedName("budget_planned") + val budgetPlanned: java.math.BigDecimal? = null, + + /* set this property to true, if you want to include not billable hours for all project times booked on this task */ + @SerializedName("budget_include_non_billable_project_times") + val budgetIncludeNonBillableProjectTimes: kotlin.Boolean? = null, + + /* set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent */ + @SerializedName("location_inherited") + val locationInherited: kotlin.Boolean? = null, + + @SerializedName("location") + val location: TaskLocation? = null, + + /* set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius */ + @SerializedName("location_restriction_radius_meters") + val locationRestrictionRadiusMeters: kotlin.Int? = null, + + /* you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + @SerializedName("custom_field_1") + val customField1: kotlin.String? = null, + + /* you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + @SerializedName("custom_field_2") + val customField2: kotlin.String? = null, + + /* you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + @SerializedName("custom_field_3") + val customField3: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskCreate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskCreate.kt new file mode 100644 index 0000000..042480c --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskCreate.kt @@ -0,0 +1,162 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BudgetPlanningTypeRequest +import com.timr.api.models.TaskLocation + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param name + * @param bookable when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @param billable + * @param parentTaskId returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param description + * @param descriptionExternal + * @param projectTimeNotesRequired depending on this property project times booked on this task have to include notes or not + * @param startDate the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @param endDate the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @param lockDate with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + * @param earliestStartTime set this property to limit the task so that it cannot be booked before this time + * @param latestEndTime set this property to limit the task so that it cannot be booked after this time + * @param budgetPlanningType when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * @param budgetHoursPlanned how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @param budgetHourlyRate depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * @param budgetPlanned the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @param budgetIncludeNonBillableProjectTimes set this property to true, if you want to include not billable hours for all project times booked on this task + * @param locationInherited set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @param location + * @param locationRestrictionRadiusMeters set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @param customField1 you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @param customField2 you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @param customField3 you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @param metadata + */ + + +data class TaskCreate ( + + @SerializedName("name") + val name: kotlin.String, + + /* when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. */ + @SerializedName("bookable") + val bookable: kotlin.Boolean, + + @SerializedName("billable") + val billable: kotlin.Boolean, + + /* returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. */ + @SerializedName("parent_task_id") + val parentTaskId: kotlin.String? = null, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? = null, + + @SerializedName("description") + val description: kotlin.String? = null, + + @SerializedName("description_external") + val descriptionExternal: kotlin.String? = null, + + /* depending on this property project times booked on this task have to include notes or not */ + @SerializedName("project_time_notes_required") + val projectTimeNotesRequired: kotlin.Boolean? = null, + + /* the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + @SerializedName("start_date") + val startDate: java.time.LocalDate? = null, + + /* the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + @SerializedName("end_date") + val endDate: java.time.LocalDate? = null, + + /* with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later */ + @SerializedName("lock_date") + val lockDate: java.time.LocalDate? = null, + + /* set this property to limit the task so that it cannot be booked before this time */ + @SerializedName("earliest_start_time") + val earliestStartTime: kotlin.String? = null, + + /* set this property to limit the task so that it cannot be booked after this time */ + @SerializedName("latest_end_time") + val latestEndTime: kotlin.String? = null, + + /* when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. */ + @SerializedName("budget_planning_type") + val budgetPlanningType: BudgetPlanningTypeRequest? = null, + + /* how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + @SerializedName("budget_hours_planned") + val budgetHoursPlanned: java.math.BigDecimal? = null, + + /* depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value */ + @SerializedName("budget_hourly_rate") + val budgetHourlyRate: java.math.BigDecimal? = null, + + /* the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + @SerializedName("budget_planned") + val budgetPlanned: java.math.BigDecimal? = null, + + /* set this property to true, if you want to include not billable hours for all project times booked on this task */ + @SerializedName("budget_include_non_billable_project_times") + val budgetIncludeNonBillableProjectTimes: kotlin.Boolean? = null, + + /* set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent */ + @SerializedName("location_inherited") + val locationInherited: kotlin.Boolean? = null, + + @SerializedName("location") + val location: TaskLocation? = null, + + /* set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius */ + @SerializedName("location_restriction_radius_meters") + val locationRestrictionRadiusMeters: kotlin.Int? = null, + + /* you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + @SerializedName("custom_field_1") + val customField1: kotlin.String? = null, + + /* you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + @SerializedName("custom_field_2") + val customField2: kotlin.String? = null, + + /* you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + @SerializedName("custom_field_3") + val customField3: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskLocation.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskLocation.kt new file mode 100644 index 0000000..d1d8fc0 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskLocation.kt @@ -0,0 +1,72 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * You can define the location of a task by setting this property. If the task has a parent task, the location is inherited if nothing else is explicitly defined. If you set this property to null, the location will be deleted. + * + * @param lat Latitude in decimal degrees. + * @param lon Longitude in decimal degrees. + * @param address + * @param city + * @param zipCode + * @param state + * @param country the country's international country code + */ + + +data class TaskLocation ( + + /* Latitude in decimal degrees. */ + @SerializedName("lat") + val lat: kotlin.Float?, + + /* Longitude in decimal degrees. */ + @SerializedName("lon") + val lon: kotlin.Float?, + + @SerializedName("address") + val address: kotlin.String?, + + @SerializedName("city") + val city: kotlin.String?, + + @SerializedName("zip_code") + val zipCode: kotlin.String?, + + @SerializedName("state") + val state: kotlin.String?, + + /* the country's international country code */ + @SerializedName("country") + val country: kotlin.String? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskPartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskPartial.kt new file mode 100644 index 0000000..36d09a2 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskPartial.kt @@ -0,0 +1,60 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param breadcrumbs Full path of the entry within its hierarchy, including its own name. + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + */ + + +data class TaskPartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + /* Full path of the entry within its hierarchy, including its own name. */ + @SerializedName("breadcrumbs") + val breadcrumbs: kotlin.String, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskReduced.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskReduced.kt new file mode 100644 index 0000000..f6d92d4 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskReduced.kt @@ -0,0 +1,136 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BudgetPlanningType +import com.timr.api.models.TaskLocation +import com.timr.api.models.TaskPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param breadcrumbs Full path of the entry within its hierarchy, including its own name. + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param parentTask + * @param description + * @param bookable + * @param billable + * @param projectTimeNotesRequired + * @param activeFrom RFC 3339 date (ISO-8601) + * @param activeTo RFC 3339 date (ISO-8601) + * @param customField1 + * @param customField2 + * @param customField3 + * @param lockDate RFC 3339 date (ISO-8601) + * @param earliestStartTime time of day (ISO-8601) + * @param latestEndTime time of day (ISO-8601) + * @param budgetPlanningType + * @param locationInherited + * @param location + * @param locationRestrictionRadiusMeters + */ + + +data class TaskReduced ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + /* Full path of the entry within its hierarchy, including its own name. */ + @SerializedName("breadcrumbs") + val breadcrumbs: kotlin.String, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String?, + + @SerializedName("parent_task") + val parentTask: TaskPartial?, + + @SerializedName("description") + val description: kotlin.String?, + + @SerializedName("bookable") + val bookable: kotlin.Boolean, + + @SerializedName("billable") + val billable: kotlin.Boolean, + + @SerializedName("project_time_notes_required") + val projectTimeNotesRequired: kotlin.Boolean, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("active_from") + val activeFrom: java.time.LocalDate?, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("active_to") + val activeTo: java.time.LocalDate?, + + @SerializedName("custom_field_1") + val customField1: kotlin.String?, + + @SerializedName("custom_field_2") + val customField2: kotlin.String?, + + @SerializedName("custom_field_3") + val customField3: kotlin.String?, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("lock_date") + val lockDate: java.time.LocalDate? = null, + + /* time of day (ISO-8601) */ + @SerializedName("earliest_start_time") + val earliestStartTime: kotlin.String? = null, + + /* time of day (ISO-8601) */ + @SerializedName("latest_end_time") + val latestEndTime: kotlin.String? = null, + + @SerializedName("budget_planning_type") + val budgetPlanningType: BudgetPlanningType? = null, + + @SerializedName("location_inherited") + val locationInherited: kotlin.Boolean? = null, + + @SerializedName("location") + val location: TaskLocation? = null, + + @SerializedName("location_restriction_radius_meters") + val locationRestrictionRadiusMeters: kotlin.Int? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToLeaderAssignment.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToLeaderAssignment.kt new file mode 100644 index 0000000..8555b3a --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToLeaderAssignment.kt @@ -0,0 +1,50 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.UserPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param user + * @param automaticallyAssigned + */ + + +data class TaskToLeaderAssignment ( + + @SerializedName("user") + val user: UserPartial, + + @SerializedName("automatically_assigned") + val automaticallyAssigned: kotlin.Boolean + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToLeaderAssignmentsPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToLeaderAssignmentsPage.kt new file mode 100644 index 0000000..3a4fc09 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToLeaderAssignmentsPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.TaskToLeaderAssignment + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class TaskToLeaderAssignmentsPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToLeaderAssignmentsSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToLeaderAssignmentsSortColumn.kt new file mode 100644 index 0000000..834fdf2 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToLeaderAssignmentsSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Task to Leader Assignments. `user_name` orders by the assigned User's last name, then first name. + * + * Values: USER_NAME + */ + +enum class TaskToLeaderAssignmentsSortColumn(val value: kotlin.String) { + + @SerializedName(value = "user_name") + USER_NAME("user_name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is TaskToLeaderAssignmentsSortColumn) "$data" else null + + /** + * Returns a valid [TaskToLeaderAssignmentsSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): TaskToLeaderAssignmentsSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToTeamAssignment.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToTeamAssignment.kt new file mode 100644 index 0000000..f223af5 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToTeamAssignment.kt @@ -0,0 +1,50 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.TeamPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param team + * @param automaticallyAssigned + */ + + +data class TaskToTeamAssignment ( + + @SerializedName("team") + val team: TeamPartial, + + @SerializedName("automatically_assigned") + val automaticallyAssigned: kotlin.Boolean + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToTeamAssignmentsPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToTeamAssignmentsPage.kt new file mode 100644 index 0000000..7010229 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToTeamAssignmentsPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.TaskToTeamAssignment + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class TaskToTeamAssignmentsPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToTeamAssignmentsSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToTeamAssignmentsSortColumn.kt new file mode 100644 index 0000000..dd868fd --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToTeamAssignmentsSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Task to Team Assignments. `team_name` orders by the assigned Team's name. + * + * Values: TEAM_NAME + */ + +enum class TaskToTeamAssignmentsSortColumn(val value: kotlin.String) { + + @SerializedName(value = "team_name") + TEAM_NAME("team_name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is TaskToTeamAssignmentsSortColumn) "$data" else null + + /** + * Returns a valid [TaskToTeamAssignmentsSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): TaskToTeamAssignmentsSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignment.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignment.kt new file mode 100644 index 0000000..4a8c7f2 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignment.kt @@ -0,0 +1,59 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.RecordingLockType +import com.timr.api.models.UserPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param user + * @param recordingLock + * @param automaticallyAssigned + * @param hoursPlanned + */ + + +data class TaskToUserAssignment ( + + @SerializedName("user") + val user: UserPartial, + + @SerializedName("recording_lock") + val recordingLock: RecordingLockType, + + @SerializedName("automatically_assigned") + val automaticallyAssigned: kotlin.Boolean, + + @SerializedName("hours_planned") + val hoursPlanned: java.math.BigDecimal? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignmentUpsert.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignmentUpsert.kt new file mode 100644 index 0000000..0516bed --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignmentUpsert.kt @@ -0,0 +1,50 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.RecordingLockType + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param hoursPlanned + * @param recordingLock + */ + + +data class TaskToUserAssignmentUpsert ( + + @SerializedName("hours_planned") + val hoursPlanned: java.math.BigDecimal? = null, + + @SerializedName("recording_lock") + val recordingLock: RecordingLockType? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignmentsPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignmentsPage.kt new file mode 100644 index 0000000..be17f28 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignmentsPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.TaskToUserAssignment + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class TaskToUserAssignmentsPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignmentsSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignmentsSortColumn.kt new file mode 100644 index 0000000..da0b19b --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskToUserAssignmentsSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Task to User Assignments. `user_name` orders by the assigned User's last name, then first name. + * + * Values: USER_NAME + */ + +enum class TaskToUserAssignmentsSortColumn(val value: kotlin.String) { + + @SerializedName(value = "user_name") + USER_NAME("user_name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is TaskToUserAssignmentsSortColumn) "$data" else null + + /** + * Returns a valid [TaskToUserAssignmentsSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): TaskToUserAssignmentsSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskUpdate.kt new file mode 100644 index 0000000..2c4e4ba --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TaskUpdate.kt @@ -0,0 +1,167 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BudgetPlanningTypeRequest +import com.timr.api.models.TaskLocation + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param name + * @param parentTaskId returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param description + * @param descriptionExternal + * @param bookable when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @param billable + * @param projectTimeNotesRequired depending on this property project times booked on this task have to include notes or not + * @param startDate the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @param endDate the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @param lockDate with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later + * @param earliestStartTime set this property to limit the task so that it cannot be booked before this time + * @param latestEndTime set this property to limit the task so that it cannot be booked after this time + * @param budgetPlanningType when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * @param budgetHoursPlanned how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @param budgetHourlyRate depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * @param budgetPlanned the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned + * @param budgetIncludeNonBillableProjectTimes set this property to true, if you want to include not billable hours for all project times booked on this task + * @param locationInherited set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @param location + * @param locationRestrictionRadiusMeters set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @param customField1 you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @param customField2 you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @param customField3 you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @param metadata + * @param budgetUpdateProjectTimes this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. + */ + + +data class TaskUpdate ( + + @SerializedName("name") + val name: kotlin.String? = null, + + /* returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. */ + @SerializedName("parent_task_id") + val parentTaskId: kotlin.String? = null, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? = null, + + @SerializedName("description") + val description: kotlin.String? = null, + + @SerializedName("description_external") + val descriptionExternal: kotlin.String? = null, + + /* when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. */ + @SerializedName("bookable") + val bookable: kotlin.Boolean? = null, + + @SerializedName("billable") + val billable: kotlin.Boolean? = null, + + /* depending on this property project times booked on this task have to include notes or not */ + @SerializedName("project_time_notes_required") + val projectTimeNotesRequired: kotlin.Boolean? = null, + + /* the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + @SerializedName("start_date") + val startDate: java.time.LocalDate? = null, + + /* the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + @SerializedName("end_date") + val endDate: java.time.LocalDate? = null, + + /* with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later */ + @SerializedName("lock_date") + val lockDate: java.time.LocalDate? = null, + + /* set this property to limit the task so that it cannot be booked before this time */ + @SerializedName("earliest_start_time") + val earliestStartTime: kotlin.String? = null, + + /* set this property to limit the task so that it cannot be booked after this time */ + @SerializedName("latest_end_time") + val latestEndTime: kotlin.String? = null, + + /* when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. */ + @SerializedName("budget_planning_type") + val budgetPlanningType: BudgetPlanningTypeRequest? = null, + + /* how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + @SerializedName("budget_hours_planned") + val budgetHoursPlanned: java.math.BigDecimal? = null, + + /* depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value */ + @SerializedName("budget_hourly_rate") + val budgetHourlyRate: java.math.BigDecimal? = null, + + /* the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + @SerializedName("budget_planned") + val budgetPlanned: java.math.BigDecimal? = null, + + /* set this property to true, if you want to include not billable hours for all project times booked on this task */ + @SerializedName("budget_include_non_billable_project_times") + val budgetIncludeNonBillableProjectTimes: kotlin.Boolean? = null, + + /* set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent */ + @SerializedName("location_inherited") + val locationInherited: kotlin.Boolean? = null, + + @SerializedName("location") + val location: TaskLocation? = null, + + /* set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius */ + @SerializedName("location_restriction_radius_meters") + val locationRestrictionRadiusMeters: kotlin.Int? = null, + + /* you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + @SerializedName("custom_field_1") + val customField1: kotlin.String? = null, + + /* you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + @SerializedName("custom_field_2") + val customField2: kotlin.String? = null, + + /* you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + @SerializedName("custom_field_3") + val customField3: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null, + + /* this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. */ + @SerializedName("budget_update_project_times") + val budgetUpdateProjectTimes: kotlin.Boolean? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TasksPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TasksPage.kt new file mode 100644 index 0000000..e20d7b1 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TasksPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.Task + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class TasksPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TasksReducedPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TasksReducedPage.kt new file mode 100644 index 0000000..a241bb8 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TasksReducedPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.TaskReduced + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class TasksReducedPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TasksSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TasksSortColumn.kt new file mode 100644 index 0000000..a7506c2 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TasksSortColumn.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Tasks. `breadcrumbs` orders by the Task's full path, `name` by its own name only. + * + * Values: BREADCRUMBS,NAME + */ + +enum class TasksSortColumn(val value: kotlin.String) { + + @SerializedName(value = "breadcrumbs") + BREADCRUMBS("breadcrumbs"), + + @SerializedName(value = "name") + NAME("name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is TasksSortColumn) "$data" else null + + /** + * Returns a valid [TasksSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): TasksSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Team.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Team.kt new file mode 100644 index 0000000..90480a8 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Team.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.TeamPartial + +import com.google.gson.annotations.SerializedName + +/** + * A team, placed in the hierarchy by `parent_team`, with the full path from the root in `breadcrumbs`. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param breadcrumbs Full path of the entry within its hierarchy, including its own name. + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param description + * @param parentTeam + */ + + +data class Team ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + /* Full path of the entry within its hierarchy, including its own name. */ + @SerializedName("breadcrumbs") + val breadcrumbs: kotlin.String, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String?, + + @SerializedName("description") + val description: kotlin.String?, + + @SerializedName("parent_team") + val parentTeam: TeamPartial? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamCreate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamCreate.kt new file mode 100644 index 0000000..89b7a06 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamCreate.kt @@ -0,0 +1,58 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param name + * @param description + * @param parentTeamId + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + */ + + +data class TeamCreate ( + + @SerializedName("name") + val name: kotlin.String, + + @SerializedName("description") + val description: kotlin.String? = null, + + @SerializedName("parent_team_id") + val parentTeamId: kotlin.String? = null, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamPartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamPartial.kt new file mode 100644 index 0000000..bcfbd68 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamPartial.kt @@ -0,0 +1,60 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param breadcrumbs Full path of the entry within its hierarchy, including its own name. + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + */ + + +data class TeamPartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + /* Full path of the entry within its hierarchy, including its own name. */ + @SerializedName("breadcrumbs") + val breadcrumbs: kotlin.String, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamUpdate.kt new file mode 100644 index 0000000..e16afe5 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamUpdate.kt @@ -0,0 +1,58 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param name + * @param description + * @param parentTeamId + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + */ + + +data class TeamUpdate ( + + @SerializedName("name") + val name: kotlin.String? = null, + + @SerializedName("description") + val description: kotlin.String? = null, + + @SerializedName("parent_team_id") + val parentTeamId: kotlin.String? = null, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamsPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamsPage.kt new file mode 100644 index 0000000..c343a07 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamsPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.Team + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class TeamsPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamsPartialPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamsPartialPage.kt new file mode 100644 index 0000000..c846cfc --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamsPartialPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.TeamPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class TeamsPartialPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamsSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamsSortColumn.kt new file mode 100644 index 0000000..a609bff --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TeamsSortColumn.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Teams. `breadcrumbs` orders by the Team's full path, `name` by its own name only. + * + * Values: BREADCRUMBS,NAME + */ + +enum class TeamsSortColumn(val value: kotlin.String) { + + @SerializedName(value = "breadcrumbs") + BREADCRUMBS("breadcrumbs"), + + @SerializedName(value = "name") + NAME("name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is TeamsSortColumn) "$data" else null + + /** + * Returns a valid [TeamsSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): TeamsSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TimeAccount.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TimeAccount.kt new file mode 100644 index 0000000..5f3561e --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/TimeAccount.kt @@ -0,0 +1,80 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.FlexTimeIndicator + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param balanceLastPeriodMinutes + * @param durationActualMinutes sum of durations in current period + * @param durationTargetMinutes target duration in current period + * @param balanceCurrentPeriodMinutes difference between target duration and actual duration + * @param balanceTotalMinutes total duration until balancing date + * @param workFromHomeDaysFull complete days worked from home in current period + * @param workFromHomeDaysPartial partial days worked from home in current period + * @param flexTimeIndicator + */ + + +data class TimeAccount ( + + @SerializedName("balance_last_period_minutes") + val balanceLastPeriodMinutes: kotlin.Int?, + + /* sum of durations in current period */ + @SerializedName("duration_actual_minutes") + val durationActualMinutes: kotlin.Int?, + + /* target duration in current period */ + @SerializedName("duration_target_minutes") + val durationTargetMinutes: kotlin.Int?, + + /* difference between target duration and actual duration */ + @SerializedName("balance_current_period_minutes") + val balanceCurrentPeriodMinutes: kotlin.Int?, + + /* total duration until balancing date */ + @SerializedName("balance_total_minutes") + val balanceTotalMinutes: kotlin.Int?, + + /* complete days worked from home in current period */ + @SerializedName("work_from_home_days_full") + val workFromHomeDaysFull: kotlin.Int?, + + /* partial days worked from home in current period */ + @SerializedName("work_from_home_days_partial") + val workFromHomeDaysPartial: kotlin.Int?, + + @SerializedName("flex_time_indicator") + val flexTimeIndicator: FlexTimeIndicator? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/User.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/User.kt new file mode 100644 index 0000000..c34018c --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/User.kt @@ -0,0 +1,105 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.HolidayCalendarPartial +import com.timr.api.models.WorkScheduleModelPartial + +import com.google.gson.annotations.SerializedName + +/** + * A user's identity (`firstname`, `lastname`, `email`), employment dates (`entry_date`, `resign_date`), and the assigned `work_schedule_model` and `holiday_calendar`. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param firstname + * @param lastname + * @param fullname + * @param email Email address must be either valid or null. + * @param employeeNumber + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param login + * @param entryDate RFC 3339 date (ISO-8601) + * @param resignDate RFC 3339 date (ISO-8601) + * @param workScheduleModel + * @param holidayCalendar + * @param vacationYearStart recurring month and day on which the user's vacation year starts + * @param metadata + */ + + +data class User ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("firstname") + val firstname: kotlin.String?, + + @SerializedName("lastname") + val lastname: kotlin.String?, + + @SerializedName("fullname") + val fullname: kotlin.String?, + + /* Email address must be either valid or null. */ + @SerializedName("email") + val email: kotlin.String?, + + @SerializedName("employee_number") + val employeeNumber: kotlin.String?, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String?, + + @SerializedName("login") + val login: kotlin.String? = null, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("entry_date") + val entryDate: java.time.LocalDate? = null, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("resign_date") + val resignDate: java.time.LocalDate? = null, + + @SerializedName("work_schedule_model") + val workScheduleModel: WorkScheduleModelPartial? = null, + + @SerializedName("holiday_calendar") + val holidayCalendar: HolidayCalendarPartial? = null, + + /* recurring month and day on which the user's vacation year starts */ + @SerializedName("vacation_year_start") + val vacationYearStart: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UserCreate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UserCreate.kt new file mode 100644 index 0000000..9c05268 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UserCreate.kt @@ -0,0 +1,87 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param login + * @param firstname + * @param lastname + * @param email + * @param entryDate RFC 3339 date (ISO-8601) + * @param resignDate RFC 3339 date (ISO-8601) + * @param employeeNumber + * @param externalId + * @param metadata + * @param authProvider + * @param authIdentifier + */ + + +data class UserCreate ( + + @SerializedName("login") + val login: kotlin.String, + + @SerializedName("firstname") + val firstname: kotlin.String? = null, + + @SerializedName("lastname") + val lastname: kotlin.String? = null, + + @SerializedName("email") + val email: kotlin.String? = null, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("entry_date") + val entryDate: java.time.LocalDate? = null, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("resign_date") + val resignDate: java.time.LocalDate? = null, + + @SerializedName("employee_number") + val employeeNumber: kotlin.String? = null, + + @SerializedName("external_id") + val externalId: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null, + + @SerializedName("auth_provider") + val authProvider: kotlin.String? = null, + + @SerializedName("auth_identifier") + val authIdentifier: kotlin.String? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UserPartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UserPartial.kt new file mode 100644 index 0000000..a402348 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UserPartial.kt @@ -0,0 +1,72 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param firstname + * @param lastname + * @param fullname + * @param email Email address must be either valid or null. + * @param employeeNumber + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + */ + + +data class UserPartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("firstname") + val firstname: kotlin.String?, + + @SerializedName("lastname") + val lastname: kotlin.String?, + + @SerializedName("fullname") + val fullname: kotlin.String?, + + /* Email address must be either valid or null. */ + @SerializedName("email") + val email: kotlin.String?, + + @SerializedName("employee_number") + val employeeNumber: kotlin.String?, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UserUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UserUpdate.kt new file mode 100644 index 0000000..29c8b9e --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UserUpdate.kt @@ -0,0 +1,79 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param login + * @param firstname + * @param lastname + * @param email + * @param entryDate RFC 3339 date (ISO-8601) + * @param resignDate RFC 3339 date (ISO-8601) + * @param employeeNumber + * @param externalId + * @param metadata + */ + + +data class UserUpdate ( + + @SerializedName("login") + val login: kotlin.String? = null, + + @SerializedName("firstname") + val firstname: kotlin.String? = null, + + @SerializedName("lastname") + val lastname: kotlin.String? = null, + + @SerializedName("email") + val email: kotlin.String? = null, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("entry_date") + val entryDate: java.time.LocalDate? = null, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("resign_date") + val resignDate: java.time.LocalDate? = null, + + @SerializedName("employee_number") + val employeeNumber: kotlin.String? = null, + + @SerializedName("external_id") + val externalId: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UsersPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UsersPage.kt new file mode 100644 index 0000000..424af30 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UsersPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.User + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class UsersPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UsersPartialPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UsersPartialPage.kt new file mode 100644 index 0000000..0a050b8 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UsersPartialPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.UserPartial + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class UsersPartialPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UsersSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UsersSortColumn.kt new file mode 100644 index 0000000..3b5ad88 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/UsersSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Users. `name` orders by last name, then first name. + * + * Values: NAME + */ + +enum class UsersSortColumn(val value: kotlin.String) { + + @SerializedName(value = "name") + NAME("name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is UsersSortColumn) "$data" else null + + /** + * Returns a valid [UsersSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): UsersSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccount.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccount.kt new file mode 100644 index 0000000..6cce613 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccount.kt @@ -0,0 +1,77 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.VacationAccountDays +import com.timr.api.models.VacationAccountMinutes +import com.timr.api.models.VacationUnit + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param unit + * @param balanceLastPeriodDays vacation balance carried over from the previous vacation period, in days + * @param consumedDays vacation consumed in the current vacation period, in days + * @param newDays vacation newly granted in the current vacation period, in days + * @param balanceTotalDays total vacation balance for the current vacation period, in days + * @param balanceLastPeriodMinutes vacation balance carried over from the previous vacation period, in minutes + * @param consumedMinutes vacation consumed in the current vacation period, in minutes + * @param newMinutes vacation newly granted in the current vacation period, in minutes + * @param balanceTotalMinutes total vacation balance for the current vacation period, in minutes + */ + + +interface VacationAccount { + + @get:SerializedName("unit") + val unit: VacationUnit + /* vacation balance carried over from the previous vacation period, in days */ + @get:SerializedName("balance_last_period_days") + val balanceLastPeriodDays: java.math.BigDecimal? + /* vacation consumed in the current vacation period, in days */ + @get:SerializedName("consumed_days") + val consumedDays: java.math.BigDecimal? + /* vacation newly granted in the current vacation period, in days */ + @get:SerializedName("new_days") + val newDays: java.math.BigDecimal? + /* total vacation balance for the current vacation period, in days */ + @get:SerializedName("balance_total_days") + val balanceTotalDays: java.math.BigDecimal? + /* vacation balance carried over from the previous vacation period, in minutes */ + @get:SerializedName("balance_last_period_minutes") + val balanceLastPeriodMinutes: java.math.BigDecimal? + /* vacation consumed in the current vacation period, in minutes */ + @get:SerializedName("consumed_minutes") + val consumedMinutes: java.math.BigDecimal? + /* vacation newly granted in the current vacation period, in minutes */ + @get:SerializedName("new_minutes") + val newMinutes: java.math.BigDecimal? + /* total vacation balance for the current vacation period, in minutes */ + @get:SerializedName("balance_total_minutes") + val balanceTotalMinutes: java.math.BigDecimal? + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccountBase.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccountBase.kt new file mode 100644 index 0000000..5e5b462 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccountBase.kt @@ -0,0 +1,46 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.VacationUnit + +import com.google.gson.annotations.SerializedName + +/** + * Members shared by every kind of vacation account, including the discriminator. + * + * @param unit + */ + + +data class VacationAccountBase ( + + @SerializedName("unit") + val unit: VacationUnit + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccountDays.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccountDays.kt new file mode 100644 index 0000000..ad5804a --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccountDays.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.VacationUnit + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param unit + * @param balanceLastPeriodDays vacation balance carried over from the previous vacation period, in days + * @param consumedDays vacation consumed in the current vacation period, in days + * @param newDays vacation newly granted in the current vacation period, in days + * @param balanceTotalDays total vacation balance for the current vacation period, in days + */ + + +data class VacationAccountDays ( + + @SerializedName("unit") + val unit: VacationUnit, + + /* vacation balance carried over from the previous vacation period, in days */ + @SerializedName("balance_last_period_days") + val balanceLastPeriodDays: java.math.BigDecimal? = null, + + /* vacation consumed in the current vacation period, in days */ + @SerializedName("consumed_days") + val consumedDays: java.math.BigDecimal? = null, + + /* vacation newly granted in the current vacation period, in days */ + @SerializedName("new_days") + val newDays: java.math.BigDecimal? = null, + + /* total vacation balance for the current vacation period, in days */ + @SerializedName("balance_total_days") + val balanceTotalDays: java.math.BigDecimal? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccountMinutes.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccountMinutes.kt new file mode 100644 index 0000000..c9b48c9 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationAccountMinutes.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.VacationUnit + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param unit + * @param balanceLastPeriodMinutes vacation balance carried over from the previous vacation period, in minutes + * @param consumedMinutes vacation consumed in the current vacation period, in minutes + * @param newMinutes vacation newly granted in the current vacation period, in minutes + * @param balanceTotalMinutes total vacation balance for the current vacation period, in minutes + */ + + +data class VacationAccountMinutes ( + + @SerializedName("unit") + val unit: VacationUnit, + + /* vacation balance carried over from the previous vacation period, in minutes */ + @SerializedName("balance_last_period_minutes") + val balanceLastPeriodMinutes: java.math.BigDecimal? = null, + + /* vacation consumed in the current vacation period, in minutes */ + @SerializedName("consumed_minutes") + val consumedMinutes: java.math.BigDecimal? = null, + + /* vacation newly granted in the current vacation period, in minutes */ + @SerializedName("new_minutes") + val newMinutes: java.math.BigDecimal? = null, + + /* total vacation balance for the current vacation period, in minutes */ + @SerializedName("balance_total_minutes") + val balanceTotalMinutes: java.math.BigDecimal? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationUnit.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationUnit.kt new file mode 100644 index 0000000..6e8eba3 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VacationUnit.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Unit a vacation entitlement is expressed in. + * + * Values: DAYS,MINUTES + */ + +enum class VacationUnit(val value: kotlin.String) { + + @SerializedName(value = "days") + DAYS("days"), + + @SerializedName(value = "minutes") + MINUTES("minutes"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is VacationUnit) "$data" else null + + /** + * Returns a valid [VacationUnit] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): VacationUnit? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VenuePartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VenuePartial.kt new file mode 100644 index 0000000..53599ab --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/VenuePartial.kt @@ -0,0 +1,80 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param city + * @param zipCode + * @param street + * @param streetNumber + * @param country + * @param lat Latitude in decimal degrees. + * @param lon Longitude in decimal degrees. + */ + + +data class VenuePartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + @SerializedName("city") + val city: kotlin.String, + + @SerializedName("zip_code") + val zipCode: kotlin.String, + + @SerializedName("street") + val street: kotlin.String, + + @SerializedName("street_number") + val streetNumber: kotlin.String, + + @SerializedName("country") + val country: kotlin.String, + + /* Latitude in decimal degrees. */ + @SerializedName("lat") + val lat: kotlin.Float? = null, + + /* Longitude in decimal degrees. */ + @SerializedName("lon") + val lon: kotlin.Float? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Waypoint.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Waypoint.kt new file mode 100644 index 0000000..3042589 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/Waypoint.kt @@ -0,0 +1,49 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param lat + * @param lon + */ + + +data class Waypoint ( + + @SerializedName("lat") + val lat: kotlin.Double, + + @SerializedName("lon") + val lon: kotlin.Double + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModel.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModel.kt new file mode 100644 index 0000000..92ad1ba --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModel.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.WorkScheduleModelType +import com.timr.api.models.WorkScheduleModelWeek +import com.timr.api.models.WorkingTimeRules + +import com.google.gson.annotations.SerializedName + +/** + * The weekday targets a user is measured against: `weeks` holds the layout, `type` selects the calculation mode, and `working_time_rules` the recording constraints. + * + * @param id + * @param name + * @param type working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks) + * @param weeks for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name + * @param workingTimeRules + */ + + +data class WorkScheduleModel ( + + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + /* working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks) */ + @SerializedName("type") + val type: WorkScheduleModelType, + + /* for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name */ + @SerializedName("weeks") + val weeks: kotlin.collections.List, + + @SerializedName("working_time_rules") + val workingTimeRules: WorkingTimeRules? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelPartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelPartial.kt new file mode 100644 index 0000000..3b2a46a --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelPartial.kt @@ -0,0 +1,50 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + */ + + +data class WorkScheduleModelPartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelSortColumn.kt new file mode 100644 index 0000000..b2e8a2d --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Work Schedule Models. + * + * Values: NAME + */ + +enum class WorkScheduleModelSortColumn(val value: kotlin.String) { + + @SerializedName(value = "name") + NAME("name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is WorkScheduleModelSortColumn) "$data" else null + + /** + * Returns a valid [WorkScheduleModelSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): WorkScheduleModelSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelType.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelType.kt new file mode 100644 index 0000000..0f3eba4 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelType.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * How the target working time of the model is defined. + * + * Values: DAILY_TARGET_HOURS,NORMAL_WORKING_TIME + */ + +enum class WorkScheduleModelType(val value: kotlin.String) { + + @SerializedName(value = "daily_target_hours") + DAILY_TARGET_HOURS("daily_target_hours"), + + @SerializedName(value = "normal_working_time") + NORMAL_WORKING_TIME("normal_working_time"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is WorkScheduleModelType) "$data" else null + + /** + * Returns a valid [WorkScheduleModelType] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): WorkScheduleModelType? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelWeek.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelWeek.kt new file mode 100644 index 0000000..8523c7a --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelWeek.kt @@ -0,0 +1,85 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DailyWorkSchedule + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param targetDurationWeeklyMinutes value in minutes + * @param monday + * @param tuesday + * @param wednesday + * @param thursday + * @param friday + * @param saturday + * @param sunday + * @param weekNumber index of the week in alternating_weeks models (0-based); omitted for fixed_week models + * @param name display name of the week in alternating_weeks models; omitted for fixed_week models + */ + + +data class WorkScheduleModelWeek ( + + /* value in minutes */ + @SerializedName("target_duration_weekly_minutes") + val targetDurationWeeklyMinutes: kotlin.Long, + + @SerializedName("monday") + val monday: DailyWorkSchedule, + + @SerializedName("tuesday") + val tuesday: DailyWorkSchedule, + + @SerializedName("wednesday") + val wednesday: DailyWorkSchedule, + + @SerializedName("thursday") + val thursday: DailyWorkSchedule, + + @SerializedName("friday") + val friday: DailyWorkSchedule, + + @SerializedName("saturday") + val saturday: DailyWorkSchedule, + + @SerializedName("sunday") + val sunday: DailyWorkSchedule, + + /* index of the week in alternating_weeks models (0-based); omitted for fixed_week models */ + @SerializedName("week_number") + val weekNumber: kotlin.Int? = null, + + /* display name of the week in alternating_weeks models; omitted for fixed_week models */ + @SerializedName("name") + val name: kotlin.String? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelsPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelsPage.kt new file mode 100644 index 0000000..b7fd1e3 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkScheduleModelsPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.WorkScheduleModel + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class WorkScheduleModelsPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTime.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTime.kt new file mode 100644 index 0000000..2f6f08b --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTime.kt @@ -0,0 +1,131 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTime +import com.timr.api.models.Duration +import com.timr.api.models.Location +import com.timr.api.models.Platform +import com.timr.api.models.UserPartial +import com.timr.api.models.WorkingTimeDateSpanPartial +import com.timr.api.models.WorkingTimeStatus +import com.timr.api.models.WorkingTimeTypePartial + +import com.google.gson.annotations.SerializedName + +/** + * One continuous stretch from `start` to `end`, classified by its `working_time_type`. Attendance entries carry `break_times`, locations and the platform they were recorded on; an entry derived from a multi-day absence links back to its `working_time_date_span`. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param start RFC 3339 date-time (ISO-8601) + * @param end RFC 3339 date-time (ISO-8601) + * @param breakTimeTotalMinutes Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + * @param breakTimes + * @param duration + * @param changed + * @param notes + * @param user + * @param workingTimeType + * @param workingTimeDateSpan + * @param startLocation + * @param endLocation + * @param startPlatform + * @param endPlatform + * @param lastModified Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @param lastModifiedBy Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @param status + * @param metadata + */ + + +data class WorkingTime ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime, + + /* RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime?, + + /* Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties */ + @SerializedName("break_time_total_minutes") + val breakTimeTotalMinutes: kotlin.Int, + + @SerializedName("break_times") + val breakTimes: kotlin.collections.List, + + @SerializedName("duration") + val duration: Duration?, + + @SerializedName("changed") + val changed: kotlin.Boolean, + + @SerializedName("notes") + val notes: kotlin.String?, + + @SerializedName("user") + val user: UserPartial, + + @SerializedName("working_time_type") + val workingTimeType: WorkingTimeTypePartial, + + @SerializedName("working_time_date_span") + val workingTimeDateSpan: WorkingTimeDateSpanPartial?, + + @SerializedName("start_location") + val startLocation: Location?, + + @SerializedName("end_location") + val endLocation: Location?, + + @SerializedName("start_platform") + val startPlatform: Platform?, + + @SerializedName("end_platform") + val endPlatform: Platform?, + + /* Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + @SerializedName("last_modified") + val lastModified: java.time.OffsetDateTime, + + /* Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + @SerializedName("last_modified_by") + val lastModifiedBy: UserPartial?, + + @SerializedName("status") + val status: WorkingTimeStatus, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeCreate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeCreate.kt new file mode 100644 index 0000000..9656edc --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeCreate.kt @@ -0,0 +1,96 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeUpdate +import com.timr.api.models.DurationType +import com.timr.api.models.LocationCreate +import com.timr.api.models.WorkingTimeStatus + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * @param changed + * @param workingTimeTypeId + * @param status + * @param userId + * @param end For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * @param breakTimes + * @param durationType Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @param notes + * @param metadata + * @param startLocation + * @param endLocation + */ + + +data class WorkingTimeCreate ( + + /* For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime, + + @SerializedName("changed") + val changed: kotlin.Boolean, + + @SerializedName("working_time_type_id") + val workingTimeTypeId: kotlin.String, + + @SerializedName("status") + val status: WorkingTimeStatus, + + @SerializedName("user_id") + val userId: kotlin.String, + + /* For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null, + + @SerializedName("break_times") + val breakTimes: kotlin.collections.List? = null, + + /* Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only */ + @SerializedName("duration_type") + val durationType: DurationType? = null, + + @SerializedName("notes") + val notes: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null, + + @SerializedName("start_location") + val startLocation: LocationCreate? = null, + + @SerializedName("end_location") + val endLocation: LocationCreate? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpan.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpan.kt new file mode 100644 index 0000000..76c68b2 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpan.kt @@ -0,0 +1,98 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.UserPartial +import com.timr.api.models.WorkingTimeTypePartial + +import com.google.gson.annotations.SerializedName + +/** + * A span from `start` to `end` of a single `working_time_type`. Every working time derived for a covered day links back to it via `WorkingTime.working_time_date_span`. It can be created directly or become effective through an approved request. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param start RFC 3339 date (ISO-8601) + * @param startHalfDay Marks the first day of the working time date span as a half day. + * @param end RFC 3339 date (ISO-8601) + * @param endHalfDay Marks the last day of the working time date span as a half day. + * @param notes + * @param user + * @param workingTimeType + * @param lastModified Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * @param lastModifiedBy Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * @param substitute + * @param metadata + */ + + +data class WorkingTimeDateSpan ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("start") + val start: java.time.LocalDate, + + /* Marks the first day of the working time date span as a half day. */ + @SerializedName("start_half_day") + val startHalfDay: kotlin.Boolean, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("end") + val end: java.time.LocalDate, + + /* Marks the last day of the working time date span as a half day. */ + @SerializedName("end_half_day") + val endHalfDay: kotlin.Boolean, + + @SerializedName("notes") + val notes: kotlin.String?, + + @SerializedName("user") + val user: UserPartial, + + @SerializedName("working_time_type") + val workingTimeType: WorkingTimeTypePartial, + + /* Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + @SerializedName("last_modified") + val lastModified: java.time.OffsetDateTime, + + /* Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + @SerializedName("last_modified_by") + val lastModifiedBy: UserPartial?, + + @SerializedName("substitute") + val substitute: UserPartial? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanCreate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanCreate.kt new file mode 100644 index 0000000..d5201e1 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanCreate.kt @@ -0,0 +1,79 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start RFC 3339 date (ISO-8601) + * @param end RFC 3339 date (ISO-8601) + * @param workingTimeTypeId + * @param userId + * @param startHalfDay + * @param endHalfDay + * @param notes + * @param substituteId + * @param metadata + */ + + +data class WorkingTimeDateSpanCreate ( + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("start") + val start: java.time.LocalDate, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("end") + val end: java.time.LocalDate, + + @SerializedName("working_time_type_id") + val workingTimeTypeId: kotlin.String, + + @SerializedName("user_id") + val userId: kotlin.String, + + @SerializedName("start_half_day") + val startHalfDay: kotlin.Boolean? = null, + + @SerializedName("end_half_day") + val endHalfDay: kotlin.Boolean? = null, + + @SerializedName("notes") + val notes: kotlin.String? = null, + + @SerializedName("substitute_id") + val substituteId: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanPage.kt new file mode 100644 index 0000000..142d300 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.WorkingTimeDateSpan + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class WorkingTimeDateSpanPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanPartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanPartial.kt new file mode 100644 index 0000000..7c2c694 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanPartial.kt @@ -0,0 +1,46 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * References the date span this working time belongs to, if any. All working times generated for a date span reference the same span; working times recorded on their own have none. + * + * @param id Unique identifier. Treat it as an opaque string. + */ + + +data class WorkingTimeDateSpanPartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanUpdate.kt new file mode 100644 index 0000000..4ef373e --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpanUpdate.kt @@ -0,0 +1,75 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start RFC 3339 date (ISO-8601) + * @param startHalfDay + * @param end RFC 3339 date (ISO-8601) + * @param endHalfDay + * @param notes + * @param workingTimeTypeId + * @param substituteId + * @param metadata + */ + + +data class WorkingTimeDateSpanUpdate ( + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("start") + val start: java.time.LocalDate? = null, + + @SerializedName("start_half_day") + val startHalfDay: kotlin.Boolean? = null, + + /* RFC 3339 date (ISO-8601) */ + @SerializedName("end") + val end: java.time.LocalDate? = null, + + @SerializedName("end_half_day") + val endHalfDay: kotlin.Boolean? = null, + + @SerializedName("notes") + val notes: kotlin.String? = null, + + @SerializedName("working_time_type_id") + val workingTimeTypeId: kotlin.String? = null, + + @SerializedName("substitute_id") + val substituteId: kotlin.String? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpansSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpansSortColumn.kt new file mode 100644 index 0000000..c666c16 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeDateSpansSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Working Time Date Spans. + * + * Values: START + */ + +enum class WorkingTimeDateSpansSortColumn(val value: kotlin.String) { + + @SerializedName(value = "start") + START("start"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is WorkingTimeDateSpansSortColumn) "$data" else null + + /** + * Returns a valid [WorkingTimeDateSpansSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): WorkingTimeDateSpansSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeRules.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeRules.kt new file mode 100644 index 0000000..3228ea4 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeRules.kt @@ -0,0 +1,50 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + */ + + +data class WorkingTimeRules ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeStatus.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeStatus.kt new file mode 100644 index 0000000..f69cfe0 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeStatus.kt @@ -0,0 +1,84 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Processing state of a Working Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, closed and archived. + * + * Values: RUNNING,PAUSED,CHANGEABLE,LOCKED,APPROVED,CLOSED,ARCHIVED + */ + +enum class WorkingTimeStatus(val value: kotlin.String) { + + @SerializedName(value = "running") + RUNNING("running"), + + @SerializedName(value = "paused") + PAUSED("paused"), + + @SerializedName(value = "changeable") + CHANGEABLE("changeable"), + + @SerializedName(value = "locked") + LOCKED("locked"), + + @SerializedName(value = "approved") + APPROVED("approved"), + + @SerializedName(value = "closed") + CLOSED("closed"), + + @SerializedName(value = "archived") + ARCHIVED("archived"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is WorkingTimeStatus) "$data" else null + + /** + * Returns a valid [WorkingTimeStatus] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): WorkingTimeStatus? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeType.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeType.kt new file mode 100644 index 0000000..12aeb26 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeType.kt @@ -0,0 +1,92 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.DurationUnit +import com.timr.api.models.RecordingModeUser +import com.timr.api.models.WorkingTimeTypeCategory +import com.timr.api.models.WorkingTimeTypeSubCategory + +import com.google.gson.annotations.SerializedName + +/** + * A working time type. `category` and `sub_category` place it in the classification, `edit_unit` decides whether it is recorded by time or by day, and `requires_substitute` governs how it is recorded. + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param shortName + * @param description + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + * @param editUnit + * @param category + * @param subCategory + * @param recordingModeUser Specifies how the user can record this working time type. + * @param archived + * @param requiresSubstitute + */ + + +data class WorkingTimeType ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + @SerializedName("short_name") + val shortName: kotlin.String?, + + @SerializedName("description") + val description: kotlin.String?, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String?, + + @SerializedName("edit_unit") + val editUnit: DurationUnit, + + @SerializedName("category") + val category: WorkingTimeTypeCategory, + + @SerializedName("sub_category") + val subCategory: WorkingTimeTypeSubCategory?, + + /* Specifies how the user can record this working time type. */ + @SerializedName("recording_mode_user") + val recordingModeUser: RecordingModeUser, + + @SerializedName("archived") + val archived: kotlin.Boolean, + + @SerializedName("requires_substitute") + val requiresSubstitute: kotlin.Boolean? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypeCategory.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypeCategory.kt new file mode 100644 index 0000000..d8a2045 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypeCategory.kt @@ -0,0 +1,81 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Category of a Working Time Type. `attendance_time` counts as time at work, the remaining categories describe kinds of absence. + * + * Values: ATTENDANCE_TIME,VACATION,PAID_TIME_OFF,UNPAID_TIME_OFF,SUSPENSION,BREAK_TIME + */ + +enum class WorkingTimeTypeCategory(val value: kotlin.String) { + + @SerializedName(value = "attendance_time") + ATTENDANCE_TIME("attendance_time"), + + @SerializedName(value = "vacation") + VACATION("vacation"), + + @SerializedName(value = "paid_time_off") + PAID_TIME_OFF("paid_time_off"), + + @SerializedName(value = "unpaid_time_off") + UNPAID_TIME_OFF("unpaid_time_off"), + + @SerializedName(value = "suspension") + SUSPENSION("suspension"), + + @SerializedName(value = "break_time") + BREAK_TIME("break_time"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is WorkingTimeTypeCategory) "$data" else null + + /** + * Returns a valid [WorkingTimeTypeCategory] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): WorkingTimeTypeCategory? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypePartial.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypePartial.kt new file mode 100644 index 0000000..1e1afbf --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypePartial.kt @@ -0,0 +1,55 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param id Unique identifier. Treat it as an opaque string. + * @param name + * @param externalId Identifier of the corresponding object in an external system. Set and owned by the client. + */ + + +data class WorkingTimeTypePartial ( + + /* Unique identifier. Treat it as an opaque string. */ + @SerializedName("id") + val id: kotlin.String, + + @SerializedName("name") + val name: kotlin.String, + + /* Identifier of the corresponding object in an external system. Set and owned by the client. */ + @SerializedName("external_id") + val externalId: kotlin.String? + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypeSubCategory.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypeSubCategory.kt new file mode 100644 index 0000000..ca0c4e9 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypeSubCategory.kt @@ -0,0 +1,78 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Further classification of a Working Time Type within its category. + * + * Values: PRESENT,WORK_FROM_HOME,AWAY,ACTIVE_DRIVING_TIME,PASSIVE_TRAVELLING_TIME + */ + +enum class WorkingTimeTypeSubCategory(val value: kotlin.String) { + + @SerializedName(value = "present") + PRESENT("present"), + + @SerializedName(value = "work_from_home") + WORK_FROM_HOME("work_from_home"), + + @SerializedName(value = "away") + AWAY("away"), + + @SerializedName(value = "active_driving_time") + ACTIVE_DRIVING_TIME("active_driving_time"), + + @SerializedName(value = "passive_travelling_time") + PASSIVE_TRAVELLING_TIME("passive_travelling_time"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is WorkingTimeTypeSubCategory) "$data" else null + + /** + * Returns a valid [WorkingTimeTypeSubCategory] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): WorkingTimeTypeSubCategory? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypesPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypesPage.kt new file mode 100644 index 0000000..a0dae3b --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypesPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.WorkingTimeType + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class WorkingTimeTypesPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypesSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypesSortColumn.kt new file mode 100644 index 0000000..f994749 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeTypesSortColumn.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Working Time Types. + * + * Values: NAME + */ + +enum class WorkingTimeTypesSortColumn(val value: kotlin.String) { + + @SerializedName(value = "name") + NAME("name"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is WorkingTimeTypesSortColumn) "$data" else null + + /** + * Returns a valid [WorkingTimeTypesSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): WorkingTimeTypesSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeUpdate.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeUpdate.kt new file mode 100644 index 0000000..c40030d --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeUpdate.kt @@ -0,0 +1,92 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeUpdate +import com.timr.api.models.DurationType +import com.timr.api.models.LocationUpdate +import com.timr.api.models.WorkingTimeStatus + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * @param end For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * @param breakTimes + * @param durationType Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @param changed + * @param notes + * @param workingTimeTypeId + * @param status + * @param metadata + * @param startLocation + * @param endLocation + */ + + +data class WorkingTimeUpdate ( + + /* For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime? = null, + + /* For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null, + + @SerializedName("break_times") + val breakTimes: kotlin.collections.List? = null, + + /* Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only */ + @SerializedName("duration_type") + val durationType: DurationType? = null, + + @SerializedName("changed") + val changed: kotlin.Boolean? = null, + + @SerializedName("notes") + val notes: kotlin.String? = null, + + @SerializedName("working_time_type_id") + val workingTimeTypeId: kotlin.String? = null, + + @SerializedName("status") + val status: WorkingTimeStatus? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null, + + @SerializedName("start_location") + val startLocation: LocationUpdate? = null, + + @SerializedName("end_location") + val endLocation: LocationUpdate? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeUpsert.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeUpsert.kt new file mode 100644 index 0000000..4643c68 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimeUpsert.kt @@ -0,0 +1,83 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.BreakTimeUpdate +import com.timr.api.models.DurationType +import com.timr.api.models.WorkingTimeStatus + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param start For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * @param end For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * @param breakTimes + * @param durationType Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @param changed + * @param notes + * @param workingTimeTypeId + * @param status + * @param metadata + */ + + +data class WorkingTimeUpsert ( + + /* For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) */ + @SerializedName("start") + val start: java.time.OffsetDateTime? = null, + + /* For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) */ + @SerializedName("end") + val end: java.time.OffsetDateTime? = null, + + @SerializedName("break_times") + val breakTimes: kotlin.collections.List? = null, + + /* Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only */ + @SerializedName("duration_type") + val durationType: DurationType? = null, + + @SerializedName("changed") + val changed: kotlin.Boolean? = null, + + @SerializedName("notes") + val notes: kotlin.String? = null, + + @SerializedName("working_time_type_id") + val workingTimeTypeId: kotlin.String? = null, + + @SerializedName("status") + val status: WorkingTimeStatus? = null, + + @SerializedName("metadata") + val metadata: kotlin.collections.Map? = null + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimesPage.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimesPage.kt new file mode 100644 index 0000000..3ce0b98 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimesPage.kt @@ -0,0 +1,51 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + +import com.timr.api.models.WorkingTime + +import com.google.gson.annotations.SerializedName + +/** + * + * + * @param nextPageToken Token for the next page, or null when this is the last page. + * @param `data` + */ + + +data class WorkingTimesPage ( + + /* Token for the next page, or null when this is the last page. */ + @SerializedName("next_page_token") + val nextPageToken: kotlin.String?, + + @SerializedName("data") + val `data`: kotlin.collections.List + +) { + + +} + diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimesSortColumn.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimesSortColumn.kt new file mode 100644 index 0000000..30b6ba8 --- /dev/null +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/models/WorkingTimesSortColumn.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "DuplicatedCode", + "EnumEntryName", + "RemoveRedundantQualifierName", + "RemoveRedundantCallsOfConversionMethods", + "REDUNDANT_CALL_OF_CONVERSION_METHOD", + "RedundantUnitReturnType", + "RemoveEmptyClassBody", + "UnnecessaryVariable", + "UnusedImport", + "UnnecessaryVariable", + "unused" +) + +package com.timr.api.models + + +import com.google.gson.annotations.SerializedName + +/** + * Sort property for Working Times. + * + * Values: START,LAST_MODIFIED + */ + +enum class WorkingTimesSortColumn(val value: kotlin.String) { + + @SerializedName(value = "start") + START("start"), + + @SerializedName(value = "last_modified") + LAST_MODIFIED("last_modified"); + + /** + * Override [toString()] to avoid using the enum variable name as the value, and instead use + * the actual value defined in the API spec file. + * + * This solves a problem when the variable name and its value are different, and ensures that + * the client sends the correct enum values to the server always. + */ + override fun toString(): kotlin.String = value + + companion object { + /** + * Converts the provided [data] to a [String] on success, null otherwise. + */ + fun encode(data: kotlin.Any?): kotlin.String? = if (data is WorkingTimesSortColumn) "$data" else null + + /** + * Returns a valid [WorkingTimesSortColumn] for [data], null otherwise. + */ + fun decode(data: kotlin.Any?): WorkingTimesSortColumn? = data?.let { + val normalizedData = "$it".lowercase() + entries.firstOrNull { value -> + it == value || normalizedData == "$value".lowercase() + } + } + } +} + diff --git a/sdk/overlay.yaml b/sdk/overlay.yaml new file mode 100644 index 0000000..eb98f27 --- /dev/null +++ b/sdk/overlay.yaml @@ -0,0 +1,461 @@ +# Fields explicitly approved for SDK log/toString output. +# This file is an allow-list: generated SDK toString/log output must exclude fields +# unless they are annotated with x-log here or in a module-local override. +overlay: 1.0.0 +info: + title: SDK log allow-list + version: 1.0.0 +actions: + - target: "$['components']['schemas']['Duration']['properties']['type']" + update: + x-log: true + - target: "$['components']['schemas']['Duration']['properties']['minutes']" + update: + x-log: true + - target: "$['components']['schemas']['BreakTimeBase']['properties']['type']" + update: + x-log: true + - target: "$['components']['schemas']['BreakTimeManual']['allOf'][*]['properties']['duration_minutes']" + update: + x-log: true + - target: "$['components']['schemas']['BreakTimeManual']['allOf'][*]['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['BreakTimeManual']['allOf'][*]['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['BreakTimeOngoing']['allOf'][*]['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['BreakTimeAutomatic']['allOf'][*]['properties']['duration_minutes']" + update: + x-log: true + - target: "$['components']['schemas']['BreakTimeAutomatic']['allOf'][*]['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['BreakTimeAutomatic']['allOf'][*]['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['UserPartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['UsersPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['UsersPartialPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['TeamPartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['Team']['allOf'][1]['properties']['parent_team']" + update: + x-log: true + - target: "$['components']['schemas']['TeamsPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['TeamsPartialPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['TeamUpdate']['properties']['parent_team_id']" + update: + x-log: true + - target: "$['components']['schemas']['HolidayCalendarPartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['HolidayCalendarsPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['Holiday']['properties']['date']" + update: + x-log: true + - target: "$['components']['schemas']['HolidaysPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['Accounts']['properties']['last_balance_date']" + update: + x-log: true + - target: "$['components']['schemas']['Accounts']['properties']['time_account']" + update: + x-log: true + - target: "$['components']['schemas']['Accounts']['properties']['vacation_account']" + update: + x-log: true + - target: "$['components']['schemas']['Accounts']['properties']['overtime_surcharge_accounts']" + update: + x-log-count: true + - target: "$['components']['schemas']['WorkScheduleModelPartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkScheduleModel']['allOf'][1]['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkScheduleModel']['allOf'][1]['properties']['type']" + update: + x-log: true + - target: "$['components']['schemas']['WorkScheduleModelsPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['DailyWorkSchedule']['properties']['normal_working_times']" + update: + x-log: true + - target: "$['components']['schemas']['NormalWorkingTimes']['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['NormalWorkingTimes']['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeRules']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTime']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTime']['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTime']['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTime']['properties']['user']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTime']['properties']['working_time_type']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTime']['properties']['working_time_date_span']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTime']['properties']['status']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimesPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeUpsert']['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeUpsert']['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeUpsert']['properties']['duration_type']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeUpsert']['properties']['working_time_type_id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeUpsert']['properties']['status']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeCreate']['allOf'][1]['properties']['user_id']" + update: + x-log: true + - target: "$['components']['schemas']['DeletedEntryWithMetadataPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['TaskPartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['Task']['allOf'][1]['properties']['parent_task']" + update: + x-log: true + - target: "$['components']['schemas']['Task']['allOf'][1]['properties']['bookable']" + update: + x-log: true + - target: "$['components']['schemas']['Task']['allOf'][1]['properties']['billable']" + update: + x-log: true + - target: "$['components']['schemas']['Task']['allOf'][1]['properties']['lock_date']" + update: + x-log: true + - target: "$['components']['schemas']['Task']['allOf'][1]['properties']['active_from']" + update: + x-log: true + - target: "$['components']['schemas']['Task']['allOf'][1]['properties']['active_to']" + update: + x-log: true + - target: "$['components']['schemas']['Task']['allOf'][1]['properties']['budget_planning_type']" + update: + x-log: true + - target: "$['components']['schemas']['TaskReduced']['allOf'][1]['properties']['parent_task']" + update: + x-log: true + - target: "$['components']['schemas']['TaskReduced']['allOf'][1]['properties']['bookable']" + update: + x-log: true + - target: "$['components']['schemas']['TaskReduced']['allOf'][1]['properties']['billable']" + update: + x-log: true + - target: "$['components']['schemas']['TaskReduced']['allOf'][1]['properties']['lock_date']" + update: + x-log: true + - target: "$['components']['schemas']['TaskReduced']['allOf'][1]['properties']['active_from']" + update: + x-log: true + - target: "$['components']['schemas']['TaskReduced']['allOf'][1]['properties']['active_to']" + update: + x-log: true + - target: "$['components']['schemas']['TaskReduced']['allOf'][1]['properties']['budget_planning_type']" + update: + x-log: true + - target: "$['components']['schemas']['TasksPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['TasksReducedPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['TaskBase']['properties']['parent_task_id']" + update: + x-log: true + - target: "$['components']['schemas']['TaskBase']['properties']['start_date']" + update: + x-log: true + - target: "$['components']['schemas']['TaskBase']['properties']['end_date']" + update: + x-log: true + - target: "$['components']['schemas']['TaskBase']['properties']['bookable']" + update: + x-log: true + - target: "$['components']['schemas']['TaskBase']['properties']['billable']" + update: + x-log: true + - target: "$['components']['schemas']['TaskBase']['properties']['lock_date']" + update: + x-log: true + - target: "$['components']['schemas']['TaskBase']['properties']['budget_planning_type']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToUserAssignment']['properties']['user']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToUserAssignment']['properties']['recording_lock']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToUserAssignment']['properties']['automatically_assigned']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToUserAssignmentsPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToUserAssignmentUpsert']['properties']['recording_lock']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToLeaderAssignment']['properties']['user']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToLeaderAssignment']['properties']['automatically_assigned']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToLeaderAssignmentsPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToTeamAssignment']['properties']['team']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToTeamAssignment']['properties']['automatically_assigned']" + update: + x-log: true + - target: "$['components']['schemas']['TaskToTeamAssignmentsPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTime']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTime']['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTime']['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTime']['properties']['user']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTime']['properties']['task']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTime']['properties']['billable']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTime']['properties']['status']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTimesPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTimeUpsert']['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTimeUpsert']['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTimeUpsert']['properties']['task_id']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTimeUpsert']['properties']['billable']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTimeUpsert']['properties']['status']" + update: + x-log: true + - target: "$['components']['schemas']['ProjectTimeCreate']['allOf'][1]['properties']['user_id']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['start_mileage']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['end_mileage']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['user']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['car']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['drive_log_category']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['start_venue']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['end_venue']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['has_track']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLog']['properties']['status']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogsPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogUpsert']['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogUpsert']['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogUpsert']['properties']['drive_log_category_id']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogUpsert']['properties']['status']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogCreate']['allOf'][1]['properties']['user_id']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogCreate']['allOf'][1]['properties']['car_id']" + update: + x-log: true + - target: "$['components']['schemas']['CarPartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['Car']['allOf'][1]['properties']['usable']" + update: + x-log: true + - target: "$['components']['schemas']['CarUpdate']['properties']['usable']" + update: + x-log: true + - target: "$['components']['schemas']['CarsPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogCategoryPartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogCategoryPartial']['properties']['business']" + update: + x-log: true + - target: "$['components']['schemas']['DriveLogCategoriesPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['VenuePartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['DeletedEntryPartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['DeletedEntryPartial']['properties']['last_modified']" + update: + x-log: true + - target: "$['components']['schemas']['DeletedEntryPartial']['properties']['last_modified_by']" + update: + x-log: true + - target: "$['components']['schemas']['DeletedEntryPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpanPartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpan']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpan']['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpan']['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpan']['properties']['user']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpan']['properties']['working_time_type']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpan']['properties']['substitute']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpanPage']['allOf'][1]['properties']['data']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpanUpdate']['properties']['start']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpanUpdate']['properties']['end']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpanUpdate']['properties']['working_time_type_id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpanUpdate']['properties']['substitute_id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeDateSpanCreate']['allOf'][0]['properties']['user_id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeTypePartial']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeType']['properties']['id']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeType']['properties']['edit_unit']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeType']['properties']['category']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeType']['properties']['sub_category']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeType']['properties']['recording_mode_user']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeType']['properties']['archived']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeType']['properties']['requires_substitute']" + update: + x-log: true + - target: "$['components']['schemas']['WorkingTimeTypesPage']['allOf'][1]['properties']['data']" + update: + x-log: true diff --git a/sdk/python/.gitignore b/sdk/python/.gitignore new file mode 100644 index 0000000..d919f54 --- /dev/null +++ b/sdk/python/.gitignore @@ -0,0 +1,2 @@ +# OpenApiGenerator generated meta files +.openapi-generator diff --git a/sdk/python/.openapi-generator-ignore b/sdk/python/.openapi-generator-ignore new file mode 100644 index 0000000..40e7a25 --- /dev/null +++ b/sdk/python/.openapi-generator-ignore @@ -0,0 +1,10 @@ +.github/** +.gitignore +.gitlab-ci.yml +.travis.yml +git_push.sh +README.md + +# Markdown docs are repo-only: neither the wheel nor the SPM/CocoaPods package ships them, +# and the reference lives at developer.timr.com. +docs/** diff --git a/sdk/python/LICENSE b/sdk/python/LICENSE new file mode 100644 index 0000000..a8e1185 --- /dev/null +++ b/sdk/python/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 troii Software GmbH + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sdk/python/README.md b/sdk/python/README.md new file mode 100644 index 0000000..09eb59f --- /dev/null +++ b/sdk/python/README.md @@ -0,0 +1,59 @@ +# timr-api + +Official Python client for the [timr](https://www.timr.com) API. + +The timr API exposes the recordings a user makes — working times, project times and drive +logs — together with the master data they refer to: users, teams, tasks, cars, working time +types, work schedule models and holiday calendars. + +**Full API reference: [developer.timr.com](https://developer.timr.com)** + +## Requirements + +Python 3.9+ + +## Installation + +```sh +pip install timr-api +``` + +## Usage + +```python +import os +import timr_api + +configuration = timr_api.Configuration() +configuration.access_token = os.environ["TIMR_ACCESS_TOKEN"] + +with timr_api.ApiClient(configuration) as api_client: + cars = timr_api.CarApi(api_client).fetch_cars() + for car in cars.data: + print(f"{car.name} ({car.plate})") +``` + +`Configuration` defaults to `https://api.timr.com/v1`; pass `host=` to point at another +environment. See `timr_api/configuration.py` for the full set of parameters. + +## Authentication + +The API uses OAuth 2.0. Two flows are supported: + +| Flow | Use for | Scopes | +| --- | --- | --- | +| `client_credentials` | server-to-server integrations acting as the client | `openid`, `timrclient` | +| `authorization_code` (with PKCE) | acting on behalf of a timr user | `openid`, `offline_access` | + +Authorization endpoint: `https://system.timr.com/id/oauth2/authorize` + +Obtain a token through your OAuth library of choice and assign it to +`configuration.access_token`. + +## Support + +[info@timr.com](mailto:info@timr.com) + +## License + +Apache License 2.0 diff --git a/sdk/python/build.gradle b/sdk/python/build.gradle new file mode 100644 index 0000000..87ae85b --- /dev/null +++ b/sdk/python/build.gradle @@ -0,0 +1,38 @@ +plugins { + alias(libs.plugins.openapi) +} +repositories { + mavenCentral() +} + +openApiGenerate { + generatorName = 'python' + templateDir = "$projectDir/templates" + outputDir = "$projectDir" + modelPackage = 'models' + generateModelTests = false + generateApiTests = false + gitHost = 'github.com' + gitUserId = 'troii' + gitRepoId = 'timr-api' + configOptions = [ + packageName : 'timr_api', + packageVersion : project.version, + packageUrl : 'https://developer.timr.com', + hideGenerationTimestamp : 'true', + useOneOfDiscriminatorLookup: 'true', + datetimeFormat : '%Y-%m-%dT%H:%M:%SZ' + ] +} + +tasks.register('cleanOpenApiGenerate', Delete) { + delete fileTree("$projectDir/docs") + delete fileTree("$projectDir/timr_api") +} + +tasks.named('openApiGenerate').configure { task -> + task.dependsOn('cleanOpenApiGenerate') + doFirst { + TimeZone.setDefault(TimeZone.getTimeZone('UTC')) + } +} diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml new file mode 100644 index 0000000..afaf671 --- /dev/null +++ b/sdk/python/pyproject.toml @@ -0,0 +1,95 @@ +[project] +name = "timr_api" +version = "1.0.0" +description = "timr API" +authors = [ + {name = "troii Software GmbH",email = "info@timr.com"}, +] +license = { text = "Apache 2.0" } +readme = "README.md" +keywords = ["OpenAPI", "OpenAPI-Generator", "timr API"] +requires-python = ">=3.9" + +dependencies = [ + "urllib3 (>=2.1.0,<3.0.0)", + "python-dateutil (>=2.8.2)", + "pydantic (>=2.11)", + "typing-extensions (>=4.7.1)", +] + +[project.urls] +Repository = "https://github.com/troii/timr-api" + +[tool.poetry] +requires-poetry = ">=2.0" + +[tool.poetry.group.dev.dependencies] +pytest = ">= 7.2.1" +pytest-cov = ">= 2.8.1" +tox = ">= 3.9.0" +flake8 = ">= 4.0.0" +types-python-dateutil = ">= 2.8.19.14" +mypy = ">= 1.5" + + +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[tool.pylint.'MESSAGES CONTROL'] +extension-pkg-whitelist = "pydantic" + +[tool.mypy] +files = [ + "timr_api", + #"test", # auto-generated tests + "tests", # hand-written tests +] +# TODO: enable "strict" once all these individual checks are passing +# strict = true + +# List from: https://mypy.readthedocs.io/en/stable/existing_code.html#introduce-stricter-options +warn_unused_configs = true +warn_redundant_casts = true +warn_unused_ignores = true + +## Getting these passing should be easy +strict_equality = true +extra_checks = true + +## Strongly recommend enabling this one as soon as you can +check_untyped_defs = true + +## These shouldn't be too much additional work, but may be tricky to +## get passing if you use a lot of untyped libraries +disallow_subclassing_any = true +disallow_untyped_decorators = true +disallow_any_generics = true + +### These next few are various gradations of forcing use of type annotations +#disallow_untyped_calls = true +#disallow_incomplete_defs = true +#disallow_untyped_defs = true +# +### This one isn't too hard to get passing, but return on investment is lower +#no_implicit_reexport = true +# +### This one can be tricky to get passing if you use a lot of untyped libraries +#warn_return_any = true + +[[tool.mypy.overrides]] +module = [ + "timr_api.configuration", +] +warn_unused_ignores = true +strict_equality = true +extra_checks = true +check_untyped_defs = true +disallow_subclassing_any = true +disallow_untyped_decorators = true +disallow_any_generics = true +disallow_untyped_calls = true +disallow_incomplete_defs = true +disallow_untyped_defs = true +no_implicit_reexport = true +warn_return_any = true diff --git a/sdk/python/requirements.txt b/sdk/python/requirements.txt new file mode 100644 index 0000000..9e2d67a --- /dev/null +++ b/sdk/python/requirements.txt @@ -0,0 +1,4 @@ +urllib3 >= 2.1.0, < 3.0.0 +python_dateutil >= 2.8.2 +pydantic >= 2.11 +typing-extensions >= 4.7.1 diff --git a/sdk/python/setup.cfg b/sdk/python/setup.cfg new file mode 100644 index 0000000..11433ee --- /dev/null +++ b/sdk/python/setup.cfg @@ -0,0 +1,2 @@ +[flake8] +max-line-length=99 diff --git a/sdk/python/setup.py b/sdk/python/setup.py new file mode 100644 index 0000000..82cadb5 --- /dev/null +++ b/sdk/python/setup.py @@ -0,0 +1,49 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from setuptools import setup, find_packages # noqa: H301 + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools +NAME = "timr-api" +VERSION = "1.0.0" +PYTHON_REQUIRES = ">= 3.9" +REQUIRES = [ + "urllib3 >= 2.1.0, < 3.0.0", + "python-dateutil >= 2.8.2", + "pydantic >= 2.11", + "typing-extensions >= 4.7.1", +] + +setup( + name=NAME, + version=VERSION, + description="timr API", + author="troii Software GmbH", + author_email="info@timr.com", + url="https://developer.timr.com", + keywords=["OpenAPI", "OpenAPI-Generator", "timr API"], + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + license="Apache 2.0", + long_description_content_type='text/markdown', + long_description="""\ + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + """, # noqa: E501 + package_data={"timr_api": ["py.typed"]}, +) diff --git a/sdk/python/templates/setup.mustache b/sdk/python/templates/setup.mustache new file mode 100644 index 0000000..e691059 --- /dev/null +++ b/sdk/python/templates/setup.mustache @@ -0,0 +1,57 @@ +{{>partial_header}} + +from setuptools import setup, find_packages # noqa: H301 + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools +NAME = "{{{projectName}}}" +VERSION = "{{packageVersion}}" +PYTHON_REQUIRES = ">= 3.9" +REQUIRES = [ +{{^async}} + "urllib3 >= 2.1.0, < 3.0.0", +{{/async}} + "python-dateutil >= 2.8.2", +{{#asyncio}} + "aiohttp >= 3.8.4", + "aiohttp-retry >= 2.8.3", +{{/asyncio}} +{{#httpx}} + "httpx >= 0.28.1", +{{/httpx}} +{{#tornado}} + "tornado>=4.2, < 5", +{{/tornado}} +{{#hasHttpSignatureMethods}} + "pem >= 19.3.0", + "pycryptodome >= 3.9.0", +{{/hasHttpSignatureMethods}} + "pydantic >= 2.11", + "typing-extensions >= 4.7.1", +{{#lazyImports}} + "lazy-imports >= 1, < 2", +{{/lazyImports}} +] + +setup( + name=NAME, + version=VERSION, + description="{{appName}}", + author="{{infoName}}{{^infoName}}OpenAPI Generator community{{/infoName}}", + author_email="{{infoEmail}}{{^infoEmail}}team@openapitools.org{{/infoEmail}}", + url="{{packageUrl}}", + keywords=["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"], + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + {{#licenseInfo}}license="{{.}}", + {{/licenseInfo}}long_description_content_type='text/markdown', + long_description="""\ + {{appDescription}} + """, # noqa: E501 + package_data={"{{{packageName}}}": ["py.typed"]}, +) diff --git a/sdk/python/test-requirements.txt b/sdk/python/test-requirements.txt new file mode 100644 index 0000000..e98555c --- /dev/null +++ b/sdk/python/test-requirements.txt @@ -0,0 +1,6 @@ +pytest >= 7.2.1 +pytest-cov >= 2.8.1 +tox >= 3.9.0 +flake8 >= 4.0.0 +types-python-dateutil >= 2.8.19.14 +mypy >= 1.5 diff --git a/sdk/python/timr_api/__init__.py b/sdk/python/timr_api/__init__.py new file mode 100644 index 0000000..9b04190 --- /dev/null +++ b/sdk/python/timr_api/__init__.py @@ -0,0 +1,347 @@ +# coding: utf-8 + +# flake8: noqa + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +__version__ = "1.0.0" + +# Define package exports +__all__ = [ + "CarApi", + "DriveLogApi", + "DriveLogCategoryApi", + "HolidayCalendarApi", + "ProjectTimeApi", + "TaskApi", + "TaskToLeaderAssignmentApi", + "TaskToTeamAssignmentApi", + "TaskToUserAssignmentApi", + "TeamApi", + "TimeAccountApi", + "TrackApi", + "UserApi", + "WorkScheduleModelApi", + "WorkingTimeApi", + "WorkingTimeDateSpanApi", + "WorkingTimeTypeApi", + "ApiResponse", + "ApiClient", + "Configuration", + "OpenApiException", + "ApiTypeError", + "ApiValueError", + "ApiKeyError", + "ApiAttributeError", + "ApiException", + "Accounts", + "BreakTime", + "BreakTimeAutomatic", + "BreakTimeBase", + "BreakTimeManual", + "BreakTimeOngoing", + "BreakTimeType", + "BreakTimeUpdate", + "BudgetPlanningType", + "BudgetPlanningTypeRequest", + "Car", + "CarCreate", + "CarPartial", + "CarUpdate", + "CarsPage", + "CarsSortColumn", + "DailyWorkSchedule", + "DeletedEntryPage", + "DeletedEntryPartial", + "DeletedEntrySortColumn", + "DeletedEntryWithMetadata", + "DeletedEntryWithMetadataPage", + "DriveLog", + "DriveLogCategoriesPage", + "DriveLogCategoriesSortColumn", + "DriveLogCategory", + "DriveLogCategoryPartial", + "DriveLogCreate", + "DriveLogStatus", + "DriveLogUpdate", + "DriveLogUpsert", + "DriveLogsPage", + "DriveLogsSortColumn", + "Duration", + "DurationType", + "DurationUnit", + "Error", + "ErrorEntry", + "FlexTimeIndicator", + "Holiday", + "HolidayCalendarPartial", + "HolidayCalendarsPage", + "HolidayCalendarsSortColumn", + "HolidaysPage", + "HolidaysSortColumn", + "Location", + "LocationCreate", + "LocationUpdate", + "NormalWorkingTimes", + "OvertimeSurchargeAccount", + "OvertimeSurchargeAccounts", + "OvertimeSurchargeRule", + "PagingInformation", + "Platform", + "ProblemDetail", + "ProjectTime", + "ProjectTimeCreate", + "ProjectTimeStatus", + "ProjectTimeUpdate", + "ProjectTimeUpsert", + "ProjectTimesPage", + "ProjectTimesSortColumn", + "RecordingLockType", + "RecordingModeUser", + "SortDirection", + "Task", + "TaskBase", + "TaskCreate", + "TaskLocation", + "TaskPartial", + "TaskReduced", + "TaskToLeaderAssignment", + "TaskToLeaderAssignmentsPage", + "TaskToLeaderAssignmentsSortColumn", + "TaskToTeamAssignment", + "TaskToTeamAssignmentsPage", + "TaskToTeamAssignmentsSortColumn", + "TaskToUserAssignment", + "TaskToUserAssignmentUpsert", + "TaskToUserAssignmentsPage", + "TaskToUserAssignmentsSortColumn", + "TaskUpdate", + "TasksPage", + "TasksReducedPage", + "TasksSortColumn", + "Team", + "TeamCreate", + "TeamPartial", + "TeamUpdate", + "TeamsPage", + "TeamsPartialPage", + "TeamsSortColumn", + "TimeAccount", + "User", + "UserCreate", + "UserPartial", + "UserUpdate", + "UsersPage", + "UsersPartialPage", + "UsersSortColumn", + "VacationAccount", + "VacationAccountBase", + "VacationAccountDays", + "VacationAccountMinutes", + "VacationUnit", + "VenuePartial", + "Waypoint", + "WorkScheduleModel", + "WorkScheduleModelPartial", + "WorkScheduleModelSortColumn", + "WorkScheduleModelType", + "WorkScheduleModelWeek", + "WorkScheduleModelsPage", + "WorkingTime", + "WorkingTimeCreate", + "WorkingTimeDateSpan", + "WorkingTimeDateSpanCreate", + "WorkingTimeDateSpanPage", + "WorkingTimeDateSpanPartial", + "WorkingTimeDateSpanUpdate", + "WorkingTimeDateSpansSortColumn", + "WorkingTimeRules", + "WorkingTimeStatus", + "WorkingTimeType", + "WorkingTimeTypeCategory", + "WorkingTimeTypePartial", + "WorkingTimeTypeSubCategory", + "WorkingTimeTypesPage", + "WorkingTimeTypesSortColumn", + "WorkingTimeUpdate", + "WorkingTimeUpsert", + "WorkingTimesPage", + "WorkingTimesSortColumn", +] + +# import apis into sdk package +from timr_api.api.car_api import CarApi as CarApi +from timr_api.api.drive_log_api import DriveLogApi as DriveLogApi +from timr_api.api.drive_log_category_api import DriveLogCategoryApi as DriveLogCategoryApi +from timr_api.api.holiday_calendar_api import HolidayCalendarApi as HolidayCalendarApi +from timr_api.api.project_time_api import ProjectTimeApi as ProjectTimeApi +from timr_api.api.task_api import TaskApi as TaskApi +from timr_api.api.task_to_leader_assignment_api import TaskToLeaderAssignmentApi as TaskToLeaderAssignmentApi +from timr_api.api.task_to_team_assignment_api import TaskToTeamAssignmentApi as TaskToTeamAssignmentApi +from timr_api.api.task_to_user_assignment_api import TaskToUserAssignmentApi as TaskToUserAssignmentApi +from timr_api.api.team_api import TeamApi as TeamApi +from timr_api.api.time_account_api import TimeAccountApi as TimeAccountApi +from timr_api.api.track_api import TrackApi as TrackApi +from timr_api.api.user_api import UserApi as UserApi +from timr_api.api.work_schedule_model_api import WorkScheduleModelApi as WorkScheduleModelApi +from timr_api.api.working_time_api import WorkingTimeApi as WorkingTimeApi +from timr_api.api.working_time_date_span_api import WorkingTimeDateSpanApi as WorkingTimeDateSpanApi +from timr_api.api.working_time_type_api import WorkingTimeTypeApi as WorkingTimeTypeApi + +# import ApiClient +from timr_api.api_response import ApiResponse as ApiResponse +from timr_api.api_client import ApiClient as ApiClient +from timr_api.configuration import Configuration as Configuration +from timr_api.exceptions import OpenApiException as OpenApiException +from timr_api.exceptions import ApiTypeError as ApiTypeError +from timr_api.exceptions import ApiValueError as ApiValueError +from timr_api.exceptions import ApiKeyError as ApiKeyError +from timr_api.exceptions import ApiAttributeError as ApiAttributeError +from timr_api.exceptions import ApiException as ApiException + +# import models into sdk package +from timr_api.models.accounts import Accounts as Accounts +from timr_api.models.break_time import BreakTime as BreakTime +from timr_api.models.break_time_automatic import BreakTimeAutomatic as BreakTimeAutomatic +from timr_api.models.break_time_base import BreakTimeBase as BreakTimeBase +from timr_api.models.break_time_manual import BreakTimeManual as BreakTimeManual +from timr_api.models.break_time_ongoing import BreakTimeOngoing as BreakTimeOngoing +from timr_api.models.break_time_type import BreakTimeType as BreakTimeType +from timr_api.models.break_time_update import BreakTimeUpdate as BreakTimeUpdate +from timr_api.models.budget_planning_type import BudgetPlanningType as BudgetPlanningType +from timr_api.models.budget_planning_type_request import BudgetPlanningTypeRequest as BudgetPlanningTypeRequest +from timr_api.models.car import Car as Car +from timr_api.models.car_create import CarCreate as CarCreate +from timr_api.models.car_partial import CarPartial as CarPartial +from timr_api.models.car_update import CarUpdate as CarUpdate +from timr_api.models.cars_page import CarsPage as CarsPage +from timr_api.models.cars_sort_column import CarsSortColumn as CarsSortColumn +from timr_api.models.daily_work_schedule import DailyWorkSchedule as DailyWorkSchedule +from timr_api.models.deleted_entry_page import DeletedEntryPage as DeletedEntryPage +from timr_api.models.deleted_entry_partial import DeletedEntryPartial as DeletedEntryPartial +from timr_api.models.deleted_entry_sort_column import DeletedEntrySortColumn as DeletedEntrySortColumn +from timr_api.models.deleted_entry_with_metadata import DeletedEntryWithMetadata as DeletedEntryWithMetadata +from timr_api.models.deleted_entry_with_metadata_page import DeletedEntryWithMetadataPage as DeletedEntryWithMetadataPage +from timr_api.models.drive_log import DriveLog as DriveLog +from timr_api.models.drive_log_categories_page import DriveLogCategoriesPage as DriveLogCategoriesPage +from timr_api.models.drive_log_categories_sort_column import DriveLogCategoriesSortColumn as DriveLogCategoriesSortColumn +from timr_api.models.drive_log_category import DriveLogCategory as DriveLogCategory +from timr_api.models.drive_log_category_partial import DriveLogCategoryPartial as DriveLogCategoryPartial +from timr_api.models.drive_log_create import DriveLogCreate as DriveLogCreate +from timr_api.models.drive_log_status import DriveLogStatus as DriveLogStatus +from timr_api.models.drive_log_update import DriveLogUpdate as DriveLogUpdate +from timr_api.models.drive_log_upsert import DriveLogUpsert as DriveLogUpsert +from timr_api.models.drive_logs_page import DriveLogsPage as DriveLogsPage +from timr_api.models.drive_logs_sort_column import DriveLogsSortColumn as DriveLogsSortColumn +from timr_api.models.duration import Duration as Duration +from timr_api.models.duration_type import DurationType as DurationType +from timr_api.models.duration_unit import DurationUnit as DurationUnit +from timr_api.models.error import Error as Error +from timr_api.models.error_entry import ErrorEntry as ErrorEntry +from timr_api.models.flex_time_indicator import FlexTimeIndicator as FlexTimeIndicator +from timr_api.models.holiday import Holiday as Holiday +from timr_api.models.holiday_calendar_partial import HolidayCalendarPartial as HolidayCalendarPartial +from timr_api.models.holiday_calendars_page import HolidayCalendarsPage as HolidayCalendarsPage +from timr_api.models.holiday_calendars_sort_column import HolidayCalendarsSortColumn as HolidayCalendarsSortColumn +from timr_api.models.holidays_page import HolidaysPage as HolidaysPage +from timr_api.models.holidays_sort_column import HolidaysSortColumn as HolidaysSortColumn +from timr_api.models.location import Location as Location +from timr_api.models.location_create import LocationCreate as LocationCreate +from timr_api.models.location_update import LocationUpdate as LocationUpdate +from timr_api.models.normal_working_times import NormalWorkingTimes as NormalWorkingTimes +from timr_api.models.overtime_surcharge_account import OvertimeSurchargeAccount as OvertimeSurchargeAccount +from timr_api.models.overtime_surcharge_accounts import OvertimeSurchargeAccounts as OvertimeSurchargeAccounts +from timr_api.models.overtime_surcharge_rule import OvertimeSurchargeRule as OvertimeSurchargeRule +from timr_api.models.paging_information import PagingInformation as PagingInformation +from timr_api.models.platform import Platform as Platform +from timr_api.models.problem_detail import ProblemDetail as ProblemDetail +from timr_api.models.project_time import ProjectTime as ProjectTime +from timr_api.models.project_time_create import ProjectTimeCreate as ProjectTimeCreate +from timr_api.models.project_time_status import ProjectTimeStatus as ProjectTimeStatus +from timr_api.models.project_time_update import ProjectTimeUpdate as ProjectTimeUpdate +from timr_api.models.project_time_upsert import ProjectTimeUpsert as ProjectTimeUpsert +from timr_api.models.project_times_page import ProjectTimesPage as ProjectTimesPage +from timr_api.models.project_times_sort_column import ProjectTimesSortColumn as ProjectTimesSortColumn +from timr_api.models.recording_lock_type import RecordingLockType as RecordingLockType +from timr_api.models.recording_mode_user import RecordingModeUser as RecordingModeUser +from timr_api.models.sort_direction import SortDirection as SortDirection +from timr_api.models.task import Task as Task +from timr_api.models.task_base import TaskBase as TaskBase +from timr_api.models.task_create import TaskCreate as TaskCreate +from timr_api.models.task_location import TaskLocation as TaskLocation +from timr_api.models.task_partial import TaskPartial as TaskPartial +from timr_api.models.task_reduced import TaskReduced as TaskReduced +from timr_api.models.task_to_leader_assignment import TaskToLeaderAssignment as TaskToLeaderAssignment +from timr_api.models.task_to_leader_assignments_page import TaskToLeaderAssignmentsPage as TaskToLeaderAssignmentsPage +from timr_api.models.task_to_leader_assignments_sort_column import TaskToLeaderAssignmentsSortColumn as TaskToLeaderAssignmentsSortColumn +from timr_api.models.task_to_team_assignment import TaskToTeamAssignment as TaskToTeamAssignment +from timr_api.models.task_to_team_assignments_page import TaskToTeamAssignmentsPage as TaskToTeamAssignmentsPage +from timr_api.models.task_to_team_assignments_sort_column import TaskToTeamAssignmentsSortColumn as TaskToTeamAssignmentsSortColumn +from timr_api.models.task_to_user_assignment import TaskToUserAssignment as TaskToUserAssignment +from timr_api.models.task_to_user_assignment_upsert import TaskToUserAssignmentUpsert as TaskToUserAssignmentUpsert +from timr_api.models.task_to_user_assignments_page import TaskToUserAssignmentsPage as TaskToUserAssignmentsPage +from timr_api.models.task_to_user_assignments_sort_column import TaskToUserAssignmentsSortColumn as TaskToUserAssignmentsSortColumn +from timr_api.models.task_update import TaskUpdate as TaskUpdate +from timr_api.models.tasks_page import TasksPage as TasksPage +from timr_api.models.tasks_reduced_page import TasksReducedPage as TasksReducedPage +from timr_api.models.tasks_sort_column import TasksSortColumn as TasksSortColumn +from timr_api.models.team import Team as Team +from timr_api.models.team_create import TeamCreate as TeamCreate +from timr_api.models.team_partial import TeamPartial as TeamPartial +from timr_api.models.team_update import TeamUpdate as TeamUpdate +from timr_api.models.teams_page import TeamsPage as TeamsPage +from timr_api.models.teams_partial_page import TeamsPartialPage as TeamsPartialPage +from timr_api.models.teams_sort_column import TeamsSortColumn as TeamsSortColumn +from timr_api.models.time_account import TimeAccount as TimeAccount +from timr_api.models.user import User as User +from timr_api.models.user_create import UserCreate as UserCreate +from timr_api.models.user_partial import UserPartial as UserPartial +from timr_api.models.user_update import UserUpdate as UserUpdate +from timr_api.models.users_page import UsersPage as UsersPage +from timr_api.models.users_partial_page import UsersPartialPage as UsersPartialPage +from timr_api.models.users_sort_column import UsersSortColumn as UsersSortColumn +from timr_api.models.vacation_account import VacationAccount as VacationAccount +from timr_api.models.vacation_account_base import VacationAccountBase as VacationAccountBase +from timr_api.models.vacation_account_days import VacationAccountDays as VacationAccountDays +from timr_api.models.vacation_account_minutes import VacationAccountMinutes as VacationAccountMinutes +from timr_api.models.vacation_unit import VacationUnit as VacationUnit +from timr_api.models.venue_partial import VenuePartial as VenuePartial +from timr_api.models.waypoint import Waypoint as Waypoint +from timr_api.models.work_schedule_model import WorkScheduleModel as WorkScheduleModel +from timr_api.models.work_schedule_model_partial import WorkScheduleModelPartial as WorkScheduleModelPartial +from timr_api.models.work_schedule_model_sort_column import WorkScheduleModelSortColumn as WorkScheduleModelSortColumn +from timr_api.models.work_schedule_model_type import WorkScheduleModelType as WorkScheduleModelType +from timr_api.models.work_schedule_model_week import WorkScheduleModelWeek as WorkScheduleModelWeek +from timr_api.models.work_schedule_models_page import WorkScheduleModelsPage as WorkScheduleModelsPage +from timr_api.models.working_time import WorkingTime as WorkingTime +from timr_api.models.working_time_create import WorkingTimeCreate as WorkingTimeCreate +from timr_api.models.working_time_date_span import WorkingTimeDateSpan as WorkingTimeDateSpan +from timr_api.models.working_time_date_span_create import WorkingTimeDateSpanCreate as WorkingTimeDateSpanCreate +from timr_api.models.working_time_date_span_page import WorkingTimeDateSpanPage as WorkingTimeDateSpanPage +from timr_api.models.working_time_date_span_partial import WorkingTimeDateSpanPartial as WorkingTimeDateSpanPartial +from timr_api.models.working_time_date_span_update import WorkingTimeDateSpanUpdate as WorkingTimeDateSpanUpdate +from timr_api.models.working_time_date_spans_sort_column import WorkingTimeDateSpansSortColumn as WorkingTimeDateSpansSortColumn +from timr_api.models.working_time_rules import WorkingTimeRules as WorkingTimeRules +from timr_api.models.working_time_status import WorkingTimeStatus as WorkingTimeStatus +from timr_api.models.working_time_type import WorkingTimeType as WorkingTimeType +from timr_api.models.working_time_type_category import WorkingTimeTypeCategory as WorkingTimeTypeCategory +from timr_api.models.working_time_type_partial import WorkingTimeTypePartial as WorkingTimeTypePartial +from timr_api.models.working_time_type_sub_category import WorkingTimeTypeSubCategory as WorkingTimeTypeSubCategory +from timr_api.models.working_time_types_page import WorkingTimeTypesPage as WorkingTimeTypesPage +from timr_api.models.working_time_types_sort_column import WorkingTimeTypesSortColumn as WorkingTimeTypesSortColumn +from timr_api.models.working_time_update import WorkingTimeUpdate as WorkingTimeUpdate +from timr_api.models.working_time_upsert import WorkingTimeUpsert as WorkingTimeUpsert +from timr_api.models.working_times_page import WorkingTimesPage as WorkingTimesPage +from timr_api.models.working_times_sort_column import WorkingTimesSortColumn as WorkingTimesSortColumn + diff --git a/sdk/python/timr_api/api/__init__.py b/sdk/python/timr_api/api/__init__.py new file mode 100644 index 0000000..98d004b --- /dev/null +++ b/sdk/python/timr_api/api/__init__.py @@ -0,0 +1,21 @@ +# flake8: noqa + +# import apis into api package +from timr_api.api.car_api import CarApi +from timr_api.api.drive_log_api import DriveLogApi +from timr_api.api.drive_log_category_api import DriveLogCategoryApi +from timr_api.api.holiday_calendar_api import HolidayCalendarApi +from timr_api.api.project_time_api import ProjectTimeApi +from timr_api.api.task_api import TaskApi +from timr_api.api.task_to_leader_assignment_api import TaskToLeaderAssignmentApi +from timr_api.api.task_to_team_assignment_api import TaskToTeamAssignmentApi +from timr_api.api.task_to_user_assignment_api import TaskToUserAssignmentApi +from timr_api.api.team_api import TeamApi +from timr_api.api.time_account_api import TimeAccountApi +from timr_api.api.track_api import TrackApi +from timr_api.api.user_api import UserApi +from timr_api.api.work_schedule_model_api import WorkScheduleModelApi +from timr_api.api.working_time_api import WorkingTimeApi +from timr_api.api.working_time_date_span_api import WorkingTimeDateSpanApi +from timr_api.api.working_time_type_api import WorkingTimeTypeApi + diff --git a/sdk/python/timr_api/api/car_api.py b/sdk/python/timr_api/api/car_api.py new file mode 100644 index 0000000..4d3ad28 --- /dev/null +++ b/sdk/python/timr_api/api/car_api.py @@ -0,0 +1,1258 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictBool, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.car import Car +from timr_api.models.car_create import CarCreate +from timr_api.models.car_update import CarUpdate +from timr_api.models.cars_page import CarsPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class CarApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_car( + self, + car_create: Annotated[CarCreate, Field(description="Car entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Car: + """Create a Car + + Creates a Car from the data in the request body. + + :param car_create: Car entity (required) + :type car_create: CarCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_car_serialize( + car_create=car_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Car", + '400': "Error", + '403': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_car_with_http_info( + self, + car_create: Annotated[CarCreate, Field(description="Car entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Car]: + """Create a Car + + Creates a Car from the data in the request body. + + :param car_create: Car entity (required) + :type car_create: CarCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_car_serialize( + car_create=car_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Car", + '400': "Error", + '403': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_car_without_preload_content( + self, + car_create: Annotated[CarCreate, Field(description="Car entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Car + + Creates a Car from the data in the request body. + + :param car_create: Car entity (required) + :type car_create: CarCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_car_serialize( + car_create=car_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Car", + '400': "Error", + '403': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_car_serialize( + self, + car_create, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if car_create is not None: + _body_params = car_create + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/cars', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_cars( + self, + name_or_plate: Annotated[Optional[StrictStr], Field(description="Only return Cars whose name or plate contains this text.")] = None, + usable: Annotated[Optional[StrictBool], Field(description="Only return Cars that are usable (true) or not usable (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> CarsPage: + """List Cars + + Lists the Cars the authenticated user or API token can access. + + :param name_or_plate: Only return Cars whose name or plate contains this text. + :type name_or_plate: str + :param usable: Only return Cars that are usable (true) or not usable (false). + :type usable: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: CarsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_cars_serialize( + name_or_plate=name_or_plate, + usable=usable, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "CarsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_cars_with_http_info( + self, + name_or_plate: Annotated[Optional[StrictStr], Field(description="Only return Cars whose name or plate contains this text.")] = None, + usable: Annotated[Optional[StrictBool], Field(description="Only return Cars that are usable (true) or not usable (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[CarsPage]: + """List Cars + + Lists the Cars the authenticated user or API token can access. + + :param name_or_plate: Only return Cars whose name or plate contains this text. + :type name_or_plate: str + :param usable: Only return Cars that are usable (true) or not usable (false). + :type usable: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: CarsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_cars_serialize( + name_or_plate=name_or_plate, + usable=usable, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "CarsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_cars_without_preload_content( + self, + name_or_plate: Annotated[Optional[StrictStr], Field(description="Only return Cars whose name or plate contains this text.")] = None, + usable: Annotated[Optional[StrictBool], Field(description="Only return Cars that are usable (true) or not usable (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Cars + + Lists the Cars the authenticated user or API token can access. + + :param name_or_plate: Only return Cars whose name or plate contains this text. + :type name_or_plate: str + :param usable: Only return Cars that are usable (true) or not usable (false). + :type usable: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: CarsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_cars_serialize( + name_or_plate=name_or_plate, + usable=usable, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "CarsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_cars_serialize( + self, + name_or_plate, + usable, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if name_or_plate is not None: + + _query_params.append(('name_or_plate', name_or_plate)) + + if usable is not None: + + _query_params.append(('usable', usable)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/cars', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_car( + self, + id: Annotated[StrictStr, Field(description="ID of the Car.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Car: + """Get a Car + + Returns a single Car by its ID. + + :param id: ID of the Car. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_car_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Car", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_car_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Car.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Car]: + """Get a Car + + Returns a single Car by its ID. + + :param id: ID of the Car. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_car_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Car", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_car_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Car.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Car + + Returns a single Car by its ID. + + :param id: ID of the Car. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_car_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Car", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_car_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/cars/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def update_car( + self, + id: Annotated[StrictStr, Field(description="ID of the Car.")], + car_update: Annotated[CarUpdate, Field(description="Car entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Car: + """Update a Car + + Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Car. (required) + :type id: str + :param car_update: Car entity (required) + :type car_update: CarUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_car_serialize( + id=id, + car_update=car_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Car", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def update_car_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Car.")], + car_update: Annotated[CarUpdate, Field(description="Car entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Car]: + """Update a Car + + Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Car. (required) + :type id: str + :param car_update: Car entity (required) + :type car_update: CarUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_car_serialize( + id=id, + car_update=car_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Car", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_car_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Car.")], + car_update: Annotated[CarUpdate, Field(description="Car entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update a Car + + Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Car. (required) + :type id: str + :param car_update: Car entity (required) + :type car_update: CarUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_car_serialize( + id=id, + car_update=car_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Car", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _update_car_serialize( + self, + id, + car_update, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if car_update is not None: + _body_params = car_update + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/cars/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/drive_log_api.py b/sdk/python/timr_api/api/drive_log_api.py new file mode 100644 index 0000000..650c914 --- /dev/null +++ b/sdk/python/timr_api/api/drive_log_api.py @@ -0,0 +1,2041 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from datetime import date, datetime +from pydantic import Field, StrictBool, StrictStr +from typing import Any, List, Optional +from typing_extensions import Annotated +from timr_api.models.deleted_entry_page import DeletedEntryPage +from timr_api.models.drive_log import DriveLog +from timr_api.models.drive_log_create import DriveLogCreate +from timr_api.models.drive_log_status import DriveLogStatus +from timr_api.models.drive_log_update import DriveLogUpdate +from timr_api.models.drive_logs_page import DriveLogsPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class DriveLogApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_drive_log( + self, + drive_log_create: Annotated[DriveLogCreate, Field(description="Drive Log entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DriveLog: + """Create a Drive Log + + Creates a Drive Log from the data in the request body. + + :param drive_log_create: Drive Log entity (required) + :type drive_log_create: DriveLogCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_drive_log_serialize( + drive_log_create=drive_log_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "DriveLog", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_drive_log_with_http_info( + self, + drive_log_create: Annotated[DriveLogCreate, Field(description="Drive Log entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DriveLog]: + """Create a Drive Log + + Creates a Drive Log from the data in the request body. + + :param drive_log_create: Drive Log entity (required) + :type drive_log_create: DriveLogCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_drive_log_serialize( + drive_log_create=drive_log_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "DriveLog", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_drive_log_without_preload_content( + self, + drive_log_create: Annotated[DriveLogCreate, Field(description="Drive Log entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Drive Log + + Creates a Drive Log from the data in the request body. + + :param drive_log_create: Drive Log entity (required) + :type drive_log_create: DriveLogCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_drive_log_serialize( + drive_log_create=drive_log_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "DriveLog", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_drive_log_serialize( + self, + drive_log_create, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if drive_log_create is not None: + _body_params = drive_log_create + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/drive-logs', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def delete_drive_log( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Drive Log + + Deletes the Drive Log, including its Track. + + :param id: ID of the Drive Log. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_drive_log_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_drive_log_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Drive Log + + Deletes the Drive Log, including its Track. + + :param id: ID of the Drive Log. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_drive_log_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_drive_log_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Drive Log + + Deletes the Drive Log, including its Track. + + :param id: ID of the Drive Log. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_drive_log_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_drive_log_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/drive-logs/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_deleted_drive_logs( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DeletedEntryPage: + """List deleted Drive Logs + + Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_drive_logs_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_deleted_drive_logs_with_http_info( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DeletedEntryPage]: + """List deleted Drive Logs + + Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_drive_logs_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_deleted_drive_logs_without_preload_content( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List deleted Drive Logs + + Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_drive_logs_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_deleted_drive_logs_serialize( + self, + last_modified_after, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if last_modified_after is not None: + if isinstance(last_modified_after, datetime): + _query_params.append( + ( + 'last_modified_after', + last_modified_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('last_modified_after', last_modified_after)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/drive-logs:deleted', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_drive_logs( + self, + start_from: Annotated[Optional[date], Field(description="Only return entries starting on or after this day.")] = None, + start_to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + cars: Annotated[Optional[List[StrictStr]], Field(description="Only return entries recorded for these Cars.")] = None, + drive_log_categories: Annotated[Optional[List[StrictStr]], Field(description="Only return entries in these Drive Log Categories.")] = None, + statuses: Annotated[Optional[List[DriveLogStatus]], Field(description="Only return entries in one of these statuses.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + details: Annotated[Optional[StrictStr], Field(description="Only return Drive Logs whose route, purpose or visited contains this text.")] = None, + changed: Annotated[Optional[StrictBool], Field(description="Only return entries that were changed by the user (true) or left unchanged (false).")] = None, + has_track: Annotated[Optional[StrictBool], Field(description="Only return Drive Logs that have a Track (true) or have none (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DriveLogsPage: + """List Drive Logs + + Lists the Drive Logs the authenticated user or API token can access. + + :param start_from: Only return entries starting on or after this day. + :type start_from: date + :param start_to: Only return entries starting on or before this day. + :type start_to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param cars: Only return entries recorded for these Cars. + :type cars: List[str] + :param drive_log_categories: Only return entries in these Drive Log Categories. + :type drive_log_categories: List[str] + :param statuses: Only return entries in one of these statuses. + :type statuses: List[DriveLogStatus] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param details: Only return Drive Logs whose route, purpose or visited contains this text. + :type details: str + :param changed: Only return entries that were changed by the user (true) or left unchanged (false). + :type changed: bool + :param has_track: Only return Drive Logs that have a Track (true) or have none (false). + :type has_track: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DriveLogsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_drive_logs_serialize( + start_from=start_from, + start_to=start_to, + last_modified_after=last_modified_after, + cars=cars, + drive_log_categories=drive_log_categories, + statuses=statuses, + users=users, + details=details, + changed=changed, + has_track=has_track, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLogsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_drive_logs_with_http_info( + self, + start_from: Annotated[Optional[date], Field(description="Only return entries starting on or after this day.")] = None, + start_to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + cars: Annotated[Optional[List[StrictStr]], Field(description="Only return entries recorded for these Cars.")] = None, + drive_log_categories: Annotated[Optional[List[StrictStr]], Field(description="Only return entries in these Drive Log Categories.")] = None, + statuses: Annotated[Optional[List[DriveLogStatus]], Field(description="Only return entries in one of these statuses.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + details: Annotated[Optional[StrictStr], Field(description="Only return Drive Logs whose route, purpose or visited contains this text.")] = None, + changed: Annotated[Optional[StrictBool], Field(description="Only return entries that were changed by the user (true) or left unchanged (false).")] = None, + has_track: Annotated[Optional[StrictBool], Field(description="Only return Drive Logs that have a Track (true) or have none (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DriveLogsPage]: + """List Drive Logs + + Lists the Drive Logs the authenticated user or API token can access. + + :param start_from: Only return entries starting on or after this day. + :type start_from: date + :param start_to: Only return entries starting on or before this day. + :type start_to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param cars: Only return entries recorded for these Cars. + :type cars: List[str] + :param drive_log_categories: Only return entries in these Drive Log Categories. + :type drive_log_categories: List[str] + :param statuses: Only return entries in one of these statuses. + :type statuses: List[DriveLogStatus] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param details: Only return Drive Logs whose route, purpose or visited contains this text. + :type details: str + :param changed: Only return entries that were changed by the user (true) or left unchanged (false). + :type changed: bool + :param has_track: Only return Drive Logs that have a Track (true) or have none (false). + :type has_track: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DriveLogsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_drive_logs_serialize( + start_from=start_from, + start_to=start_to, + last_modified_after=last_modified_after, + cars=cars, + drive_log_categories=drive_log_categories, + statuses=statuses, + users=users, + details=details, + changed=changed, + has_track=has_track, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLogsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_drive_logs_without_preload_content( + self, + start_from: Annotated[Optional[date], Field(description="Only return entries starting on or after this day.")] = None, + start_to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + cars: Annotated[Optional[List[StrictStr]], Field(description="Only return entries recorded for these Cars.")] = None, + drive_log_categories: Annotated[Optional[List[StrictStr]], Field(description="Only return entries in these Drive Log Categories.")] = None, + statuses: Annotated[Optional[List[DriveLogStatus]], Field(description="Only return entries in one of these statuses.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + details: Annotated[Optional[StrictStr], Field(description="Only return Drive Logs whose route, purpose or visited contains this text.")] = None, + changed: Annotated[Optional[StrictBool], Field(description="Only return entries that were changed by the user (true) or left unchanged (false).")] = None, + has_track: Annotated[Optional[StrictBool], Field(description="Only return Drive Logs that have a Track (true) or have none (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Drive Logs + + Lists the Drive Logs the authenticated user or API token can access. + + :param start_from: Only return entries starting on or after this day. + :type start_from: date + :param start_to: Only return entries starting on or before this day. + :type start_to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param cars: Only return entries recorded for these Cars. + :type cars: List[str] + :param drive_log_categories: Only return entries in these Drive Log Categories. + :type drive_log_categories: List[str] + :param statuses: Only return entries in one of these statuses. + :type statuses: List[DriveLogStatus] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param details: Only return Drive Logs whose route, purpose or visited contains this text. + :type details: str + :param changed: Only return entries that were changed by the user (true) or left unchanged (false). + :type changed: bool + :param has_track: Only return Drive Logs that have a Track (true) or have none (false). + :type has_track: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DriveLogsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_drive_logs_serialize( + start_from=start_from, + start_to=start_to, + last_modified_after=last_modified_after, + cars=cars, + drive_log_categories=drive_log_categories, + statuses=statuses, + users=users, + details=details, + changed=changed, + has_track=has_track, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLogsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_drive_logs_serialize( + self, + start_from, + start_to, + last_modified_after, + cars, + drive_log_categories, + statuses, + users, + details, + changed, + has_track, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'cars': 'multi', + 'drive_log_categories': 'multi', + 'statuses': 'multi', + 'users': 'multi', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if start_from is not None: + if isinstance(start_from, date): + _query_params.append( + ( + 'start_from', + start_from.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('start_from', start_from)) + + if start_to is not None: + if isinstance(start_to, date): + _query_params.append( + ( + 'start_to', + start_to.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('start_to', start_to)) + + if last_modified_after is not None: + if isinstance(last_modified_after, datetime): + _query_params.append( + ( + 'last_modified_after', + last_modified_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('last_modified_after', last_modified_after)) + + if cars is not None: + + _query_params.append(('cars', cars)) + + if drive_log_categories is not None: + + _query_params.append(('drive_log_categories', drive_log_categories)) + + if statuses is not None: + + _query_params.append(('statuses', statuses)) + + if users is not None: + + _query_params.append(('users', users)) + + if details is not None: + + _query_params.append(('details', details)) + + if changed is not None: + + _query_params.append(('changed', changed)) + + if has_track is not None: + + _query_params.append(('has_track', has_track)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/drive-logs', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_drive_log( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DriveLog: + """Get a Drive Log + + Returns a single Drive Log by its ID. + + :param id: ID of the Drive Log. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_drive_log_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLog", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_drive_log_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DriveLog]: + """Get a Drive Log + + Returns a single Drive Log by its ID. + + :param id: ID of the Drive Log. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_drive_log_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLog", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_drive_log_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Drive Log + + Returns a single Drive Log by its ID. + + :param id: ID of the Drive Log. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_drive_log_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLog", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_drive_log_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/drive-logs/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def update_drive_log( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log.")], + drive_log_update: Annotated[DriveLogUpdate, Field(description="Drive Log entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DriveLog: + """Update a Drive Log + + Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Drive Log. (required) + :type id: str + :param drive_log_update: Drive Log entity (required) + :type drive_log_update: DriveLogUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_drive_log_serialize( + id=id, + drive_log_update=drive_log_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLog", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def update_drive_log_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log.")], + drive_log_update: Annotated[DriveLogUpdate, Field(description="Drive Log entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DriveLog]: + """Update a Drive Log + + Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Drive Log. (required) + :type id: str + :param drive_log_update: Drive Log entity (required) + :type drive_log_update: DriveLogUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_drive_log_serialize( + id=id, + drive_log_update=drive_log_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLog", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_drive_log_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log.")], + drive_log_update: Annotated[DriveLogUpdate, Field(description="Drive Log entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update a Drive Log + + Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Drive Log. (required) + :type id: str + :param drive_log_update: Drive Log entity (required) + :type drive_log_update: DriveLogUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_drive_log_serialize( + id=id, + drive_log_update=drive_log_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLog", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _update_drive_log_serialize( + self, + id, + drive_log_update, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if drive_log_update is not None: + _body_params = drive_log_update + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/drive-logs/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/drive_log_category_api.py b/sdk/python/timr_api/api/drive_log_category_api.py new file mode 100644 index 0000000..a5da598 --- /dev/null +++ b/sdk/python/timr_api/api/drive_log_category_api.py @@ -0,0 +1,628 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.drive_log_categories_page import DriveLogCategoriesPage +from timr_api.models.drive_log_category import DriveLogCategory + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class DriveLogCategoryApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def fetch_drive_log_categories( + self, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DriveLogCategoriesPage: + """List Drive Log Categories + + Lists the Drive Log Categories the authenticated user or API token can access. + + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DriveLogCategoriesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_drive_log_categories_serialize( + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLogCategoriesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_drive_log_categories_with_http_info( + self, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DriveLogCategoriesPage]: + """List Drive Log Categories + + Lists the Drive Log Categories the authenticated user or API token can access. + + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DriveLogCategoriesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_drive_log_categories_serialize( + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLogCategoriesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_drive_log_categories_without_preload_content( + self, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Drive Log Categories + + Lists the Drive Log Categories the authenticated user or API token can access. + + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DriveLogCategoriesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_drive_log_categories_serialize( + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLogCategoriesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_drive_log_categories_serialize( + self, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/drive-log-categories', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_drive_log_category( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log Category.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DriveLogCategory: + """Get a Drive Log Category + + Returns a single Drive Log Category by its ID. + + :param id: ID of the Drive Log Category. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_drive_log_category_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLogCategory", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_drive_log_category_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log Category.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DriveLogCategory]: + """Get a Drive Log Category + + Returns a single Drive Log Category by its ID. + + :param id: ID of the Drive Log Category. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_drive_log_category_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLogCategory", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_drive_log_category_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Drive Log Category.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Drive Log Category + + Returns a single Drive Log Category by its ID. + + :param id: ID of the Drive Log Category. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_drive_log_category_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DriveLogCategory", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_drive_log_category_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/drive-log-categories/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/holiday_calendar_api.py b/sdk/python/timr_api/api/holiday_calendar_api.py new file mode 100644 index 0000000..112506e --- /dev/null +++ b/sdk/python/timr_api/api/holiday_calendar_api.py @@ -0,0 +1,969 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.holiday_calendar_partial import HolidayCalendarPartial +from timr_api.models.holiday_calendars_page import HolidayCalendarsPage +from timr_api.models.holidays_page import HolidaysPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class HolidayCalendarApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def fetch_holiday_calendars( + self, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> HolidayCalendarsPage: + """List Holiday Calendars + + Lists the Holiday Calendars the authenticated user or API token can access. + + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: HolidayCalendarsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_holiday_calendars_serialize( + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HolidayCalendarsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_holiday_calendars_with_http_info( + self, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[HolidayCalendarsPage]: + """List Holiday Calendars + + Lists the Holiday Calendars the authenticated user or API token can access. + + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: HolidayCalendarsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_holiday_calendars_serialize( + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HolidayCalendarsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_holiday_calendars_without_preload_content( + self, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Holiday Calendars + + Lists the Holiday Calendars the authenticated user or API token can access. + + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: HolidayCalendarsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_holiday_calendars_serialize( + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HolidayCalendarsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_holiday_calendars_serialize( + self, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/holiday-calendars', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_holidays( + self, + id: Annotated[StrictStr, Field(description="ID of the Holiday Calendar.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> HolidaysPage: + """List Holidays + + Lists the Holidays in the Holiday Calendar. + + :param id: ID of the Holiday Calendar. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: HolidaysSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_holidays_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HolidaysPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_holidays_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Holiday Calendar.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[HolidaysPage]: + """List Holidays + + Lists the Holidays in the Holiday Calendar. + + :param id: ID of the Holiday Calendar. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: HolidaysSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_holidays_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HolidaysPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_holidays_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Holiday Calendar.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Holidays + + Lists the Holidays in the Holiday Calendar. + + :param id: ID of the Holiday Calendar. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: HolidaysSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_holidays_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HolidaysPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_holidays_serialize( + self, + id, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/holiday-calendars/{id}/holidays', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_holiday_calendar( + self, + id: Annotated[StrictStr, Field(description="ID of the Holiday Calendar.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> HolidayCalendarPartial: + """Get a Holiday Calendar + + Returns a single Holiday Calendar by its ID. + + :param id: ID of the Holiday Calendar. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_holiday_calendar_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HolidayCalendarPartial", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_holiday_calendar_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Holiday Calendar.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[HolidayCalendarPartial]: + """Get a Holiday Calendar + + Returns a single Holiday Calendar by its ID. + + :param id: ID of the Holiday Calendar. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_holiday_calendar_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HolidayCalendarPartial", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_holiday_calendar_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Holiday Calendar.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Holiday Calendar + + Returns a single Holiday Calendar by its ID. + + :param id: ID of the Holiday Calendar. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_holiday_calendar_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HolidayCalendarPartial", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_holiday_calendar_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/holiday-calendars/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/project_time_api.py b/sdk/python/timr_api/api/project_time_api.py new file mode 100644 index 0000000..dcf7453 --- /dev/null +++ b/sdk/python/timr_api/api/project_time_api.py @@ -0,0 +1,2039 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from datetime import date, datetime +from pydantic import Field, StrictBool, StrictStr +from typing import Any, List, Optional +from typing_extensions import Annotated +from timr_api.models.deleted_entry_with_metadata_page import DeletedEntryWithMetadataPage +from timr_api.models.project_time import ProjectTime +from timr_api.models.project_time_create import ProjectTimeCreate +from timr_api.models.project_time_status import ProjectTimeStatus +from timr_api.models.project_time_update import ProjectTimeUpdate +from timr_api.models.project_times_page import ProjectTimesPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class ProjectTimeApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_project_time( + self, + project_time_create: Annotated[ProjectTimeCreate, Field(description="Project Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ProjectTime: + """Create a Project Time + + Creates a Project Time from the data in the request body. + + :param project_time_create: Project Time entity (required) + :type project_time_create: ProjectTimeCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_project_time_serialize( + project_time_create=project_time_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "ProjectTime", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_project_time_with_http_info( + self, + project_time_create: Annotated[ProjectTimeCreate, Field(description="Project Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ProjectTime]: + """Create a Project Time + + Creates a Project Time from the data in the request body. + + :param project_time_create: Project Time entity (required) + :type project_time_create: ProjectTimeCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_project_time_serialize( + project_time_create=project_time_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "ProjectTime", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_project_time_without_preload_content( + self, + project_time_create: Annotated[ProjectTimeCreate, Field(description="Project Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Project Time + + Creates a Project Time from the data in the request body. + + :param project_time_create: Project Time entity (required) + :type project_time_create: ProjectTimeCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_project_time_serialize( + project_time_create=project_time_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "ProjectTime", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_project_time_serialize( + self, + project_time_create, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if project_time_create is not None: + _body_params = project_time_create + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/project-times', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def delete_project_time( + self, + id: Annotated[StrictStr, Field(description="ID of the Project Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Project Time + + Deletes the Project Time. + + :param id: ID of the Project Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_project_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_project_time_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Project Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Project Time + + Deletes the Project Time. + + :param id: ID of the Project Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_project_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_project_time_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Project Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Project Time + + Deletes the Project Time. + + :param id: ID of the Project Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_project_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_project_time_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/project-times/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_deleted_project_times( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DeletedEntryWithMetadataPage: + """List deleted Project Times + + Lists Project Times that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_project_times_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryWithMetadataPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_deleted_project_times_with_http_info( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DeletedEntryWithMetadataPage]: + """List deleted Project Times + + Lists Project Times that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_project_times_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryWithMetadataPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_deleted_project_times_without_preload_content( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List deleted Project Times + + Lists Project Times that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_project_times_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryWithMetadataPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_deleted_project_times_serialize( + self, + last_modified_after, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if last_modified_after is not None: + if isinstance(last_modified_after, datetime): + _query_params.append( + ( + 'last_modified_after', + last_modified_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('last_modified_after', last_modified_after)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/project-times:deleted', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_project_times( + self, + notes: Annotated[Optional[StrictStr], Field(description="Only return entries whose notes contain this text.")] = None, + start_from: Annotated[Optional[date], Field(description="Only return entries starting on or after this day.")] = None, + start_to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + task: Annotated[Optional[StrictStr], Field(description="Only return entries recorded on the Task with this ID.")] = None, + traverse_task_tree: Annotated[Optional[StrictBool], Field(description="Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false).")] = None, + billable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + statuses: Annotated[Optional[List[ProjectTimeStatus]], Field(description="Only return entries in one of these statuses.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + changed: Annotated[Optional[StrictBool], Field(description="Only return entries that were changed by the user (true) or left unchanged (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ProjectTimesPage: + """List Project Times + + Lists the Project Times the authenticated user or API token can access. + + :param notes: Only return entries whose notes contain this text. + :type notes: str + :param start_from: Only return entries starting on or after this day. + :type start_from: date + :param start_to: Only return entries starting on or before this day. + :type start_to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param task: Only return entries recorded on the Task with this ID. + :type task: str + :param traverse_task_tree: Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). + :type traverse_task_tree: bool + :param billable: Only return entries that are billable (true) or not billable (false). + :type billable: bool + :param statuses: Only return entries in one of these statuses. + :type statuses: List[ProjectTimeStatus] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param changed: Only return entries that were changed by the user (true) or left unchanged (false). + :type changed: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: ProjectTimesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_project_times_serialize( + notes=notes, + start_from=start_from, + start_to=start_to, + last_modified_after=last_modified_after, + task=task, + traverse_task_tree=traverse_task_tree, + billable=billable, + statuses=statuses, + users=users, + changed=changed, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ProjectTimesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_project_times_with_http_info( + self, + notes: Annotated[Optional[StrictStr], Field(description="Only return entries whose notes contain this text.")] = None, + start_from: Annotated[Optional[date], Field(description="Only return entries starting on or after this day.")] = None, + start_to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + task: Annotated[Optional[StrictStr], Field(description="Only return entries recorded on the Task with this ID.")] = None, + traverse_task_tree: Annotated[Optional[StrictBool], Field(description="Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false).")] = None, + billable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + statuses: Annotated[Optional[List[ProjectTimeStatus]], Field(description="Only return entries in one of these statuses.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + changed: Annotated[Optional[StrictBool], Field(description="Only return entries that were changed by the user (true) or left unchanged (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ProjectTimesPage]: + """List Project Times + + Lists the Project Times the authenticated user or API token can access. + + :param notes: Only return entries whose notes contain this text. + :type notes: str + :param start_from: Only return entries starting on or after this day. + :type start_from: date + :param start_to: Only return entries starting on or before this day. + :type start_to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param task: Only return entries recorded on the Task with this ID. + :type task: str + :param traverse_task_tree: Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). + :type traverse_task_tree: bool + :param billable: Only return entries that are billable (true) or not billable (false). + :type billable: bool + :param statuses: Only return entries in one of these statuses. + :type statuses: List[ProjectTimeStatus] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param changed: Only return entries that were changed by the user (true) or left unchanged (false). + :type changed: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: ProjectTimesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_project_times_serialize( + notes=notes, + start_from=start_from, + start_to=start_to, + last_modified_after=last_modified_after, + task=task, + traverse_task_tree=traverse_task_tree, + billable=billable, + statuses=statuses, + users=users, + changed=changed, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ProjectTimesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_project_times_without_preload_content( + self, + notes: Annotated[Optional[StrictStr], Field(description="Only return entries whose notes contain this text.")] = None, + start_from: Annotated[Optional[date], Field(description="Only return entries starting on or after this day.")] = None, + start_to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + task: Annotated[Optional[StrictStr], Field(description="Only return entries recorded on the Task with this ID.")] = None, + traverse_task_tree: Annotated[Optional[StrictBool], Field(description="Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false).")] = None, + billable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + statuses: Annotated[Optional[List[ProjectTimeStatus]], Field(description="Only return entries in one of these statuses.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + changed: Annotated[Optional[StrictBool], Field(description="Only return entries that were changed by the user (true) or left unchanged (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Project Times + + Lists the Project Times the authenticated user or API token can access. + + :param notes: Only return entries whose notes contain this text. + :type notes: str + :param start_from: Only return entries starting on or after this day. + :type start_from: date + :param start_to: Only return entries starting on or before this day. + :type start_to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param task: Only return entries recorded on the Task with this ID. + :type task: str + :param traverse_task_tree: Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). + :type traverse_task_tree: bool + :param billable: Only return entries that are billable (true) or not billable (false). + :type billable: bool + :param statuses: Only return entries in one of these statuses. + :type statuses: List[ProjectTimeStatus] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param changed: Only return entries that were changed by the user (true) or left unchanged (false). + :type changed: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: ProjectTimesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_project_times_serialize( + notes=notes, + start_from=start_from, + start_to=start_to, + last_modified_after=last_modified_after, + task=task, + traverse_task_tree=traverse_task_tree, + billable=billable, + statuses=statuses, + users=users, + changed=changed, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ProjectTimesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_project_times_serialize( + self, + notes, + start_from, + start_to, + last_modified_after, + task, + traverse_task_tree, + billable, + statuses, + users, + changed, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'statuses': 'multi', + 'users': 'multi', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if notes is not None: + + _query_params.append(('notes', notes)) + + if start_from is not None: + if isinstance(start_from, date): + _query_params.append( + ( + 'start_from', + start_from.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('start_from', start_from)) + + if start_to is not None: + if isinstance(start_to, date): + _query_params.append( + ( + 'start_to', + start_to.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('start_to', start_to)) + + if last_modified_after is not None: + if isinstance(last_modified_after, datetime): + _query_params.append( + ( + 'last_modified_after', + last_modified_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('last_modified_after', last_modified_after)) + + if task is not None: + + _query_params.append(('task', task)) + + if traverse_task_tree is not None: + + _query_params.append(('traverse_task_tree', traverse_task_tree)) + + if billable is not None: + + _query_params.append(('billable', billable)) + + if statuses is not None: + + _query_params.append(('statuses', statuses)) + + if users is not None: + + _query_params.append(('users', users)) + + if changed is not None: + + _query_params.append(('changed', changed)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/project-times', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_project_time( + self, + id: Annotated[StrictStr, Field(description="ID of the Project Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ProjectTime: + """Get a Project Time + + Returns a single Project Time by its ID. + + :param id: ID of the Project Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_project_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ProjectTime", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_project_time_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Project Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ProjectTime]: + """Get a Project Time + + Returns a single Project Time by its ID. + + :param id: ID of the Project Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_project_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ProjectTime", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_project_time_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Project Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Project Time + + Returns a single Project Time by its ID. + + :param id: ID of the Project Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_project_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ProjectTime", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_project_time_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/project-times/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def update_project_time( + self, + id: Annotated[StrictStr, Field(description="ID of the Project Time.")], + project_time_update: Annotated[ProjectTimeUpdate, Field(description="Project Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ProjectTime: + """Update a Project Time + + Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Project Time. (required) + :type id: str + :param project_time_update: Project Time entity (required) + :type project_time_update: ProjectTimeUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_project_time_serialize( + id=id, + project_time_update=project_time_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ProjectTime", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def update_project_time_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Project Time.")], + project_time_update: Annotated[ProjectTimeUpdate, Field(description="Project Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ProjectTime]: + """Update a Project Time + + Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Project Time. (required) + :type id: str + :param project_time_update: Project Time entity (required) + :type project_time_update: ProjectTimeUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_project_time_serialize( + id=id, + project_time_update=project_time_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ProjectTime", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_project_time_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Project Time.")], + project_time_update: Annotated[ProjectTimeUpdate, Field(description="Project Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update a Project Time + + Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Project Time. (required) + :type id: str + :param project_time_update: Project Time entity (required) + :type project_time_update: ProjectTimeUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_project_time_serialize( + id=id, + project_time_update=project_time_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ProjectTime", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _update_project_time_serialize( + self, + id, + project_time_update, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if project_time_update is not None: + _body_params = project_time_update + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/project-times/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/task_api.py b/sdk/python/timr_api/api/task_api.py new file mode 100644 index 0000000..36b51e6 --- /dev/null +++ b/sdk/python/timr_api/api/task_api.py @@ -0,0 +1,1760 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictBool, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.task import Task +from timr_api.models.task_create import TaskCreate +from timr_api.models.task_update import TaskUpdate +from timr_api.models.tasks_page import TasksPage +from timr_api.models.tasks_reduced_page import TasksReducedPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class TaskApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_task( + self, + task_create: Annotated[TaskCreate, Field(description="Project Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Task: + """Create a Task + + Creates a Task from the data in the request body. + + :param task_create: Project Time entity (required) + :type task_create: TaskCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_task_serialize( + task_create=task_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Task", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_task_with_http_info( + self, + task_create: Annotated[TaskCreate, Field(description="Project Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Task]: + """Create a Task + + Creates a Task from the data in the request body. + + :param task_create: Project Time entity (required) + :type task_create: TaskCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_task_serialize( + task_create=task_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Task", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_task_without_preload_content( + self, + task_create: Annotated[TaskCreate, Field(description="Project Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Task + + Creates a Task from the data in the request body. + + :param task_create: Project Time entity (required) + :type task_create: TaskCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_task_serialize( + task_create=task_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Task", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_task_serialize( + self, + task_create, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if task_create is not None: + _body_params = task_create + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/tasks', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_tasks( + self, + parent_task_id: Annotated[Optional[StrictStr], Field(description="Only return Tasks whose parent is the Task with this ID.")] = None, + traverse_task_tree: Annotated[Optional[StrictBool], Field(description="Include Tasks from the whole subtree (true) or only direct children (false).")] = None, + name: Annotated[Optional[StrictStr], Field(description="Only return Users whose name contains this text.")] = None, + bookable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + billable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + active_at: Annotated[Optional[Any], Field(description="Only return Tasks that are active on this day.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TasksPage: + """List Tasks + + Lists the Tasks the authenticated user or API token can access. + + :param parent_task_id: Only return Tasks whose parent is the Task with this ID. + :type parent_task_id: str + :param traverse_task_tree: Include Tasks from the whole subtree (true) or only direct children (false). + :type traverse_task_tree: bool + :param name: Only return Users whose name contains this text. + :type name: str + :param bookable: Only return entries that are billable (true) or not billable (false). + :type bookable: bool + :param billable: Only return entries that are billable (true) or not billable (false). + :type billable: bool + :param active_at: Only return Tasks that are active on this day. + :type active_at: date + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TasksSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_tasks_serialize( + parent_task_id=parent_task_id, + traverse_task_tree=traverse_task_tree, + name=name, + bookable=bookable, + billable=billable, + active_at=active_at, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TasksPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_tasks_with_http_info( + self, + parent_task_id: Annotated[Optional[StrictStr], Field(description="Only return Tasks whose parent is the Task with this ID.")] = None, + traverse_task_tree: Annotated[Optional[StrictBool], Field(description="Include Tasks from the whole subtree (true) or only direct children (false).")] = None, + name: Annotated[Optional[StrictStr], Field(description="Only return Users whose name contains this text.")] = None, + bookable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + billable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + active_at: Annotated[Optional[Any], Field(description="Only return Tasks that are active on this day.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TasksPage]: + """List Tasks + + Lists the Tasks the authenticated user or API token can access. + + :param parent_task_id: Only return Tasks whose parent is the Task with this ID. + :type parent_task_id: str + :param traverse_task_tree: Include Tasks from the whole subtree (true) or only direct children (false). + :type traverse_task_tree: bool + :param name: Only return Users whose name contains this text. + :type name: str + :param bookable: Only return entries that are billable (true) or not billable (false). + :type bookable: bool + :param billable: Only return entries that are billable (true) or not billable (false). + :type billable: bool + :param active_at: Only return Tasks that are active on this day. + :type active_at: date + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TasksSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_tasks_serialize( + parent_task_id=parent_task_id, + traverse_task_tree=traverse_task_tree, + name=name, + bookable=bookable, + billable=billable, + active_at=active_at, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TasksPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_tasks_without_preload_content( + self, + parent_task_id: Annotated[Optional[StrictStr], Field(description="Only return Tasks whose parent is the Task with this ID.")] = None, + traverse_task_tree: Annotated[Optional[StrictBool], Field(description="Include Tasks from the whole subtree (true) or only direct children (false).")] = None, + name: Annotated[Optional[StrictStr], Field(description="Only return Users whose name contains this text.")] = None, + bookable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + billable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + active_at: Annotated[Optional[Any], Field(description="Only return Tasks that are active on this day.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Tasks + + Lists the Tasks the authenticated user or API token can access. + + :param parent_task_id: Only return Tasks whose parent is the Task with this ID. + :type parent_task_id: str + :param traverse_task_tree: Include Tasks from the whole subtree (true) or only direct children (false). + :type traverse_task_tree: bool + :param name: Only return Users whose name contains this text. + :type name: str + :param bookable: Only return entries that are billable (true) or not billable (false). + :type bookable: bool + :param billable: Only return entries that are billable (true) or not billable (false). + :type billable: bool + :param active_at: Only return Tasks that are active on this day. + :type active_at: date + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TasksSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_tasks_serialize( + parent_task_id=parent_task_id, + traverse_task_tree=traverse_task_tree, + name=name, + bookable=bookable, + billable=billable, + active_at=active_at, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TasksPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_tasks_serialize( + self, + parent_task_id, + traverse_task_tree, + name, + bookable, + billable, + active_at, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if parent_task_id is not None: + + _query_params.append(('parent_task_id', parent_task_id)) + + if traverse_task_tree is not None: + + _query_params.append(('traverse_task_tree', traverse_task_tree)) + + if name is not None: + + _query_params.append(('name', name)) + + if bookable is not None: + + _query_params.append(('bookable', bookable)) + + if billable is not None: + + _query_params.append(('billable', billable)) + + if active_at is not None: + + _query_params.append(('active_at', active_at)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/tasks', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_user_tasks( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + parent_task_id: Annotated[Optional[StrictStr], Field(description="Only return Tasks whose parent is the Task with this ID.")] = None, + traverse_task_tree: Annotated[Optional[StrictBool], Field(description="Include Tasks from the whole subtree (true) or only direct children (false).")] = None, + name: Annotated[Optional[StrictStr], Field(description="Only return Users whose name contains this text.")] = None, + bookable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + billable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + active_at: Annotated[Optional[Any], Field(description="Only return Tasks that are active on this day.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TasksReducedPage: + """List a User's Tasks + + Lists the Tasks the User is assigned to and may record on. + + :param id: ID of the User. (required) + :type id: str + :param parent_task_id: Only return Tasks whose parent is the Task with this ID. + :type parent_task_id: str + :param traverse_task_tree: Include Tasks from the whole subtree (true) or only direct children (false). + :type traverse_task_tree: bool + :param name: Only return Users whose name contains this text. + :type name: str + :param bookable: Only return entries that are billable (true) or not billable (false). + :type bookable: bool + :param billable: Only return entries that are billable (true) or not billable (false). + :type billable: bool + :param active_at: Only return Tasks that are active on this day. + :type active_at: date + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TasksSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_user_tasks_serialize( + id=id, + parent_task_id=parent_task_id, + traverse_task_tree=traverse_task_tree, + name=name, + bookable=bookable, + billable=billable, + active_at=active_at, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TasksReducedPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_user_tasks_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + parent_task_id: Annotated[Optional[StrictStr], Field(description="Only return Tasks whose parent is the Task with this ID.")] = None, + traverse_task_tree: Annotated[Optional[StrictBool], Field(description="Include Tasks from the whole subtree (true) or only direct children (false).")] = None, + name: Annotated[Optional[StrictStr], Field(description="Only return Users whose name contains this text.")] = None, + bookable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + billable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + active_at: Annotated[Optional[Any], Field(description="Only return Tasks that are active on this day.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TasksReducedPage]: + """List a User's Tasks + + Lists the Tasks the User is assigned to and may record on. + + :param id: ID of the User. (required) + :type id: str + :param parent_task_id: Only return Tasks whose parent is the Task with this ID. + :type parent_task_id: str + :param traverse_task_tree: Include Tasks from the whole subtree (true) or only direct children (false). + :type traverse_task_tree: bool + :param name: Only return Users whose name contains this text. + :type name: str + :param bookable: Only return entries that are billable (true) or not billable (false). + :type bookable: bool + :param billable: Only return entries that are billable (true) or not billable (false). + :type billable: bool + :param active_at: Only return Tasks that are active on this day. + :type active_at: date + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TasksSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_user_tasks_serialize( + id=id, + parent_task_id=parent_task_id, + traverse_task_tree=traverse_task_tree, + name=name, + bookable=bookable, + billable=billable, + active_at=active_at, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TasksReducedPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_user_tasks_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + parent_task_id: Annotated[Optional[StrictStr], Field(description="Only return Tasks whose parent is the Task with this ID.")] = None, + traverse_task_tree: Annotated[Optional[StrictBool], Field(description="Include Tasks from the whole subtree (true) or only direct children (false).")] = None, + name: Annotated[Optional[StrictStr], Field(description="Only return Users whose name contains this text.")] = None, + bookable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + billable: Annotated[Optional[StrictBool], Field(description="Only return entries that are billable (true) or not billable (false).")] = None, + active_at: Annotated[Optional[Any], Field(description="Only return Tasks that are active on this day.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List a User's Tasks + + Lists the Tasks the User is assigned to and may record on. + + :param id: ID of the User. (required) + :type id: str + :param parent_task_id: Only return Tasks whose parent is the Task with this ID. + :type parent_task_id: str + :param traverse_task_tree: Include Tasks from the whole subtree (true) or only direct children (false). + :type traverse_task_tree: bool + :param name: Only return Users whose name contains this text. + :type name: str + :param bookable: Only return entries that are billable (true) or not billable (false). + :type bookable: bool + :param billable: Only return entries that are billable (true) or not billable (false). + :type billable: bool + :param active_at: Only return Tasks that are active on this day. + :type active_at: date + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TasksSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_user_tasks_serialize( + id=id, + parent_task_id=parent_task_id, + traverse_task_tree=traverse_task_tree, + name=name, + bookable=bookable, + billable=billable, + active_at=active_at, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TasksReducedPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_user_tasks_serialize( + self, + id, + parent_task_id, + traverse_task_tree, + name, + bookable, + billable, + active_at, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + if parent_task_id is not None: + + _query_params.append(('parent_task_id', parent_task_id)) + + if traverse_task_tree is not None: + + _query_params.append(('traverse_task_tree', traverse_task_tree)) + + if name is not None: + + _query_params.append(('name', name)) + + if bookable is not None: + + _query_params.append(('bookable', bookable)) + + if billable is not None: + + _query_params.append(('billable', billable)) + + if active_at is not None: + + _query_params.append(('active_at', active_at)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/users/{id}/tasks', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_task( + self, + id: Annotated[StrictStr, Field(description="ID of the Task.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Task: + """Get a Task + + Returns a single Task by its ID. + + :param id: ID of the Task. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Task", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_task_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Task.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Task]: + """Get a Task + + Returns a single Task by its ID. + + :param id: ID of the Task. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Task", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_task_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Task.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Task + + Returns a single Task by its ID. + + :param id: ID of the Task. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Task", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_task_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/tasks/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def update_task( + self, + id: Annotated[StrictStr, Field(description="ID of the Task.")], + task_update: Annotated[TaskUpdate, Field(description="Task entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Task: + """Update a Task + + Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Task. (required) + :type id: str + :param task_update: Task entity (required) + :type task_update: TaskUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_task_serialize( + id=id, + task_update=task_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Task", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def update_task_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Task.")], + task_update: Annotated[TaskUpdate, Field(description="Task entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Task]: + """Update a Task + + Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Task. (required) + :type id: str + :param task_update: Task entity (required) + :type task_update: TaskUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_task_serialize( + id=id, + task_update=task_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Task", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_task_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Task.")], + task_update: Annotated[TaskUpdate, Field(description="Task entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update a Task + + Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Task. (required) + :type id: str + :param task_update: Task entity (required) + :type task_update: TaskUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_task_serialize( + id=id, + task_update=task_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Task", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _update_task_serialize( + self, + id, + task_update, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if task_update is not None: + _body_params = task_update + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/tasks/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/task_to_leader_assignment_api.py b/sdk/python/timr_api/api/task_to_leader_assignment_api.py new file mode 100644 index 0000000..94c0ba3 --- /dev/null +++ b/sdk/python/timr_api/api/task_to_leader_assignment_api.py @@ -0,0 +1,1237 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.task_to_leader_assignment import TaskToLeaderAssignment +from timr_api.models.task_to_leader_assignments_page import TaskToLeaderAssignmentsPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class TaskToLeaderAssignmentApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_task_to_leader_assignment( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TaskToLeaderAssignment: + """Create a Task to Leader Assignment + + Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_task_to_leader_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToLeaderAssignment", + '201': "TaskToLeaderAssignment", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_task_to_leader_assignment_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TaskToLeaderAssignment]: + """Create a Task to Leader Assignment + + Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_task_to_leader_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToLeaderAssignment", + '201': "TaskToLeaderAssignment", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_task_to_leader_assignment_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Task to Leader Assignment + + Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_task_to_leader_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToLeaderAssignment", + '201': "TaskToLeaderAssignment", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_task_to_leader_assignment_serialize( + self, + task_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/tasks/{task_id}/leaders/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def delete_task_to_leader_assignment( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Task to Leader Assignment + + Removes the User's leader assignment to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_to_leader_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_task_to_leader_assignment_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Task to Leader Assignment + + Removes the User's leader assignment to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_to_leader_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_task_to_leader_assignment_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Task to Leader Assignment + + Removes the User's leader assignment to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_to_leader_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_task_to_leader_assignment_serialize( + self, + task_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/tasks/{task_id}/leaders/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_task_to_leader_assignments( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TaskToLeaderAssignmentsPage: + """List Task to Leader Assignments + + Lists the Users assigned to the Task as leaders. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TaskToLeaderAssignmentsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_task_to_leader_assignments_serialize( + task_id=task_id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToLeaderAssignmentsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_task_to_leader_assignments_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TaskToLeaderAssignmentsPage]: + """List Task to Leader Assignments + + Lists the Users assigned to the Task as leaders. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TaskToLeaderAssignmentsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_task_to_leader_assignments_serialize( + task_id=task_id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToLeaderAssignmentsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_task_to_leader_assignments_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Task to Leader Assignments + + Lists the Users assigned to the Task as leaders. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TaskToLeaderAssignmentsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_task_to_leader_assignments_serialize( + task_id=task_id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToLeaderAssignmentsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_task_to_leader_assignments_serialize( + self, + task_id, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/tasks/{task_id}/leaders', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_task_to_leader_assignment( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TaskToLeaderAssignment: + """Get a Task to Leader Assignment + + Returns the leader assignment of a single User to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_to_leader_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToLeaderAssignment", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_task_to_leader_assignment_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TaskToLeaderAssignment]: + """Get a Task to Leader Assignment + + Returns the leader assignment of a single User to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_to_leader_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToLeaderAssignment", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_task_to_leader_assignment_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Task to Leader Assignment + + Returns the leader assignment of a single User to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_to_leader_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToLeaderAssignment", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_task_to_leader_assignment_serialize( + self, + task_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/tasks/{task_id}/leaders/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/task_to_team_assignment_api.py b/sdk/python/timr_api/api/task_to_team_assignment_api.py new file mode 100644 index 0000000..89ff099 --- /dev/null +++ b/sdk/python/timr_api/api/task_to_team_assignment_api.py @@ -0,0 +1,1237 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.task_to_team_assignment import TaskToTeamAssignment +from timr_api.models.task_to_team_assignments_page import TaskToTeamAssignmentsPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class TaskToTeamAssignmentApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_task_to_team_assignment( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TaskToTeamAssignment: + """Create a Task to Team Assignment + + Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param team_id: ID of the Team. (required) + :type team_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_task_to_team_assignment_serialize( + task_id=task_id, + team_id=team_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToTeamAssignment", + '201': "TaskToTeamAssignment", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_task_to_team_assignment_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TaskToTeamAssignment]: + """Create a Task to Team Assignment + + Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param team_id: ID of the Team. (required) + :type team_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_task_to_team_assignment_serialize( + task_id=task_id, + team_id=team_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToTeamAssignment", + '201': "TaskToTeamAssignment", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_task_to_team_assignment_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Task to Team Assignment + + Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param team_id: ID of the Team. (required) + :type team_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_task_to_team_assignment_serialize( + task_id=task_id, + team_id=team_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToTeamAssignment", + '201': "TaskToTeamAssignment", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_task_to_team_assignment_serialize( + self, + task_id, + team_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + if team_id is not None: + _path_params['team_id'] = team_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/tasks/{task_id}/teams/{team_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def delete_task_to_team_assignment( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Task to Team Assignment + + Removes the Team's assignment to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param team_id: ID of the Team. (required) + :type team_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_to_team_assignment_serialize( + task_id=task_id, + team_id=team_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_task_to_team_assignment_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Task to Team Assignment + + Removes the Team's assignment to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param team_id: ID of the Team. (required) + :type team_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_to_team_assignment_serialize( + task_id=task_id, + team_id=team_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_task_to_team_assignment_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Task to Team Assignment + + Removes the Team's assignment to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param team_id: ID of the Team. (required) + :type team_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_to_team_assignment_serialize( + task_id=task_id, + team_id=team_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_task_to_team_assignment_serialize( + self, + task_id, + team_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + if team_id is not None: + _path_params['team_id'] = team_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/tasks/{task_id}/teams/{team_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_task_to_team_assignments( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TaskToTeamAssignmentsPage: + """List Task to Team Assignments + + Lists the Teams assigned to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TaskToTeamAssignmentsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_task_to_team_assignments_serialize( + task_id=task_id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToTeamAssignmentsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_task_to_team_assignments_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TaskToTeamAssignmentsPage]: + """List Task to Team Assignments + + Lists the Teams assigned to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TaskToTeamAssignmentsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_task_to_team_assignments_serialize( + task_id=task_id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToTeamAssignmentsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_task_to_team_assignments_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Task to Team Assignments + + Lists the Teams assigned to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TaskToTeamAssignmentsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_task_to_team_assignments_serialize( + task_id=task_id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToTeamAssignmentsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_task_to_team_assignments_serialize( + self, + task_id, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/tasks/{task_id}/teams', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_task_to_team_assignment( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TaskToTeamAssignment: + """Get a Task to Team Assignment + + Returns the assignment of a single Team to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param team_id: ID of the Team. (required) + :type team_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_to_team_assignment_serialize( + task_id=task_id, + team_id=team_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToTeamAssignment", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_task_to_team_assignment_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TaskToTeamAssignment]: + """Get a Task to Team Assignment + + Returns the assignment of a single Team to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param team_id: ID of the Team. (required) + :type team_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_to_team_assignment_serialize( + task_id=task_id, + team_id=team_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToTeamAssignment", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_task_to_team_assignment_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Task to Team Assignment + + Returns the assignment of a single Team to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param team_id: ID of the Team. (required) + :type team_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_to_team_assignment_serialize( + task_id=task_id, + team_id=team_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToTeamAssignment", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_task_to_team_assignment_serialize( + self, + task_id, + team_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + if team_id is not None: + _path_params['team_id'] = team_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/tasks/{task_id}/teams/{team_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/task_to_user_assignment_api.py b/sdk/python/timr_api/api/task_to_user_assignment_api.py new file mode 100644 index 0000000..2e7bce1 --- /dev/null +++ b/sdk/python/timr_api/api/task_to_user_assignment_api.py @@ -0,0 +1,1266 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.task_to_user_assignment import TaskToUserAssignment +from timr_api.models.task_to_user_assignment_upsert import TaskToUserAssignmentUpsert +from timr_api.models.task_to_user_assignments_page import TaskToUserAssignmentsPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class TaskToUserAssignmentApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def delete_task_to_user_assignment( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Task to User Assignment + + Removes the User's assignment to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_to_user_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_task_to_user_assignment_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Task to User Assignment + + Removes the User's assignment to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_to_user_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_task_to_user_assignment_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Task to User Assignment + + Removes the User's assignment to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_to_user_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_task_to_user_assignment_serialize( + self, + task_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/tasks/{task_id}/users/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_task_to_user_assignments( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TaskToUserAssignmentsPage: + """List Task to User Assignments + + Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TaskToUserAssignmentsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_task_to_user_assignments_serialize( + task_id=task_id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToUserAssignmentsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_task_to_user_assignments_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TaskToUserAssignmentsPage]: + """List Task to User Assignments + + Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TaskToUserAssignmentsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_task_to_user_assignments_serialize( + task_id=task_id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToUserAssignmentsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_task_to_user_assignments_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Task to User Assignments + + Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TaskToUserAssignmentsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_task_to_user_assignments_serialize( + task_id=task_id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToUserAssignmentsPage", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_task_to_user_assignments_serialize( + self, + task_id, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/tasks/{task_id}/users', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_task_to_user_assignment( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TaskToUserAssignment: + """Get a Task to User Assignment + + Returns the assignment of a single User to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_to_user_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToUserAssignment", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_task_to_user_assignment_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TaskToUserAssignment]: + """Get a Task to User Assignment + + Returns the assignment of a single User to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_to_user_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToUserAssignment", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_task_to_user_assignment_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Task to User Assignment + + Returns the assignment of a single User to the Task. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_task_to_user_assignment_serialize( + task_id=task_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToUserAssignment", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_task_to_user_assignment_serialize( + self, + task_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/tasks/{task_id}/users/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def upsert_task_to_user_assignment( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + task_to_user_assignment_upsert: Annotated[TaskToUserAssignmentUpsert, Field(description="Task to User Assignment entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TaskToUserAssignment: + """Create or update a Task to User Assignment + + Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param task_to_user_assignment_upsert: Task to User Assignment entity (required) + :type task_to_user_assignment_upsert: TaskToUserAssignmentUpsert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upsert_task_to_user_assignment_serialize( + task_id=task_id, + user_id=user_id, + task_to_user_assignment_upsert=task_to_user_assignment_upsert, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToUserAssignment", + '201': "TaskToUserAssignment", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def upsert_task_to_user_assignment_with_http_info( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + task_to_user_assignment_upsert: Annotated[TaskToUserAssignmentUpsert, Field(description="Task to User Assignment entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TaskToUserAssignment]: + """Create or update a Task to User Assignment + + Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param task_to_user_assignment_upsert: Task to User Assignment entity (required) + :type task_to_user_assignment_upsert: TaskToUserAssignmentUpsert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upsert_task_to_user_assignment_serialize( + task_id=task_id, + user_id=user_id, + task_to_user_assignment_upsert=task_to_user_assignment_upsert, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToUserAssignment", + '201': "TaskToUserAssignment", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def upsert_task_to_user_assignment_without_preload_content( + self, + task_id: Annotated[StrictStr, Field(description="ID of the Task.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + task_to_user_assignment_upsert: Annotated[TaskToUserAssignmentUpsert, Field(description="Task to User Assignment entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create or update a Task to User Assignment + + Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + + :param task_id: ID of the Task. (required) + :type task_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param task_to_user_assignment_upsert: Task to User Assignment entity (required) + :type task_to_user_assignment_upsert: TaskToUserAssignmentUpsert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upsert_task_to_user_assignment_serialize( + task_id=task_id, + user_id=user_id, + task_to_user_assignment_upsert=task_to_user_assignment_upsert, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TaskToUserAssignment", + '201': "TaskToUserAssignment", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _upsert_task_to_user_assignment_serialize( + self, + task_id, + user_id, + task_to_user_assignment_upsert, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if task_id is not None: + _path_params['task_id'] = task_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if task_to_user_assignment_upsert is not None: + _body_params = task_to_user_assignment_upsert + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/tasks/{task_id}/users/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/team_api.py b/sdk/python/timr_api/api/team_api.py new file mode 100644 index 0000000..3f19bcc --- /dev/null +++ b/sdk/python/timr_api/api/team_api.py @@ -0,0 +1,3899 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.team import Team +from timr_api.models.team_create import TeamCreate +from timr_api.models.team_update import TeamUpdate +from timr_api.models.teams_page import TeamsPage +from timr_api.models.user_partial import UserPartial +from timr_api.models.users_partial_page import UsersPartialPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class TeamApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def add_team_leader( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> UserPartial: + """Add a Team Leader + + Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._add_team_leader_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '201': "UserPartial", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def add_team_leader_with_http_info( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[UserPartial]: + """Add a Team Leader + + Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._add_team_leader_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '201': "UserPartial", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def add_team_leader_without_preload_content( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Add a Team Leader + + Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._add_team_leader_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '201': "UserPartial", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _add_team_leader_serialize( + self, + team_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if team_id is not None: + _path_params['team_id'] = team_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/teams/{team_id}/leaders/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def add_team_member( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> UserPartial: + """Add a Team Member + + Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._add_team_member_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '201': "UserPartial", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def add_team_member_with_http_info( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[UserPartial]: + """Add a Team Member + + Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._add_team_member_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '201': "UserPartial", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def add_team_member_without_preload_content( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Add a Team Member + + Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._add_team_member_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '201': "UserPartial", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _add_team_member_serialize( + self, + team_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if team_id is not None: + _path_params['team_id'] = team_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/teams/{team_id}/members/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def create_team( + self, + team_create: Annotated[TeamCreate, Field(description="Team entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Team: + """Create a Team + + Creates a Team from the data in the request body. + + :param team_create: Team entity (required) + :type team_create: TeamCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_team_serialize( + team_create=team_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Team", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_team_with_http_info( + self, + team_create: Annotated[TeamCreate, Field(description="Team entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Team]: + """Create a Team + + Creates a Team from the data in the request body. + + :param team_create: Team entity (required) + :type team_create: TeamCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_team_serialize( + team_create=team_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Team", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_team_without_preload_content( + self, + team_create: Annotated[TeamCreate, Field(description="Team entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Team + + Creates a Team from the data in the request body. + + :param team_create: Team entity (required) + :type team_create: TeamCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_team_serialize( + team_create=team_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Team", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_team_serialize( + self, + team_create, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if team_create is not None: + _body_params = team_create + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/teams', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def delete_team( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Team + + Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + + :param id: ID of the Team. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_team_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_team_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Team + + Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + + :param id: ID of the Team. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_team_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_team_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Team + + Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + + :param id: ID of the Team. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_team_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_team_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/teams/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_team_leaders( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> UsersPartialPage: + """List Team Leaders + + Lists the Users who lead the Team. + + :param id: ID of the Team. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: UsersSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_team_leaders_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UsersPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_team_leaders_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[UsersPartialPage]: + """List Team Leaders + + Lists the Users who lead the Team. + + :param id: ID of the Team. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: UsersSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_team_leaders_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UsersPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_team_leaders_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Team Leaders + + Lists the Users who lead the Team. + + :param id: ID of the Team. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: UsersSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_team_leaders_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UsersPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_team_leaders_serialize( + self, + id, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/teams/{id}/leaders', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_team_members( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> UsersPartialPage: + """List Team Members + + Lists the Users who are members of the Team. + + :param id: ID of the Team. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: UsersSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_team_members_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UsersPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_team_members_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[UsersPartialPage]: + """List Team Members + + Lists the Users who are members of the Team. + + :param id: ID of the Team. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: UsersSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_team_members_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UsersPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_team_members_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Team Members + + Lists the Users who are members of the Team. + + :param id: ID of the Team. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: UsersSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_team_members_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UsersPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_team_members_serialize( + self, + id, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/teams/{id}/members', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_teams( + self, + name: Annotated[Optional[StrictStr], Field(description="Only return Teams whose name matches this value in any segment of the breadcrumbs path.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TeamsPage: + """List Teams + + Lists the Teams the authenticated user or API token can access. + + :param name: Only return Teams whose name matches this value in any segment of the breadcrumbs path. + :type name: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TeamsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_teams_serialize( + name=name, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TeamsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_teams_with_http_info( + self, + name: Annotated[Optional[StrictStr], Field(description="Only return Teams whose name matches this value in any segment of the breadcrumbs path.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TeamsPage]: + """List Teams + + Lists the Teams the authenticated user or API token can access. + + :param name: Only return Teams whose name matches this value in any segment of the breadcrumbs path. + :type name: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TeamsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_teams_serialize( + name=name, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TeamsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_teams_without_preload_content( + self, + name: Annotated[Optional[StrictStr], Field(description="Only return Teams whose name matches this value in any segment of the breadcrumbs path.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Teams + + Lists the Teams the authenticated user or API token can access. + + :param name: Only return Teams whose name matches this value in any segment of the breadcrumbs path. + :type name: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TeamsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_teams_serialize( + name=name, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TeamsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_teams_serialize( + self, + name, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if name is not None: + + _query_params.append(('name', name)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/teams', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_team( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Team: + """Get a Team + + Returns a single Team by its ID. + + :param id: ID of the Team. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_team_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Team", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_team_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Team]: + """Get a Team + + Returns a single Team by its ID. + + :param id: ID of the Team. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_team_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Team", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_team_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Team + + Returns a single Team by its ID. + + :param id: ID of the Team. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_team_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Team", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_team_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/teams/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_team_leader( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> UserPartial: + """Get a Team Leader + + Returns the leadership of a single User in the Team. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_team_leader_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_team_leader_with_http_info( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[UserPartial]: + """Get a Team Leader + + Returns the leadership of a single User in the Team. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_team_leader_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_team_leader_without_preload_content( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Team Leader + + Returns the leadership of a single User in the Team. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_team_leader_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_team_leader_serialize( + self, + team_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if team_id is not None: + _path_params['team_id'] = team_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/teams/{team_id}/leaders/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_team_member( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> UserPartial: + """Get a Team Member + + Returns the membership of a single User in the Team. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_team_member_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_team_member_with_http_info( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[UserPartial]: + """Get a Team Member + + Returns the membership of a single User in the Team. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_team_member_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_team_member_without_preload_content( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Team Member + + Returns the membership of a single User in the Team. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_team_member_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UserPartial", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_team_member_serialize( + self, + team_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if team_id is not None: + _path_params['team_id'] = team_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/teams/{team_id}/members/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def remove_team_leader( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Remove a Team Leader + + Removes the User's leadership of the Team. The User itself is not deleted. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._remove_team_leader_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def remove_team_leader_with_http_info( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Remove a Team Leader + + Removes the User's leadership of the Team. The User itself is not deleted. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._remove_team_leader_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def remove_team_leader_without_preload_content( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Remove a Team Leader + + Removes the User's leadership of the Team. The User itself is not deleted. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._remove_team_leader_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _remove_team_leader_serialize( + self, + team_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if team_id is not None: + _path_params['team_id'] = team_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/teams/{team_id}/leaders/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def remove_team_member( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Remove a Team Member + + Removes the User's membership in the Team. The User itself is not deleted. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._remove_team_member_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def remove_team_member_with_http_info( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Remove a Team Member + + Removes the User's membership in the Team. The User itself is not deleted. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._remove_team_member_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def remove_team_member_without_preload_content( + self, + team_id: Annotated[StrictStr, Field(description="ID of the Team.")], + user_id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Remove a Team Member + + Removes the User's membership in the Team. The User itself is not deleted. + + :param team_id: ID of the Team. (required) + :type team_id: str + :param user_id: ID of the User. (required) + :type user_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._remove_team_member_serialize( + team_id=team_id, + user_id=user_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _remove_team_member_serialize( + self, + team_id, + user_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if team_id is not None: + _path_params['team_id'] = team_id + if user_id is not None: + _path_params['user_id'] = user_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/teams/{team_id}/members/{user_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def update_team( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + team_update: Annotated[TeamUpdate, Field(description="Team entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Team: + """Update a Team + + Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Team. (required) + :type id: str + :param team_update: Team entity (required) + :type team_update: TeamUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_team_serialize( + id=id, + team_update=team_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Team", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def update_team_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + team_update: Annotated[TeamUpdate, Field(description="Team entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Team]: + """Update a Team + + Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Team. (required) + :type id: str + :param team_update: Team entity (required) + :type team_update: TeamUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_team_serialize( + id=id, + team_update=team_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Team", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_team_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Team.")], + team_update: Annotated[TeamUpdate, Field(description="Team entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update a Team + + Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Team. (required) + :type id: str + :param team_update: Team entity (required) + :type team_update: TeamUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_team_serialize( + id=id, + team_update=team_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Team", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _update_team_serialize( + self, + id, + team_update, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if team_update is not None: + _body_params = team_update + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/teams/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/time_account_api.py b/sdk/python/timr_api/api/time_account_api.py new file mode 100644 index 0000000..d18b1f9 --- /dev/null +++ b/sdk/python/timr_api/api/time_account_api.py @@ -0,0 +1,607 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from datetime import date +from pydantic import Field, StrictStr +from typing_extensions import Annotated +from timr_api.models.accounts import Accounts + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class TimeAccountApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def get_user_accounts( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + var_date: Annotated[date, Field(description="Day to return the balances for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Accounts: + """Get a User's accounts + + Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + + :param id: ID of the User. (required) + :type id: str + :param var_date: Day to return the balances for. (required) + :type var_date: date + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_accounts_serialize( + id=id, + var_date=var_date, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Accounts", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_user_accounts_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + var_date: Annotated[date, Field(description="Day to return the balances for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Accounts]: + """Get a User's accounts + + Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + + :param id: ID of the User. (required) + :type id: str + :param var_date: Day to return the balances for. (required) + :type var_date: date + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_accounts_serialize( + id=id, + var_date=var_date, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Accounts", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_user_accounts_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + var_date: Annotated[date, Field(description="Day to return the balances for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a User's accounts + + Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + + :param id: ID of the User. (required) + :type id: str + :param var_date: Day to return the balances for. (required) + :type var_date: date + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_accounts_serialize( + id=id, + var_date=var_date, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Accounts", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_user_accounts_serialize( + self, + id, + var_date, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + if var_date is not None: + _path_params['date'] = var_date + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/users/{id}/accounts/{date}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_user_working_time_accounts( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + var_date: Annotated[date, Field(description="Day to return the balances for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Accounts: + """Get a User's working time accounts + + Returns the User's working time account balances as of the given day. + + :param id: ID of the User. (required) + :type id: str + :param var_date: Day to return the balances for. (required) + :type var_date: date + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_working_time_accounts_serialize( + id=id, + var_date=var_date, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Accounts", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_user_working_time_accounts_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + var_date: Annotated[date, Field(description="Day to return the balances for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Accounts]: + """Get a User's working time accounts + + Returns the User's working time account balances as of the given day. + + :param id: ID of the User. (required) + :type id: str + :param var_date: Day to return the balances for. (required) + :type var_date: date + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_working_time_accounts_serialize( + id=id, + var_date=var_date, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Accounts", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_user_working_time_accounts_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + var_date: Annotated[date, Field(description="Day to return the balances for.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a User's working time accounts + + Returns the User's working time account balances as of the given day. + + :param id: ID of the User. (required) + :type id: str + :param var_date: Day to return the balances for. (required) + :type var_date: date + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_working_time_accounts_serialize( + id=id, + var_date=var_date, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Accounts", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_user_working_time_accounts_serialize( + self, + id, + var_date, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + if var_date is not None: + _path_params['date'] = var_date + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/users/{id}/working-time-accounts/{date}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/track_api.py b/sdk/python/timr_api/api/track_api.py new file mode 100644 index 0000000..090b660 --- /dev/null +++ b/sdk/python/timr_api/api/track_api.py @@ -0,0 +1,1187 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing import List +from typing_extensions import Annotated +from timr_api.models.waypoint import Waypoint + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class TrackApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_track( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + waypoint: Annotated[List[Waypoint], Field(description="Working Time Date Span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Waypoint]: + """Create a Drive Log's Track + + Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + + :param id: drive log id (required) + :type id: str + :param waypoint: Working Time Date Span entity (required) + :type waypoint: List[Waypoint] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_track_serialize( + id=id, + waypoint=waypoint, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "List[Waypoint]", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_track_with_http_info( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + waypoint: Annotated[List[Waypoint], Field(description="Working Time Date Span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Waypoint]]: + """Create a Drive Log's Track + + Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + + :param id: drive log id (required) + :type id: str + :param waypoint: Working Time Date Span entity (required) + :type waypoint: List[Waypoint] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_track_serialize( + id=id, + waypoint=waypoint, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "List[Waypoint]", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_track_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + waypoint: Annotated[List[Waypoint], Field(description="Working Time Date Span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Drive Log's Track + + Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + + :param id: drive log id (required) + :type id: str + :param waypoint: Working Time Date Span entity (required) + :type waypoint: List[Waypoint] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_track_serialize( + id=id, + waypoint=waypoint, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "List[Waypoint]", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_track_serialize( + self, + id, + waypoint, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'Waypoint': '', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if waypoint is not None: + _body_params = waypoint + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/drive-logs/{id}/track', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def delete_track( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Drive Log's Track + + Deletes the Drive Log's Track. The Drive Log itself is kept. + + :param id: drive log id (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_track_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_track_with_http_info( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Drive Log's Track + + Deletes the Drive Log's Track. The Drive Log itself is kept. + + :param id: drive log id (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_track_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_track_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Drive Log's Track + + Deletes the Drive Log's Track. The Drive Log itself is kept. + + :param id: drive log id (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_track_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_track_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/drive-logs/{id}/track', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_track( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Waypoint]: + """Get a Drive Log's Track + + Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + + :param id: drive log id (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_track_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Waypoint]", + '400': "Error", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_track_with_http_info( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Waypoint]]: + """Get a Drive Log's Track + + Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + + :param id: drive log id (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_track_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Waypoint]", + '400': "Error", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_track_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Drive Log's Track + + Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + + :param id: drive log id (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_track_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Waypoint]", + '400': "Error", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_track_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/drive-logs/{id}/track', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def update_track( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + waypoint: Annotated[List[Waypoint], Field(description="working time date span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Waypoint]: + """Replace a Drive Log's Track + + Replaces the Drive Log's Track with the waypoints in the request body. + + :param id: drive log id (required) + :type id: str + :param waypoint: working time date span entity (required) + :type waypoint: List[Waypoint] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_track_serialize( + id=id, + waypoint=waypoint, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Waypoint]", + '400': "Error", + '403': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def update_track_with_http_info( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + waypoint: Annotated[List[Waypoint], Field(description="working time date span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Waypoint]]: + """Replace a Drive Log's Track + + Replaces the Drive Log's Track with the waypoints in the request body. + + :param id: drive log id (required) + :type id: str + :param waypoint: working time date span entity (required) + :type waypoint: List[Waypoint] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_track_serialize( + id=id, + waypoint=waypoint, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Waypoint]", + '400': "Error", + '403': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_track_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="drive log id")], + waypoint: Annotated[List[Waypoint], Field(description="working time date span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Replace a Drive Log's Track + + Replaces the Drive Log's Track with the waypoints in the request body. + + :param id: drive log id (required) + :type id: str + :param waypoint: working time date span entity (required) + :type waypoint: List[Waypoint] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_track_serialize( + id=id, + waypoint=waypoint, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Waypoint]", + '400': "Error", + '403': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _update_track_serialize( + self, + id, + waypoint, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'Waypoint': '', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if waypoint is not None: + _body_params = waypoint + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/drive-logs/{id}/track', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/user_api.py b/sdk/python/timr_api/api/user_api.py new file mode 100644 index 0000000..90fe9c0 --- /dev/null +++ b/sdk/python/timr_api/api/user_api.py @@ -0,0 +1,2316 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from datetime import date +from pydantic import Field, StrictBool, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.teams_partial_page import TeamsPartialPage +from timr_api.models.user import User +from timr_api.models.user_create import UserCreate +from timr_api.models.user_update import UserUpdate +from timr_api.models.users_page import UsersPage +from timr_api.models.work_schedule_model import WorkScheduleModel + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class UserApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_user( + self, + user_create: Annotated[UserCreate, Field(description="User entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> User: + """Create a User + + Creates a User from the data in the request body. + + :param user_create: User entity (required) + :type user_create: UserCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_user_serialize( + user_create=user_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "User", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_user_with_http_info( + self, + user_create: Annotated[UserCreate, Field(description="User entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[User]: + """Create a User + + Creates a User from the data in the request body. + + :param user_create: User entity (required) + :type user_create: UserCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_user_serialize( + user_create=user_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "User", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_user_without_preload_content( + self, + user_create: Annotated[UserCreate, Field(description="User entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a User + + Creates a User from the data in the request body. + + :param user_create: User entity (required) + :type user_create: UserCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_user_serialize( + user_create=user_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "User", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_user_serialize( + self, + user_create, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if user_create is not None: + _body_params = user_create + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/users', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_user_team_leaderships( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TeamsPartialPage: + """List a User's Team leaderships + + Lists the Teams the User leads. + + :param id: ID of the User. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TeamsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_user_team_leaderships_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TeamsPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_user_team_leaderships_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TeamsPartialPage]: + """List a User's Team leaderships + + Lists the Teams the User leads. + + :param id: ID of the User. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TeamsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_user_team_leaderships_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TeamsPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_user_team_leaderships_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List a User's Team leaderships + + Lists the Teams the User leads. + + :param id: ID of the User. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TeamsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_user_team_leaderships_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TeamsPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_user_team_leaderships_serialize( + self, + id, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/users/{id}/team-leaderships', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_user_team_memberships( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> TeamsPartialPage: + """List a User's Team memberships + + Lists the Teams the User is a member of. + + :param id: ID of the User. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TeamsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_user_team_memberships_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TeamsPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_user_team_memberships_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[TeamsPartialPage]: + """List a User's Team memberships + + Lists the Teams the User is a member of. + + :param id: ID of the User. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TeamsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_user_team_memberships_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TeamsPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_user_team_memberships_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List a User's Team memberships + + Lists the Teams the User is a member of. + + :param id: ID of the User. (required) + :type id: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: TeamsSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_user_team_memberships_serialize( + id=id, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "TeamsPartialPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_user_team_memberships_serialize( + self, + id, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/users/{id}/team-memberships', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_users( + self, + name: Annotated[Optional[StrictStr], Field(description="Only return Users whose name contains this text.")] = None, + entry_date_from: Annotated[Optional[date], Field(description="Only return Users whose entry date is on or after this day.")] = None, + entry_date_to: Annotated[Optional[date], Field(description="Only return Users whose entry date is on or before this day.")] = None, + resign_date_from: Annotated[Optional[date], Field(description="Only return Users whose resignation date is on or after this day.")] = None, + resign_date_to: Annotated[Optional[date], Field(description="Only return Users whose resignation date is on or before this day.")] = None, + resigned: Annotated[Optional[StrictBool], Field(description="Only return Users who have resigned (true) or have not resigned (false).")] = None, + employee_number: Annotated[Optional[StrictStr], Field(description="Only return Users with this employee number.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> UsersPage: + """List Users + + Lists the Users the authenticated user or API token can access. + + :param name: Only return Users whose name contains this text. + :type name: str + :param entry_date_from: Only return Users whose entry date is on or after this day. + :type entry_date_from: date + :param entry_date_to: Only return Users whose entry date is on or before this day. + :type entry_date_to: date + :param resign_date_from: Only return Users whose resignation date is on or after this day. + :type resign_date_from: date + :param resign_date_to: Only return Users whose resignation date is on or before this day. + :type resign_date_to: date + :param resigned: Only return Users who have resigned (true) or have not resigned (false). + :type resigned: bool + :param employee_number: Only return Users with this employee number. + :type employee_number: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: UsersSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_users_serialize( + name=name, + entry_date_from=entry_date_from, + entry_date_to=entry_date_to, + resign_date_from=resign_date_from, + resign_date_to=resign_date_to, + resigned=resigned, + employee_number=employee_number, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UsersPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_users_with_http_info( + self, + name: Annotated[Optional[StrictStr], Field(description="Only return Users whose name contains this text.")] = None, + entry_date_from: Annotated[Optional[date], Field(description="Only return Users whose entry date is on or after this day.")] = None, + entry_date_to: Annotated[Optional[date], Field(description="Only return Users whose entry date is on or before this day.")] = None, + resign_date_from: Annotated[Optional[date], Field(description="Only return Users whose resignation date is on or after this day.")] = None, + resign_date_to: Annotated[Optional[date], Field(description="Only return Users whose resignation date is on or before this day.")] = None, + resigned: Annotated[Optional[StrictBool], Field(description="Only return Users who have resigned (true) or have not resigned (false).")] = None, + employee_number: Annotated[Optional[StrictStr], Field(description="Only return Users with this employee number.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[UsersPage]: + """List Users + + Lists the Users the authenticated user or API token can access. + + :param name: Only return Users whose name contains this text. + :type name: str + :param entry_date_from: Only return Users whose entry date is on or after this day. + :type entry_date_from: date + :param entry_date_to: Only return Users whose entry date is on or before this day. + :type entry_date_to: date + :param resign_date_from: Only return Users whose resignation date is on or after this day. + :type resign_date_from: date + :param resign_date_to: Only return Users whose resignation date is on or before this day. + :type resign_date_to: date + :param resigned: Only return Users who have resigned (true) or have not resigned (false). + :type resigned: bool + :param employee_number: Only return Users with this employee number. + :type employee_number: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: UsersSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_users_serialize( + name=name, + entry_date_from=entry_date_from, + entry_date_to=entry_date_to, + resign_date_from=resign_date_from, + resign_date_to=resign_date_to, + resigned=resigned, + employee_number=employee_number, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UsersPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_users_without_preload_content( + self, + name: Annotated[Optional[StrictStr], Field(description="Only return Users whose name contains this text.")] = None, + entry_date_from: Annotated[Optional[date], Field(description="Only return Users whose entry date is on or after this day.")] = None, + entry_date_to: Annotated[Optional[date], Field(description="Only return Users whose entry date is on or before this day.")] = None, + resign_date_from: Annotated[Optional[date], Field(description="Only return Users whose resignation date is on or after this day.")] = None, + resign_date_to: Annotated[Optional[date], Field(description="Only return Users whose resignation date is on or before this day.")] = None, + resigned: Annotated[Optional[StrictBool], Field(description="Only return Users who have resigned (true) or have not resigned (false).")] = None, + employee_number: Annotated[Optional[StrictStr], Field(description="Only return Users with this employee number.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Users + + Lists the Users the authenticated user or API token can access. + + :param name: Only return Users whose name contains this text. + :type name: str + :param entry_date_from: Only return Users whose entry date is on or after this day. + :type entry_date_from: date + :param entry_date_to: Only return Users whose entry date is on or before this day. + :type entry_date_to: date + :param resign_date_from: Only return Users whose resignation date is on or after this day. + :type resign_date_from: date + :param resign_date_to: Only return Users whose resignation date is on or before this day. + :type resign_date_to: date + :param resigned: Only return Users who have resigned (true) or have not resigned (false). + :type resigned: bool + :param employee_number: Only return Users with this employee number. + :type employee_number: str + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: UsersSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_users_serialize( + name=name, + entry_date_from=entry_date_from, + entry_date_to=entry_date_to, + resign_date_from=resign_date_from, + resign_date_to=resign_date_to, + resigned=resigned, + employee_number=employee_number, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "UsersPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_users_serialize( + self, + name, + entry_date_from, + entry_date_to, + resign_date_from, + resign_date_to, + resigned, + employee_number, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if name is not None: + + _query_params.append(('name', name)) + + if entry_date_from is not None: + if isinstance(entry_date_from, date): + _query_params.append( + ( + 'entry_date_from', + entry_date_from.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('entry_date_from', entry_date_from)) + + if entry_date_to is not None: + if isinstance(entry_date_to, date): + _query_params.append( + ( + 'entry_date_to', + entry_date_to.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('entry_date_to', entry_date_to)) + + if resign_date_from is not None: + if isinstance(resign_date_from, date): + _query_params.append( + ( + 'resign_date_from', + resign_date_from.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('resign_date_from', resign_date_from)) + + if resign_date_to is not None: + if isinstance(resign_date_to, date): + _query_params.append( + ( + 'resign_date_to', + resign_date_to.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('resign_date_to', resign_date_to)) + + if resigned is not None: + + _query_params.append(('resigned', resigned)) + + if employee_number is not None: + + _query_params.append(('employee_number', employee_number)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/users', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_user( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> User: + """Get a User + + Returns a single User by its ID. + + :param id: ID of the User. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_user_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[User]: + """Get a User + + Returns a single User by its ID. + + :param id: ID of the User. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_user_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a User + + Returns a single User by its ID. + + :param id: ID of the User. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_user_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/users/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_user_work_schedule_model( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkScheduleModel: + """Get a User's Work Schedule Model + + Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + + :param id: ID of the User. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_work_schedule_model_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkScheduleModel", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_user_work_schedule_model_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkScheduleModel]: + """Get a User's Work Schedule Model + + Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + + :param id: ID of the User. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_work_schedule_model_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkScheduleModel", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_user_work_schedule_model_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a User's Work Schedule Model + + Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + + :param id: ID of the User. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_work_schedule_model_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkScheduleModel", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_user_work_schedule_model_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/users/{id}/work-schedule-model', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def update_user( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + user_update: Annotated[UserUpdate, Field(description="User entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> User: + """Update a User + + Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the User. (required) + :type id: str + :param user_update: User entity (required) + :type user_update: UserUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_user_serialize( + id=id, + user_update=user_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def update_user_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + user_update: Annotated[UserUpdate, Field(description="User entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[User]: + """Update a User + + Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the User. (required) + :type id: str + :param user_update: User entity (required) + :type user_update: UserUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_user_serialize( + id=id, + user_update=user_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_user_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the User.")], + user_update: Annotated[UserUpdate, Field(description="User entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update a User + + Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the User. (required) + :type id: str + :param user_update: User entity (required) + :type user_update: UserUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_user_serialize( + id=id, + user_update=user_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _update_user_serialize( + self, + id, + user_update, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if user_update is not None: + _body_params = user_update + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/users/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/work_schedule_model_api.py b/sdk/python/timr_api/api/work_schedule_model_api.py new file mode 100644 index 0000000..8532625 --- /dev/null +++ b/sdk/python/timr_api/api/work_schedule_model_api.py @@ -0,0 +1,899 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictStr +from typing import Any, Optional +from typing_extensions import Annotated +from timr_api.models.work_schedule_model import WorkScheduleModel +from timr_api.models.work_schedule_models_page import WorkScheduleModelsPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class WorkScheduleModelApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def delete_work_schedule_model( + self, + id: Annotated[StrictStr, Field(description="ID of the Work Schedule Model.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Work Schedule Model + + Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + + :param id: ID of the Work Schedule Model. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_work_schedule_model_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_work_schedule_model_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Work Schedule Model.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Work Schedule Model + + Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + + :param id: ID of the Work Schedule Model. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_work_schedule_model_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_work_schedule_model_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Work Schedule Model.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Work Schedule Model + + Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + + :param id: ID of the Work Schedule Model. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_work_schedule_model_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_work_schedule_model_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/work-schedule-models/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_work_schedule_models( + self, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkScheduleModelsPage: + """List Work Schedule Models + + Lists the Work Schedule Models the authenticated user or API token can access. + + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkScheduleModelSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_work_schedule_models_serialize( + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkScheduleModelsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_work_schedule_models_with_http_info( + self, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkScheduleModelsPage]: + """List Work Schedule Models + + Lists the Work Schedule Models the authenticated user or API token can access. + + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkScheduleModelSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_work_schedule_models_serialize( + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkScheduleModelsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_work_schedule_models_without_preload_content( + self, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Work Schedule Models + + Lists the Work Schedule Models the authenticated user or API token can access. + + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkScheduleModelSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_work_schedule_models_serialize( + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkScheduleModelsPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_work_schedule_models_serialize( + self, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/work-schedule-models', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_work_schedule_model( + self, + id: Annotated[StrictStr, Field(description="ID of the Work Schedule Model.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkScheduleModel: + """Get a Work Schedule Model + + Returns a single Work Schedule Model by its ID. + + :param id: ID of the Work Schedule Model. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_work_schedule_model_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkScheduleModel", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_work_schedule_model_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Work Schedule Model.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkScheduleModel]: + """Get a Work Schedule Model + + Returns a single Work Schedule Model by its ID. + + :param id: ID of the Work Schedule Model. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_work_schedule_model_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkScheduleModel", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_work_schedule_model_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Work Schedule Model.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Work Schedule Model + + Returns a single Work Schedule Model by its ID. + + :param id: ID of the Work Schedule Model. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_work_schedule_model_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkScheduleModel", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_work_schedule_model_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/work-schedule-models/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/working_time_api.py b/sdk/python/timr_api/api/working_time_api.py new file mode 100644 index 0000000..65fa3d5 --- /dev/null +++ b/sdk/python/timr_api/api/working_time_api.py @@ -0,0 +1,2028 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from datetime import date, datetime +from pydantic import Field, StrictBool, StrictStr +from typing import Any, List, Optional +from typing_extensions import Annotated +from timr_api.models.deleted_entry_with_metadata_page import DeletedEntryWithMetadataPage +from timr_api.models.working_time import WorkingTime +from timr_api.models.working_time_create import WorkingTimeCreate +from timr_api.models.working_time_status import WorkingTimeStatus +from timr_api.models.working_time_type_category import WorkingTimeTypeCategory +from timr_api.models.working_time_update import WorkingTimeUpdate +from timr_api.models.working_times_page import WorkingTimesPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class WorkingTimeApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_working_time( + self, + working_time_create: Annotated[WorkingTimeCreate, Field(description="Working Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTime: + """Create a Working Time + + Creates a Working Time from the data in the request body. + + :param working_time_create: Working Time entity (required) + :type working_time_create: WorkingTimeCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_working_time_serialize( + working_time_create=working_time_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "WorkingTime", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_working_time_with_http_info( + self, + working_time_create: Annotated[WorkingTimeCreate, Field(description="Working Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTime]: + """Create a Working Time + + Creates a Working Time from the data in the request body. + + :param working_time_create: Working Time entity (required) + :type working_time_create: WorkingTimeCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_working_time_serialize( + working_time_create=working_time_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "WorkingTime", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_working_time_without_preload_content( + self, + working_time_create: Annotated[WorkingTimeCreate, Field(description="Working Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Working Time + + Creates a Working Time from the data in the request body. + + :param working_time_create: Working Time entity (required) + :type working_time_create: WorkingTimeCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_working_time_serialize( + working_time_create=working_time_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "WorkingTime", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_working_time_serialize( + self, + working_time_create, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if working_time_create is not None: + _body_params = working_time_create + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/working-times', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def delete_working_time( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Working Time + + Deletes the Working Time. + + :param id: ID of the Working Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_working_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_working_time_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Working Time + + Deletes the Working Time. + + :param id: ID of the Working Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_working_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_working_time_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Working Time + + Deletes the Working Time. + + :param id: ID of the Working Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_working_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_working_time_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/working-times/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_deleted_working_times( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DeletedEntryWithMetadataPage: + """List deleted Working Times + + Lists Working Times that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_working_times_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryWithMetadataPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_deleted_working_times_with_http_info( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DeletedEntryWithMetadataPage]: + """List deleted Working Times + + Lists Working Times that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_working_times_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryWithMetadataPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_deleted_working_times_without_preload_content( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List deleted Working Times + + Lists Working Times that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_working_times_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryWithMetadataPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_deleted_working_times_serialize( + self, + last_modified_after, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if last_modified_after is not None: + if isinstance(last_modified_after, datetime): + _query_params.append( + ( + 'last_modified_after', + last_modified_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('last_modified_after', last_modified_after)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/working-times:deleted', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_working_times( + self, + notes: Annotated[Optional[StrictStr], Field(description="Only return entries whose notes contain this text.")] = None, + start_from: Annotated[Optional[date], Field(description="Only return entries starting on or after this day.")] = None, + start_to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + working_time_types: Annotated[Optional[List[StrictStr]], Field(description="Only return entries of these Working Time Types.")] = None, + working_time_type_categories: Annotated[Optional[List[WorkingTimeTypeCategory]], Field(description="Only return entries whose Working Time Type is in one of these categories.")] = None, + statuses: Annotated[Optional[List[WorkingTimeStatus]], Field(description="Only return entries in one of these statuses.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + changed: Annotated[Optional[StrictBool], Field(description="Only return entries that were changed by the user (true) or left unchanged (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTimesPage: + """List Working Times + + Lists the Working Times the authenticated user or API token can access. + + :param notes: Only return entries whose notes contain this text. + :type notes: str + :param start_from: Only return entries starting on or after this day. + :type start_from: date + :param start_to: Only return entries starting on or before this day. + :type start_to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param working_time_types: Only return entries of these Working Time Types. + :type working_time_types: List[str] + :param working_time_type_categories: Only return entries whose Working Time Type is in one of these categories. + :type working_time_type_categories: List[WorkingTimeTypeCategory] + :param statuses: Only return entries in one of these statuses. + :type statuses: List[WorkingTimeStatus] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param changed: Only return entries that were changed by the user (true) or left unchanged (false). + :type changed: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkingTimesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_working_times_serialize( + notes=notes, + start_from=start_from, + start_to=start_to, + last_modified_after=last_modified_after, + working_time_types=working_time_types, + working_time_type_categories=working_time_type_categories, + statuses=statuses, + users=users, + changed=changed, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_working_times_with_http_info( + self, + notes: Annotated[Optional[StrictStr], Field(description="Only return entries whose notes contain this text.")] = None, + start_from: Annotated[Optional[date], Field(description="Only return entries starting on or after this day.")] = None, + start_to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + working_time_types: Annotated[Optional[List[StrictStr]], Field(description="Only return entries of these Working Time Types.")] = None, + working_time_type_categories: Annotated[Optional[List[WorkingTimeTypeCategory]], Field(description="Only return entries whose Working Time Type is in one of these categories.")] = None, + statuses: Annotated[Optional[List[WorkingTimeStatus]], Field(description="Only return entries in one of these statuses.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + changed: Annotated[Optional[StrictBool], Field(description="Only return entries that were changed by the user (true) or left unchanged (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTimesPage]: + """List Working Times + + Lists the Working Times the authenticated user or API token can access. + + :param notes: Only return entries whose notes contain this text. + :type notes: str + :param start_from: Only return entries starting on or after this day. + :type start_from: date + :param start_to: Only return entries starting on or before this day. + :type start_to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param working_time_types: Only return entries of these Working Time Types. + :type working_time_types: List[str] + :param working_time_type_categories: Only return entries whose Working Time Type is in one of these categories. + :type working_time_type_categories: List[WorkingTimeTypeCategory] + :param statuses: Only return entries in one of these statuses. + :type statuses: List[WorkingTimeStatus] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param changed: Only return entries that were changed by the user (true) or left unchanged (false). + :type changed: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkingTimesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_working_times_serialize( + notes=notes, + start_from=start_from, + start_to=start_to, + last_modified_after=last_modified_after, + working_time_types=working_time_types, + working_time_type_categories=working_time_type_categories, + statuses=statuses, + users=users, + changed=changed, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_working_times_without_preload_content( + self, + notes: Annotated[Optional[StrictStr], Field(description="Only return entries whose notes contain this text.")] = None, + start_from: Annotated[Optional[date], Field(description="Only return entries starting on or after this day.")] = None, + start_to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + working_time_types: Annotated[Optional[List[StrictStr]], Field(description="Only return entries of these Working Time Types.")] = None, + working_time_type_categories: Annotated[Optional[List[WorkingTimeTypeCategory]], Field(description="Only return entries whose Working Time Type is in one of these categories.")] = None, + statuses: Annotated[Optional[List[WorkingTimeStatus]], Field(description="Only return entries in one of these statuses.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + changed: Annotated[Optional[StrictBool], Field(description="Only return entries that were changed by the user (true) or left unchanged (false).")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Working Times + + Lists the Working Times the authenticated user or API token can access. + + :param notes: Only return entries whose notes contain this text. + :type notes: str + :param start_from: Only return entries starting on or after this day. + :type start_from: date + :param start_to: Only return entries starting on or before this day. + :type start_to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param working_time_types: Only return entries of these Working Time Types. + :type working_time_types: List[str] + :param working_time_type_categories: Only return entries whose Working Time Type is in one of these categories. + :type working_time_type_categories: List[WorkingTimeTypeCategory] + :param statuses: Only return entries in one of these statuses. + :type statuses: List[WorkingTimeStatus] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param changed: Only return entries that were changed by the user (true) or left unchanged (false). + :type changed: bool + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkingTimesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_working_times_serialize( + notes=notes, + start_from=start_from, + start_to=start_to, + last_modified_after=last_modified_after, + working_time_types=working_time_types, + working_time_type_categories=working_time_type_categories, + statuses=statuses, + users=users, + changed=changed, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_working_times_serialize( + self, + notes, + start_from, + start_to, + last_modified_after, + working_time_types, + working_time_type_categories, + statuses, + users, + changed, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'working_time_types': 'multi', + 'working_time_type_categories': 'multi', + 'statuses': 'multi', + 'users': 'multi', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if notes is not None: + + _query_params.append(('notes', notes)) + + if start_from is not None: + if isinstance(start_from, date): + _query_params.append( + ( + 'start_from', + start_from.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('start_from', start_from)) + + if start_to is not None: + if isinstance(start_to, date): + _query_params.append( + ( + 'start_to', + start_to.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('start_to', start_to)) + + if last_modified_after is not None: + if isinstance(last_modified_after, datetime): + _query_params.append( + ( + 'last_modified_after', + last_modified_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('last_modified_after', last_modified_after)) + + if working_time_types is not None: + + _query_params.append(('working_time_types', working_time_types)) + + if working_time_type_categories is not None: + + _query_params.append(('working_time_type_categories', working_time_type_categories)) + + if statuses is not None: + + _query_params.append(('statuses', statuses)) + + if users is not None: + + _query_params.append(('users', users)) + + if changed is not None: + + _query_params.append(('changed', changed)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/working-times', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_working_time( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTime: + """Get a Working Time + + Returns a single Working Time by its ID. + + :param id: ID of the Working Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_working_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTime", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_working_time_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTime]: + """Get a Working Time + + Returns a single Working Time by its ID. + + :param id: ID of the Working Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_working_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTime", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_working_time_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Working Time + + Returns a single Working Time by its ID. + + :param id: ID of the Working Time. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_working_time_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTime", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_working_time_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/working-times/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def update_working_time( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time.")], + working_time_update: Annotated[WorkingTimeUpdate, Field(description="Working Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTime: + """Update a Working Time + + Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Working Time. (required) + :type id: str + :param working_time_update: Working Time entity (required) + :type working_time_update: WorkingTimeUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_working_time_serialize( + id=id, + working_time_update=working_time_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTime", + '302': None, + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def update_working_time_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time.")], + working_time_update: Annotated[WorkingTimeUpdate, Field(description="Working Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTime]: + """Update a Working Time + + Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Working Time. (required) + :type id: str + :param working_time_update: Working Time entity (required) + :type working_time_update: WorkingTimeUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_working_time_serialize( + id=id, + working_time_update=working_time_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTime", + '302': None, + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_working_time_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time.")], + working_time_update: Annotated[WorkingTimeUpdate, Field(description="Working Time entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update a Working Time + + Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + + :param id: ID of the Working Time. (required) + :type id: str + :param working_time_update: Working Time entity (required) + :type working_time_update: WorkingTimeUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_working_time_serialize( + id=id, + working_time_update=working_time_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTime", + '302': None, + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _update_working_time_serialize( + self, + id, + working_time_update, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if working_time_update is not None: + _body_params = working_time_update + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/working-times/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/working_time_date_span_api.py b/sdk/python/timr_api/api/working_time_date_span_api.py new file mode 100644 index 0000000..49d49a8 --- /dev/null +++ b/sdk/python/timr_api/api/working_time_date_span_api.py @@ -0,0 +1,1956 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from datetime import date, datetime +from pydantic import Field, StrictStr +from typing import Any, List, Optional +from typing_extensions import Annotated +from timr_api.models.deleted_entry_with_metadata_page import DeletedEntryWithMetadataPage +from timr_api.models.working_time_date_span import WorkingTimeDateSpan +from timr_api.models.working_time_date_span_create import WorkingTimeDateSpanCreate +from timr_api.models.working_time_date_span_page import WorkingTimeDateSpanPage +from timr_api.models.working_time_date_span_update import WorkingTimeDateSpanUpdate + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class WorkingTimeDateSpanApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def create_working_time_date_span( + self, + working_time_date_span_create: Annotated[WorkingTimeDateSpanCreate, Field(description="Working Time Date Span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTimeDateSpan: + """Create a Working Time Date Span + + Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + + :param working_time_date_span_create: Working Time Date Span entity (required) + :type working_time_date_span_create: WorkingTimeDateSpanCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_working_time_date_span_serialize( + working_time_date_span_create=working_time_date_span_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "WorkingTimeDateSpan", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def create_working_time_date_span_with_http_info( + self, + working_time_date_span_create: Annotated[WorkingTimeDateSpanCreate, Field(description="Working Time Date Span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTimeDateSpan]: + """Create a Working Time Date Span + + Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + + :param working_time_date_span_create: Working Time Date Span entity (required) + :type working_time_date_span_create: WorkingTimeDateSpanCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_working_time_date_span_serialize( + working_time_date_span_create=working_time_date_span_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "WorkingTimeDateSpan", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_working_time_date_span_without_preload_content( + self, + working_time_date_span_create: Annotated[WorkingTimeDateSpanCreate, Field(description="Working Time Date Span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a Working Time Date Span + + Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + + :param working_time_date_span_create: Working Time Date Span entity (required) + :type working_time_date_span_create: WorkingTimeDateSpanCreate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_working_time_date_span_serialize( + working_time_date_span_create=working_time_date_span_create, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "WorkingTimeDateSpan", + '400': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_working_time_date_span_serialize( + self, + working_time_date_span_create, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if working_time_date_span_create is not None: + _body_params = working_time_date_span_create + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/working-time-date-spans', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def delete_working_time_date_span( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Date Span.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Working Time Date Span + + Deletes the Working Time Date Span together with the Working Times it covers. + + :param id: ID of the Working Time Date Span. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_working_time_date_span_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_working_time_date_span_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Date Span.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Working Time Date Span + + Deletes the Working Time Date Span together with the Working Times it covers. + + :param id: ID of the Working Time Date Span. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_working_time_date_span_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_working_time_date_span_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Date Span.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Working Time Date Span + + Deletes the Working Time Date Span together with the Working Times it covers. + + :param id: ID of the Working Time Date Span. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_working_time_date_span_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_working_time_date_span_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/working-time-date-spans/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_deleted_working_time_date_spans( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DeletedEntryWithMetadataPage: + """List deleted Working Time Date Spans + + Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_working_time_date_spans_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryWithMetadataPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_deleted_working_time_date_spans_with_http_info( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DeletedEntryWithMetadataPage]: + """List deleted Working Time Date Spans + + Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_working_time_date_spans_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryWithMetadataPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_deleted_working_time_date_spans_without_preload_content( + self, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List deleted Working Time Date Spans + + Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: DeletedEntrySortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_deleted_working_time_date_spans_serialize( + last_modified_after=last_modified_after, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DeletedEntryWithMetadataPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_deleted_working_time_date_spans_serialize( + self, + last_modified_after, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if last_modified_after is not None: + if isinstance(last_modified_after, datetime): + _query_params.append( + ( + 'last_modified_after', + last_modified_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('last_modified_after', last_modified_after)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/working-time-date-spans:deleted', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_working_time_date_spans( + self, + var_from: Annotated[Optional[date], Field(description="Only return Working Time Date Spans that end on or after this day.")] = None, + to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + working_time_types: Annotated[Optional[List[StrictStr]], Field(description="Only return entries of these Working Time Types.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTimeDateSpanPage: + """List Working Time Date Spans + + Lists the Working Time Date Spans the authenticated user or API token can access. + + :param var_from: Only return Working Time Date Spans that end on or after this day. + :type var_from: date + :param to: Only return entries starting on or before this day. + :type to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param working_time_types: Only return entries of these Working Time Types. + :type working_time_types: List[str] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkingTimeDateSpansSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_working_time_date_spans_serialize( + var_from=var_from, + to=to, + last_modified_after=last_modified_after, + working_time_types=working_time_types, + users=users, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeDateSpanPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_working_time_date_spans_with_http_info( + self, + var_from: Annotated[Optional[date], Field(description="Only return Working Time Date Spans that end on or after this day.")] = None, + to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + working_time_types: Annotated[Optional[List[StrictStr]], Field(description="Only return entries of these Working Time Types.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTimeDateSpanPage]: + """List Working Time Date Spans + + Lists the Working Time Date Spans the authenticated user or API token can access. + + :param var_from: Only return Working Time Date Spans that end on or after this day. + :type var_from: date + :param to: Only return entries starting on or before this day. + :type to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param working_time_types: Only return entries of these Working Time Types. + :type working_time_types: List[str] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkingTimeDateSpansSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_working_time_date_spans_serialize( + var_from=var_from, + to=to, + last_modified_after=last_modified_after, + working_time_types=working_time_types, + users=users, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeDateSpanPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_working_time_date_spans_without_preload_content( + self, + var_from: Annotated[Optional[date], Field(description="Only return Working Time Date Spans that end on or after this day.")] = None, + to: Annotated[Optional[date], Field(description="Only return entries starting on or before this day.")] = None, + last_modified_after: Annotated[Optional[datetime], Field(description="Only return entries modified after this instant.")] = None, + working_time_types: Annotated[Optional[List[StrictStr]], Field(description="Only return entries of these Working Time Types.")] = None, + users: Annotated[Optional[List[StrictStr]], Field(description="Only return entries belonging to these users.")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Working Time Date Spans + + Lists the Working Time Date Spans the authenticated user or API token can access. + + :param var_from: Only return Working Time Date Spans that end on or after this day. + :type var_from: date + :param to: Only return entries starting on or before this day. + :type to: date + :param last_modified_after: Only return entries modified after this instant. + :type last_modified_after: datetime + :param working_time_types: Only return entries of these Working Time Types. + :type working_time_types: List[str] + :param users: Only return entries belonging to these users. + :type users: List[str] + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkingTimeDateSpansSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_working_time_date_spans_serialize( + var_from=var_from, + to=to, + last_modified_after=last_modified_after, + working_time_types=working_time_types, + users=users, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeDateSpanPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_working_time_date_spans_serialize( + self, + var_from, + to, + last_modified_after, + working_time_types, + users, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'working_time_types': 'multi', + 'users': 'multi', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if var_from is not None: + if isinstance(var_from, date): + _query_params.append( + ( + 'from', + var_from.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('from', var_from)) + + if to is not None: + if isinstance(to, date): + _query_params.append( + ( + 'to', + to.strftime( + self.api_client.configuration.date_format + ) + ) + ) + else: + _query_params.append(('to', to)) + + if last_modified_after is not None: + if isinstance(last_modified_after, datetime): + _query_params.append( + ( + 'last_modified_after', + last_modified_after.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('last_modified_after', last_modified_after)) + + if working_time_types is not None: + + _query_params.append(('working_time_types', working_time_types)) + + if users is not None: + + _query_params.append(('users', users)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/working-time-date-spans', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_working_time_date_span( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Date Span.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTimeDateSpan: + """Get a Working Time Date Span + + Returns a single Working Time Date Span by its ID. + + :param id: ID of the Working Time Date Span. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_working_time_date_span_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeDateSpan", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_working_time_date_span_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Date Span.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTimeDateSpan]: + """Get a Working Time Date Span + + Returns a single Working Time Date Span by its ID. + + :param id: ID of the Working Time Date Span. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_working_time_date_span_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeDateSpan", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_working_time_date_span_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Date Span.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Working Time Date Span + + Returns a single Working Time Date Span by its ID. + + :param id: ID of the Working Time Date Span. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_working_time_date_span_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeDateSpan", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_working_time_date_span_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/working-time-date-spans/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def update_working_time_date_span( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Date Span.")], + working_time_date_span_update: Annotated[WorkingTimeDateSpanUpdate, Field(description="working time date span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTimeDateSpan: + """Update a Working Time Date Span + + Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + + :param id: ID of the Working Time Date Span. (required) + :type id: str + :param working_time_date_span_update: working time date span entity (required) + :type working_time_date_span_update: WorkingTimeDateSpanUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_working_time_date_span_serialize( + id=id, + working_time_date_span_update=working_time_date_span_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeDateSpan", + '204': None, + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def update_working_time_date_span_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Date Span.")], + working_time_date_span_update: Annotated[WorkingTimeDateSpanUpdate, Field(description="working time date span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTimeDateSpan]: + """Update a Working Time Date Span + + Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + + :param id: ID of the Working Time Date Span. (required) + :type id: str + :param working_time_date_span_update: working time date span entity (required) + :type working_time_date_span_update: WorkingTimeDateSpanUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_working_time_date_span_serialize( + id=id, + working_time_date_span_update=working_time_date_span_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeDateSpan", + '204': None, + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_working_time_date_span_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Date Span.")], + working_time_date_span_update: Annotated[WorkingTimeDateSpanUpdate, Field(description="working time date span entity")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update a Working Time Date Span + + Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + + :param id: ID of the Working Time Date Span. (required) + :type id: str + :param working_time_date_span_update: working time date span entity (required) + :type working_time_date_span_update: WorkingTimeDateSpanUpdate + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_working_time_date_span_serialize( + id=id, + working_time_date_span_update=working_time_date_span_update, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeDateSpan", + '204': None, + '400': "Error", + '403': "Error", + '404': "Error", + '409': "Error", + '422': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _update_working_time_date_span_serialize( + self, + id, + working_time_date_span_update, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if working_time_date_span_update is not None: + _body_params = working_time_date_span_update + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/working-time-date-spans/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api/working_time_type_api.py b/sdk/python/timr_api/api/working_time_type_api.py new file mode 100644 index 0000000..9cca17e --- /dev/null +++ b/sdk/python/timr_api/api/working_time_type_api.py @@ -0,0 +1,1043 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from pydantic import Field, StrictBool, StrictStr +from typing import Any, List, Optional +from typing_extensions import Annotated +from timr_api.models.duration_unit import DurationUnit +from timr_api.models.recording_mode_user import RecordingModeUser +from timr_api.models.working_time_type import WorkingTimeType +from timr_api.models.working_time_type_category import WorkingTimeTypeCategory +from timr_api.models.working_time_type_sub_category import WorkingTimeTypeSubCategory +from timr_api.models.working_time_types_page import WorkingTimeTypesPage + +from timr_api.api_client import ApiClient, RequestSerialized +from timr_api.api_response import ApiResponse +from timr_api.rest import RESTResponseType + + +class WorkingTimeTypeApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def delete_working_time_type( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Type.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Working Time Type + + Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + + :param id: ID of the Working Time Type. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_working_time_type_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_working_time_type_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Type.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Working Time Type + + Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + + :param id: ID of the Working Time Type. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_working_time_type_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_working_time_type_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Type.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Working Time Type + + Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + + :param id: ID of the Working Time Type. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_working_time_type_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_working_time_type_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/working-time-types/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def fetch_working_time_types( + self, + name: Annotated[Optional[StrictStr], Field(description="Only return entries whose name contains this text.")] = None, + short_name: Annotated[Optional[StrictStr], Field(description="filter by short name")] = None, + description: Annotated[Optional[StrictStr], Field(description="filter by description")] = None, + categories: Annotated[Optional[List[WorkingTimeTypeCategory]], Field(description="filter by WorkingTimeTypeCategory")] = None, + sub_categories: Annotated[Optional[List[WorkingTimeTypeSubCategory]], Field(description="filter by WorkingTimeTypeSubCategory")] = None, + edit_units: Annotated[Optional[List[DurationUnit]], Field(description="filter by WorkingTimeType's DurationUnit")] = None, + archived: Annotated[Optional[StrictBool], Field(description="Only return entries that are archived (true) or not archived (false).")] = None, + recording_modes: Annotated[Optional[List[RecordingModeUser]], Field(description="filter entries bAWS on their RecordingMode")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTimeTypesPage: + """List Working Time Types + + Lists the Working Time Types the authenticated user or API token can access. + + :param name: Only return entries whose name contains this text. + :type name: str + :param short_name: filter by short name + :type short_name: str + :param description: filter by description + :type description: str + :param categories: filter by WorkingTimeTypeCategory + :type categories: List[WorkingTimeTypeCategory] + :param sub_categories: filter by WorkingTimeTypeSubCategory + :type sub_categories: List[WorkingTimeTypeSubCategory] + :param edit_units: filter by WorkingTimeType's DurationUnit + :type edit_units: List[DurationUnit] + :param archived: Only return entries that are archived (true) or not archived (false). + :type archived: bool + :param recording_modes: filter entries bAWS on their RecordingMode + :type recording_modes: List[RecordingModeUser] + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkingTimeTypesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_working_time_types_serialize( + name=name, + short_name=short_name, + description=description, + categories=categories, + sub_categories=sub_categories, + edit_units=edit_units, + archived=archived, + recording_modes=recording_modes, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeTypesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def fetch_working_time_types_with_http_info( + self, + name: Annotated[Optional[StrictStr], Field(description="Only return entries whose name contains this text.")] = None, + short_name: Annotated[Optional[StrictStr], Field(description="filter by short name")] = None, + description: Annotated[Optional[StrictStr], Field(description="filter by description")] = None, + categories: Annotated[Optional[List[WorkingTimeTypeCategory]], Field(description="filter by WorkingTimeTypeCategory")] = None, + sub_categories: Annotated[Optional[List[WorkingTimeTypeSubCategory]], Field(description="filter by WorkingTimeTypeSubCategory")] = None, + edit_units: Annotated[Optional[List[DurationUnit]], Field(description="filter by WorkingTimeType's DurationUnit")] = None, + archived: Annotated[Optional[StrictBool], Field(description="Only return entries that are archived (true) or not archived (false).")] = None, + recording_modes: Annotated[Optional[List[RecordingModeUser]], Field(description="filter entries bAWS on their RecordingMode")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTimeTypesPage]: + """List Working Time Types + + Lists the Working Time Types the authenticated user or API token can access. + + :param name: Only return entries whose name contains this text. + :type name: str + :param short_name: filter by short name + :type short_name: str + :param description: filter by description + :type description: str + :param categories: filter by WorkingTimeTypeCategory + :type categories: List[WorkingTimeTypeCategory] + :param sub_categories: filter by WorkingTimeTypeSubCategory + :type sub_categories: List[WorkingTimeTypeSubCategory] + :param edit_units: filter by WorkingTimeType's DurationUnit + :type edit_units: List[DurationUnit] + :param archived: Only return entries that are archived (true) or not archived (false). + :type archived: bool + :param recording_modes: filter entries bAWS on their RecordingMode + :type recording_modes: List[RecordingModeUser] + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkingTimeTypesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_working_time_types_serialize( + name=name, + short_name=short_name, + description=description, + categories=categories, + sub_categories=sub_categories, + edit_units=edit_units, + archived=archived, + recording_modes=recording_modes, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeTypesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fetch_working_time_types_without_preload_content( + self, + name: Annotated[Optional[StrictStr], Field(description="Only return entries whose name contains this text.")] = None, + short_name: Annotated[Optional[StrictStr], Field(description="filter by short name")] = None, + description: Annotated[Optional[StrictStr], Field(description="filter by description")] = None, + categories: Annotated[Optional[List[WorkingTimeTypeCategory]], Field(description="filter by WorkingTimeTypeCategory")] = None, + sub_categories: Annotated[Optional[List[WorkingTimeTypeSubCategory]], Field(description="filter by WorkingTimeTypeSubCategory")] = None, + edit_units: Annotated[Optional[List[DurationUnit]], Field(description="filter by WorkingTimeType's DurationUnit")] = None, + archived: Annotated[Optional[StrictBool], Field(description="Only return entries that are archived (true) or not archived (false).")] = None, + recording_modes: Annotated[Optional[List[RecordingModeUser]], Field(description="filter entries bAWS on their RecordingMode")] = None, + page_token: Annotated[Optional[StrictStr], Field(description="Token identifying the page to return. Take it from the 'next_page_token' field of the previous response.")] = None, + limit: Annotated[Optional[Annotated[int, Field(strict=True, ge=1)]], Field(description="Maximum number of entries per page. Values above 500 are capped at 500.")] = None, + sort_direction: Annotated[Optional[Any], Field(description="Direction to sort the entries in.")] = None, + sort_by: Annotated[Optional[Any], Field(description="Property to sort the entries by.")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List Working Time Types + + Lists the Working Time Types the authenticated user or API token can access. + + :param name: Only return entries whose name contains this text. + :type name: str + :param short_name: filter by short name + :type short_name: str + :param description: filter by description + :type description: str + :param categories: filter by WorkingTimeTypeCategory + :type categories: List[WorkingTimeTypeCategory] + :param sub_categories: filter by WorkingTimeTypeSubCategory + :type sub_categories: List[WorkingTimeTypeSubCategory] + :param edit_units: filter by WorkingTimeType's DurationUnit + :type edit_units: List[DurationUnit] + :param archived: Only return entries that are archived (true) or not archived (false). + :type archived: bool + :param recording_modes: filter entries bAWS on their RecordingMode + :type recording_modes: List[RecordingModeUser] + :param page_token: Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. + :type page_token: str + :param limit: Maximum number of entries per page. Values above 500 are capped at 500. + :type limit: int + :param sort_direction: Direction to sort the entries in. + :type sort_direction: SortDirection + :param sort_by: Property to sort the entries by. + :type sort_by: WorkingTimeTypesSortColumn + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fetch_working_time_types_serialize( + name=name, + short_name=short_name, + description=description, + categories=categories, + sub_categories=sub_categories, + edit_units=edit_units, + archived=archived, + recording_modes=recording_modes, + page_token=page_token, + limit=limit, + sort_direction=sort_direction, + sort_by=sort_by, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeTypesPage", + '400': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fetch_working_time_types_serialize( + self, + name, + short_name, + description, + categories, + sub_categories, + edit_units, + archived, + recording_modes, + page_token, + limit, + sort_direction, + sort_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'categories': 'multi', + 'sub_categories': 'multi', + 'edit_units': 'multi', + 'recording_modes': 'multi', + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if name is not None: + + _query_params.append(('name', name)) + + if short_name is not None: + + _query_params.append(('short_name', short_name)) + + if description is not None: + + _query_params.append(('description', description)) + + if categories is not None: + + _query_params.append(('categories', categories)) + + if sub_categories is not None: + + _query_params.append(('sub_categories', sub_categories)) + + if edit_units is not None: + + _query_params.append(('edit_units', edit_units)) + + if archived is not None: + + _query_params.append(('archived', archived)) + + if recording_modes is not None: + + _query_params.append(('recording_modes', recording_modes)) + + if page_token is not None: + + _query_params.append(('page_token', page_token)) + + if limit is not None: + + _query_params.append(('limit', limit)) + + if sort_direction is not None: + + _query_params.append(('sort_direction', sort_direction.value)) + + if sort_by is not None: + + _query_params.append(('sort_by', sort_by.value)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/working-time-types', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_working_time_type( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Type.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> WorkingTimeType: + """Get a Working Time Type + + Returns a single Working Time Type by its ID. + + :param id: ID of the Working Time Type. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_working_time_type_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeType", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_working_time_type_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Type.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[WorkingTimeType]: + """Get a Working Time Type + + Returns a single Working Time Type by its ID. + + :param id: ID of the Working Time Type. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_working_time_type_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeType", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_working_time_type_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Working Time Type.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a Working Time Type + + Returns a single Working Time Type by its ID. + + :param id: ID of the Working Time Type. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_working_time_type_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "WorkingTimeType", + '403': "Error", + '404': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_working_time_type_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json', + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/working-time-types/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sdk/python/timr_api/api_client.py b/sdk/python/timr_api/api_client.py new file mode 100644 index 0000000..9c5978a --- /dev/null +++ b/sdk/python/timr_api/api_client.py @@ -0,0 +1,805 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + + +import datetime +from dateutil.parser import parse +from enum import Enum +import decimal +import json +import mimetypes +import os +import re +import tempfile +import uuid + +from urllib.parse import quote +from typing import Tuple, Optional, List, Dict, Union +from pydantic import SecretStr + +from timr_api.configuration import Configuration +from timr_api.api_response import ApiResponse, T as ApiResponseT +import timr_api.models +from timr_api import rest +from timr_api.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] + +class ApiClient: + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + """ + + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'decimal': decimal.Decimal, + 'UUID': uuid.UUID, + 'object': object, + } + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) + if files: + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth( + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + if _host is None or self.configuration.ignore_operation_servers: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) + url += "?" + url_query + + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + + try: + # perform request and return response + response_data = self.rest_client.request( + method, url, + headers=header_params, + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + + except ApiException as e: + raise e + + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type in ("bytearray", "bytes"): + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.headers.get('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type, content_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.headers, + raw_data = response_data.data + ) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is SecretStr, return obj.get_secret_value() + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is decimal.Decimal return string representation. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, Enum): + return obj.value + elif isinstance(obj, SecretStr): + return obj.get_secret_value() + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, uuid.UUID): + return str(obj) + elif isinstance(obj, list): + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] + elif isinstance(obj, tuple): + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + elif isinstance(obj, decimal.Decimal): + return str(obj) + elif isinstance(obj, dict): + return { + key: self.sanitize_for_serialization(val) + for key, val in obj.items() + } + + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')): + obj_dict = obj.to_dict() + else: + obj_dict = obj.__dict__ + + return self.sanitize_for_serialization(obj_dict) + + + def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + :param content_type: content type of response. + + :return: deserialized object. + """ + + # fetch data from response object + if content_type is None: + try: + data = json.loads(response_text) + except ValueError: + data = response_text + elif re.match(r'^application/(json|[\w!#$&.+\-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE): + if response_text == "": + data = "" + else: + data = json.loads(response_text) + elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE): + data = response_text + else: + raise ApiException( + status=0, + reason="Unsupported content type: {0}".format(content_type) + ) + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if isinstance(klass, str): + if klass.startswith('List['): + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('Dict['): + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(timr_api.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass is object: + return self.__deserialize_object(data) + elif klass is datetime.date: + return self.__deserialize_date(data) + elif klass is datetime.datetime: + return self.__deserialize_datetime(data) + elif klass is decimal.Decimal: + return decimal.Decimal(data) + elif klass is uuid.UUID: + return uuid.UUID(data) + elif issubclass(klass, Enum): + return self.__deserialize_enum(data, klass) + else: + return self.__deserialize_model(data, klass) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, quote(str(value))) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v)) + ) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(map(str, item)) for item in new_params]) + + def files_parameters( + self, + files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]], + ): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + for k, v in files.items(): + if isinstance(v, str): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + elif isinstance(v, bytes): + filename = k + filedata = v + elif isinstance(v, tuple): + filename, filedata = v + elif isinstance(v, list): + for file_param in v: + params.extend(self.files_parameters({k: file_param})) + continue + else: + raise ValueError("Unsupported file value") + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) + params.append( + tuple([k, tuple([filename, filedata, mimetype])]) + ) + return params + + def select_header_accept(self, accepts: List[str]) -> Optional[str]: + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return None + + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept + + return accepts[0] + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return None + + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type + + return content_types[0] + + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. + """ + if not auth_settings: + return + + if request_auth: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint + """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + handle file downloading + save response body into a tmp file and return the instance + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.headers.get("Content-Disposition") + if content_disposition: + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = os.path.basename(m.group(1)) # Strip any directory traversal + if filename in ("", ".", ".."): # fall back to tmp filename + filename = os.path.basename(path) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) + ) + + def __deserialize_enum(self, data, klass): + """Deserializes primitive type to enum. + + :param data: primitive type. + :param klass: class literal. + :return: enum value. + """ + try: + return klass(data) + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as `{1}`" + .format(data, klass) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) diff --git a/sdk/python/timr_api/api_response.py b/sdk/python/timr_api/api_response.py new file mode 100644 index 0000000..9bc7c11 --- /dev/null +++ b/sdk/python/timr_api/api_response.py @@ -0,0 +1,21 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel + +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): + """ + API response object + """ + + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") + + model_config = { + "arbitrary_types_allowed": True + } diff --git a/sdk/python/timr_api/configuration.py b/sdk/python/timr_api/configuration.py new file mode 100644 index 0000000..59b3672 --- /dev/null +++ b/sdk/python/timr_api/configuration.py @@ -0,0 +1,614 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import copy +import http.client as httplib +import logging +from logging import FileHandler +import multiprocessing +import sys +from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union +from typing_extensions import NotRequired, Self + +import urllib3 + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +ServerVariablesT = Dict[str, str] + +GenericAuthSetting = TypedDict( + "GenericAuthSetting", + { + "type": str, + "in": str, + "key": str, + "value": str, + }, +) + + +OAuth2AuthSetting = TypedDict( + "OAuth2AuthSetting", + { + "type": Literal["oauth2"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +APIKeyAuthSetting = TypedDict( + "APIKeyAuthSetting", + { + "type": Literal["api_key"], + "in": str, + "key": str, + "value": Optional[str], + }, +) + + +BasicAuthSetting = TypedDict( + "BasicAuthSetting", + { + "type": Literal["basic"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": Optional[str], + }, +) + + +BearerFormatAuthSetting = TypedDict( + "BearerFormatAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "format": Literal["JWT"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +BearerAuthSetting = TypedDict( + "BearerAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +HTTPSignatureAuthSetting = TypedDict( + "HTTPSignatureAuthSetting", + { + "type": Literal["http-signature"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": None, + }, +) + + +AuthSettings = TypedDict( + "AuthSettings", + { + "OAuth2": OAuth2AuthSetting, + "OAuth2": OAuth2AuthSetting, + }, + total=False, +) + + +class HostSettingVariable(TypedDict): + description: str + default_value: str + enum_values: List[str] + + +class HostSetting(TypedDict): + url: str + description: str + variables: NotRequired[Dict[str, HostSettingVariable]] + + +class Configuration: + """This class contains various settings of the API client. + + :param host: Base url. + :param ignore_operation_servers + Boolean to ignore operation servers for the API client. + Config will use `host` as the base url regardless of the operation servers. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum + values before. + :param verify_ssl: bool - Set this to false to skip verifying SSL certificate + when calling API from https server. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. + :param retries: int | urllib3.util.retry.Retry - Retry configuration. + :param ca_cert_data: verify the peer using concatenated CA certificate data + in PEM (str) or DER (bytes) format. + :param cert_file: the path to a client certificate file, for mTLS. + :param key_file: the path to a client key file, for mTLS. + :param assert_hostname: Set this to True/False to enable/disable SSL hostname verification. + :param tls_server_name: SSL/TLS Server Name Indication (SNI). Set this to the SNI value expected by the server. + :param connection_pool_maxsize: Connection pool max size. None in the constructor is coerced to 100 for async and cpu_count * 5 for sync. + :param proxy: Proxy URL. + :param proxy_headers: Proxy headers. + :param safe_chars_for_path_param: Safe characters for path parameter encoding. + :param client_side_validation: Enable client-side validation. Default True. + :param socket_options: Options to pass down to the underlying urllib3 socket. + :param datetime_format: Datetime format string for serialization. + :param date_format: Date format string for serialization. + + :Example: + """ + + _default: ClassVar[Optional[Self]] = None + + def __init__( + self, + host: Optional[str]=None, + api_key: Optional[Dict[str, str]]=None, + api_key_prefix: Optional[Dict[str, str]]=None, + username: Optional[str]=None, + password: Optional[str]=None, + access_token: Optional[str]=None, + server_index: Optional[int]=None, + server_variables: Optional[ServerVariablesT]=None, + server_operation_index: Optional[Dict[int, int]]=None, + server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None, + ignore_operation_servers: bool=False, + ssl_ca_cert: Optional[str]=None, + retries: Optional[Union[int, urllib3.util.retry.Retry]] = None, + ca_cert_data: Optional[Union[str, bytes]] = None, + cert_file: Optional[str]=None, + key_file: Optional[str]=None, + verify_ssl: bool=True, + assert_hostname: Optional[bool]=None, + tls_server_name: Optional[str]=None, + connection_pool_maxsize: Optional[int]=None, + proxy: Optional[str]=None, + proxy_headers: Optional[Any]=None, + safe_chars_for_path_param: str='', + client_side_validation: bool=True, + socket_options: Optional[Any]=None, + datetime_format: str="%Y-%m-%dT%H:%M:%SZ", + date_format: str="%Y-%m-%d", + *, + debug: Optional[bool] = None, + ) -> None: + """Constructor + """ + self._base_path = "https://api.timr.com/v1" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.ignore_operation_servers = ignore_operation_servers + """Ignore operation servers + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("timr_api") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler: Optional[FileHandler] = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + if debug is not None: + self.debug = debug + else: + self.__debug = False + """Debug switch + """ + + self.verify_ssl = verify_ssl + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.ca_cert_data = ca_cert_data + """Set this to verify the peer using PEM (str) or DER (bytes) + certificate data. + """ + self.cert_file = cert_file + """client certificate file + """ + self.key_file = key_file + """client key file + """ + self.assert_hostname = assert_hostname + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = tls_server_name + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ + + self.connection_pool_maxsize = connection_pool_maxsize if connection_pool_maxsize is not None else multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. None in the constructor is coerced to cpu_count * 5. + """ + + self.proxy = proxy + """Proxy URL + """ + self.proxy_headers = proxy_headers + """Proxy headers + """ + self.safe_chars_for_path_param = safe_chars_for_path_param + """Safe chars for path_param + """ + self.retries = retries + """Retry configuration + """ + # Enable client side validation + self.client_side_validation = client_side_validation + + self.socket_options = socket_options + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = datetime_format + """datetime format + """ + + self.date_format = date_format + """date format + """ + + def __deepcopy__(self, memo: Dict[int, Any]) -> Self: + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name: str, value: Any) -> None: + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default: Optional[Self]) -> None: + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls) -> Self: + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls) -> Self: + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = cls() + return cls._default + + @property + def logger_file(self) -> Optional[str]: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value: Optional[str]) -> None: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self) -> bool: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value: bool) -> None: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self) -> str: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value: str) -> None: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]: + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + return None + + def get_basic_auth_token(self) -> Optional[str]: + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self)-> AuthSettings: + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth: AuthSettings = {} + if self.access_token is not None: + auth['OAuth2'] = { + 'type': 'oauth2', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + if self.access_token is not None: + auth['OAuth2'] = { + 'type': 'oauth2', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + return auth + + def to_debug_report(self) -> str: + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 1.0.0\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self) -> List[HostSetting]: + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "https://api.timr.com/v1", + 'description': "No description provided", + } + ] + + def get_host_from_settings( + self, + index: Optional[int], + variables: Optional[ServerVariablesT]=None, + servers: Optional[List[HostSetting]]=None, + ) -> str: + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and variable['enum_values'] \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self) -> str: + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value: str) -> None: + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/sdk/python/timr_api/exceptions.py b/sdk/python/timr_api/exceptions.py new file mode 100644 index 0000000..c7bc9fc --- /dev/null +++ b/sdk/python/timr_api/exceptions.py @@ -0,0 +1,219 @@ +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from typing import Any, Optional +from typing_extensions import Self + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + + if http_resp: + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass + self.headers = http_resp.headers + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + # Added new conditions for 409 and 422 + if http_resp.status == 409: + raise ConflictException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 422: + raise UnprocessableEntityException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + if self.data: + error_message += "HTTP response data: {0}\n".format(self.data) + + return error_message + + +class BadRequestException(ApiException): + pass + + +class NotFoundException(ApiException): + pass + + +class UnauthorizedException(ApiException): + pass + + +class ForbiddenException(ApiException): + pass + + +class ServiceException(ApiException): + pass + + +class ConflictException(ApiException): + """Exception for HTTP 409 Conflict.""" + pass + + +class UnprocessableEntityException(ApiException): + """Exception for HTTP 422 Unprocessable Entity.""" + pass + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/sdk/python/timr_api/models/__init__.py b/sdk/python/timr_api/models/__init__.py new file mode 100644 index 0000000..ac7d759 --- /dev/null +++ b/sdk/python/timr_api/models/__init__.py @@ -0,0 +1,150 @@ +# coding: utf-8 + +# flake8: noqa +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +# import models into model package +from timr_api.models.accounts import Accounts +from timr_api.models.break_time import BreakTime +from timr_api.models.break_time_automatic import BreakTimeAutomatic +from timr_api.models.break_time_base import BreakTimeBase +from timr_api.models.break_time_manual import BreakTimeManual +from timr_api.models.break_time_ongoing import BreakTimeOngoing +from timr_api.models.break_time_type import BreakTimeType +from timr_api.models.break_time_update import BreakTimeUpdate +from timr_api.models.budget_planning_type import BudgetPlanningType +from timr_api.models.budget_planning_type_request import BudgetPlanningTypeRequest +from timr_api.models.car import Car +from timr_api.models.car_create import CarCreate +from timr_api.models.car_partial import CarPartial +from timr_api.models.car_update import CarUpdate +from timr_api.models.cars_page import CarsPage +from timr_api.models.cars_sort_column import CarsSortColumn +from timr_api.models.daily_work_schedule import DailyWorkSchedule +from timr_api.models.deleted_entry_page import DeletedEntryPage +from timr_api.models.deleted_entry_partial import DeletedEntryPartial +from timr_api.models.deleted_entry_sort_column import DeletedEntrySortColumn +from timr_api.models.deleted_entry_with_metadata import DeletedEntryWithMetadata +from timr_api.models.deleted_entry_with_metadata_page import DeletedEntryWithMetadataPage +from timr_api.models.drive_log import DriveLog +from timr_api.models.drive_log_categories_page import DriveLogCategoriesPage +from timr_api.models.drive_log_categories_sort_column import DriveLogCategoriesSortColumn +from timr_api.models.drive_log_category import DriveLogCategory +from timr_api.models.drive_log_category_partial import DriveLogCategoryPartial +from timr_api.models.drive_log_create import DriveLogCreate +from timr_api.models.drive_log_status import DriveLogStatus +from timr_api.models.drive_log_update import DriveLogUpdate +from timr_api.models.drive_log_upsert import DriveLogUpsert +from timr_api.models.drive_logs_page import DriveLogsPage +from timr_api.models.drive_logs_sort_column import DriveLogsSortColumn +from timr_api.models.duration import Duration +from timr_api.models.duration_type import DurationType +from timr_api.models.duration_unit import DurationUnit +from timr_api.models.error import Error +from timr_api.models.error_entry import ErrorEntry +from timr_api.models.flex_time_indicator import FlexTimeIndicator +from timr_api.models.holiday import Holiday +from timr_api.models.holiday_calendar_partial import HolidayCalendarPartial +from timr_api.models.holiday_calendars_page import HolidayCalendarsPage +from timr_api.models.holiday_calendars_sort_column import HolidayCalendarsSortColumn +from timr_api.models.holidays_page import HolidaysPage +from timr_api.models.holidays_sort_column import HolidaysSortColumn +from timr_api.models.location import Location +from timr_api.models.location_create import LocationCreate +from timr_api.models.location_update import LocationUpdate +from timr_api.models.normal_working_times import NormalWorkingTimes +from timr_api.models.overtime_surcharge_account import OvertimeSurchargeAccount +from timr_api.models.overtime_surcharge_accounts import OvertimeSurchargeAccounts +from timr_api.models.overtime_surcharge_rule import OvertimeSurchargeRule +from timr_api.models.paging_information import PagingInformation +from timr_api.models.platform import Platform +from timr_api.models.problem_detail import ProblemDetail +from timr_api.models.project_time import ProjectTime +from timr_api.models.project_time_create import ProjectTimeCreate +from timr_api.models.project_time_status import ProjectTimeStatus +from timr_api.models.project_time_update import ProjectTimeUpdate +from timr_api.models.project_time_upsert import ProjectTimeUpsert +from timr_api.models.project_times_page import ProjectTimesPage +from timr_api.models.project_times_sort_column import ProjectTimesSortColumn +from timr_api.models.recording_lock_type import RecordingLockType +from timr_api.models.recording_mode_user import RecordingModeUser +from timr_api.models.sort_direction import SortDirection +from timr_api.models.task import Task +from timr_api.models.task_base import TaskBase +from timr_api.models.task_create import TaskCreate +from timr_api.models.task_location import TaskLocation +from timr_api.models.task_partial import TaskPartial +from timr_api.models.task_reduced import TaskReduced +from timr_api.models.task_to_leader_assignment import TaskToLeaderAssignment +from timr_api.models.task_to_leader_assignments_page import TaskToLeaderAssignmentsPage +from timr_api.models.task_to_leader_assignments_sort_column import TaskToLeaderAssignmentsSortColumn +from timr_api.models.task_to_team_assignment import TaskToTeamAssignment +from timr_api.models.task_to_team_assignments_page import TaskToTeamAssignmentsPage +from timr_api.models.task_to_team_assignments_sort_column import TaskToTeamAssignmentsSortColumn +from timr_api.models.task_to_user_assignment import TaskToUserAssignment +from timr_api.models.task_to_user_assignment_upsert import TaskToUserAssignmentUpsert +from timr_api.models.task_to_user_assignments_page import TaskToUserAssignmentsPage +from timr_api.models.task_to_user_assignments_sort_column import TaskToUserAssignmentsSortColumn +from timr_api.models.task_update import TaskUpdate +from timr_api.models.tasks_page import TasksPage +from timr_api.models.tasks_reduced_page import TasksReducedPage +from timr_api.models.tasks_sort_column import TasksSortColumn +from timr_api.models.team import Team +from timr_api.models.team_create import TeamCreate +from timr_api.models.team_partial import TeamPartial +from timr_api.models.team_update import TeamUpdate +from timr_api.models.teams_page import TeamsPage +from timr_api.models.teams_partial_page import TeamsPartialPage +from timr_api.models.teams_sort_column import TeamsSortColumn +from timr_api.models.time_account import TimeAccount +from timr_api.models.user import User +from timr_api.models.user_create import UserCreate +from timr_api.models.user_partial import UserPartial +from timr_api.models.user_update import UserUpdate +from timr_api.models.users_page import UsersPage +from timr_api.models.users_partial_page import UsersPartialPage +from timr_api.models.users_sort_column import UsersSortColumn +from timr_api.models.vacation_account import VacationAccount +from timr_api.models.vacation_account_base import VacationAccountBase +from timr_api.models.vacation_account_days import VacationAccountDays +from timr_api.models.vacation_account_minutes import VacationAccountMinutes +from timr_api.models.vacation_unit import VacationUnit +from timr_api.models.venue_partial import VenuePartial +from timr_api.models.waypoint import Waypoint +from timr_api.models.work_schedule_model import WorkScheduleModel +from timr_api.models.work_schedule_model_partial import WorkScheduleModelPartial +from timr_api.models.work_schedule_model_sort_column import WorkScheduleModelSortColumn +from timr_api.models.work_schedule_model_type import WorkScheduleModelType +from timr_api.models.work_schedule_model_week import WorkScheduleModelWeek +from timr_api.models.work_schedule_models_page import WorkScheduleModelsPage +from timr_api.models.working_time import WorkingTime +from timr_api.models.working_time_create import WorkingTimeCreate +from timr_api.models.working_time_date_span import WorkingTimeDateSpan +from timr_api.models.working_time_date_span_create import WorkingTimeDateSpanCreate +from timr_api.models.working_time_date_span_page import WorkingTimeDateSpanPage +from timr_api.models.working_time_date_span_partial import WorkingTimeDateSpanPartial +from timr_api.models.working_time_date_span_update import WorkingTimeDateSpanUpdate +from timr_api.models.working_time_date_spans_sort_column import WorkingTimeDateSpansSortColumn +from timr_api.models.working_time_rules import WorkingTimeRules +from timr_api.models.working_time_status import WorkingTimeStatus +from timr_api.models.working_time_type import WorkingTimeType +from timr_api.models.working_time_type_category import WorkingTimeTypeCategory +from timr_api.models.working_time_type_partial import WorkingTimeTypePartial +from timr_api.models.working_time_type_sub_category import WorkingTimeTypeSubCategory +from timr_api.models.working_time_types_page import WorkingTimeTypesPage +from timr_api.models.working_time_types_sort_column import WorkingTimeTypesSortColumn +from timr_api.models.working_time_update import WorkingTimeUpdate +from timr_api.models.working_time_upsert import WorkingTimeUpsert +from timr_api.models.working_times_page import WorkingTimesPage +from timr_api.models.working_times_sort_column import WorkingTimesSortColumn + diff --git a/sdk/python/timr_api/models/accounts.py b/sdk/python/timr_api/models/accounts.py new file mode 100644 index 0000000..5473c2a --- /dev/null +++ b/sdk/python/timr_api/models/accounts.py @@ -0,0 +1,132 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.overtime_surcharge_accounts import OvertimeSurchargeAccounts +from timr_api.models.time_account import TimeAccount +from timr_api.models.vacation_account import VacationAccount +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Accounts(BaseModel): + """ + Accounts + """ # noqa: E501 + last_balance_date: Optional[date] = Field(description="date of last balance") + time_account: Optional[TimeAccount] = None + overtime_surcharge_accounts: Optional[List[OvertimeSurchargeAccounts]] = None + vacation_account: Optional[VacationAccount] = None + __properties: ClassVar[List[str]] = ["last_balance_date", "time_account", "overtime_surcharge_accounts", "vacation_account"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Accounts from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of time_account + if self.time_account: + _dict['time_account'] = self.time_account.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in overtime_surcharge_accounts (list) + _items = [] + if self.overtime_surcharge_accounts: + for _item_overtime_surcharge_accounts in self.overtime_surcharge_accounts: + if _item_overtime_surcharge_accounts: + _items.append(_item_overtime_surcharge_accounts.to_dict()) + _dict['overtime_surcharge_accounts'] = _items + # override the default output from pydantic by calling `to_dict()` of vacation_account + if self.vacation_account: + _dict['vacation_account'] = self.vacation_account.to_dict() + # set to None if last_balance_date (nullable) is None + # and model_fields_set contains the field + if self.last_balance_date is None and "last_balance_date" in self.model_fields_set: + _dict['last_balance_date'] = None + + # set to None if time_account (nullable) is None + # and model_fields_set contains the field + if self.time_account is None and "time_account" in self.model_fields_set: + _dict['time_account'] = None + + # set to None if overtime_surcharge_accounts (nullable) is None + # and model_fields_set contains the field + if self.overtime_surcharge_accounts is None and "overtime_surcharge_accounts" in self.model_fields_set: + _dict['overtime_surcharge_accounts'] = None + + # set to None if vacation_account (nullable) is None + # and model_fields_set contains the field + if self.vacation_account is None and "vacation_account" in self.model_fields_set: + _dict['vacation_account'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Accounts from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "last_balance_date": obj.get("last_balance_date"), + "time_account": TimeAccount.from_dict(obj["time_account"]) if obj.get("time_account") is not None else None, + "overtime_surcharge_accounts": [OvertimeSurchargeAccounts.from_dict(_item) for _item in obj["overtime_surcharge_accounts"]] if obj.get("overtime_surcharge_accounts") is not None else None, + "vacation_account": VacationAccount.from_dict(obj["vacation_account"]) if obj.get("vacation_account") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/break_time.py b/sdk/python/timr_api/models/break_time.py new file mode 100644 index 0000000..46a36f1 --- /dev/null +++ b/sdk/python/timr_api/models/break_time.py @@ -0,0 +1,175 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from timr_api.models.break_time_automatic import BreakTimeAutomatic +from timr_api.models.break_time_manual import BreakTimeManual +from timr_api.models.break_time_ongoing import BreakTimeOngoing +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +BREAKTIME_ONE_OF_SCHEMAS = ["BreakTimeAutomatic", "BreakTimeManual", "BreakTimeOngoing"] + +class BreakTime(BaseModel): + """ + BreakTime + """ + # data type: BreakTimeManual + oneof_schema_1_validator: Optional[BreakTimeManual] = None + # data type: BreakTimeOngoing + oneof_schema_2_validator: Optional[BreakTimeOngoing] = None + # data type: BreakTimeAutomatic + oneof_schema_3_validator: Optional[BreakTimeAutomatic] = None + actual_instance: Optional[Union[BreakTimeAutomatic, BreakTimeManual, BreakTimeOngoing]] = None + one_of_schemas: Set[str] = { "BreakTimeAutomatic", "BreakTimeManual", "BreakTimeOngoing" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + discriminator_value_class_map: Dict[str, str] = { + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = BreakTime.model_construct() + error_messages = [] + match = 0 + # validate data type: BreakTimeManual + if not isinstance(v, BreakTimeManual): + error_messages.append(f"Error! Input type `{type(v)}` is not `BreakTimeManual`") + else: + match += 1 + # validate data type: BreakTimeOngoing + if not isinstance(v, BreakTimeOngoing): + error_messages.append(f"Error! Input type `{type(v)}` is not `BreakTimeOngoing`") + else: + match += 1 + # validate data type: BreakTimeAutomatic + if not isinstance(v, BreakTimeAutomatic): + error_messages.append(f"Error! Input type `{type(v)}` is not `BreakTimeAutomatic`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in BreakTime with oneOf schemas: BreakTimeAutomatic, BreakTimeManual, BreakTimeOngoing. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in BreakTime with oneOf schemas: BreakTimeAutomatic, BreakTimeManual, BreakTimeOngoing. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # use oneOf discriminator to lookup the data type + _data_type = json.loads(json_str).get("type") + if not _data_type: + raise ValueError("Failed to lookup data type from the field `type` in the input.") + + # check if data type is `BreakTimeAutomatic` + if _data_type == "automatic": + instance.actual_instance = BreakTimeAutomatic.from_json(json_str) + return instance + + # check if data type is `BreakTimeManual` + if _data_type == "manual": + instance.actual_instance = BreakTimeManual.from_json(json_str) + return instance + + # check if data type is `BreakTimeOngoing` + if _data_type == "ongoing": + instance.actual_instance = BreakTimeOngoing.from_json(json_str) + return instance + + # deserialize data into BreakTimeManual + try: + instance.actual_instance = BreakTimeManual.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into BreakTimeOngoing + try: + instance.actual_instance = BreakTimeOngoing.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into BreakTimeAutomatic + try: + instance.actual_instance = BreakTimeAutomatic.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into BreakTime with oneOf schemas: BreakTimeAutomatic, BreakTimeManual, BreakTimeOngoing. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into BreakTime with oneOf schemas: BreakTimeAutomatic, BreakTimeManual, BreakTimeOngoing. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], BreakTimeAutomatic, BreakTimeManual, BreakTimeOngoing]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/sdk/python/timr_api/models/break_time_automatic.py b/sdk/python/timr_api/models/break_time_automatic.py new file mode 100644 index 0000000..593379a --- /dev/null +++ b/sdk/python/timr_api/models/break_time_automatic.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time_type import BreakTimeType +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class BreakTimeAutomatic(BaseModel): + """ + BreakTimeAutomatic + """ # noqa: E501 + type: BreakTimeType + duration_minutes: StrictInt = Field(description="Duration of break in minutes") + start: Optional[datetime] = Field(description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(description="RFC 3339 date-time (ISO-8601)") + __properties: ClassVar[List[str]] = ["type", "duration_minutes", "start", "end"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BreakTimeAutomatic from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if start (nullable) is None + # and model_fields_set contains the field + if self.start is None and "start" in self.model_fields_set: + _dict['start'] = None + + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BreakTimeAutomatic from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "duration_minutes": obj.get("duration_minutes"), + "start": obj.get("start"), + "end": obj.get("end") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/break_time_base.py b/sdk/python/timr_api/models/break_time_base.py new file mode 100644 index 0000000..d3c65c2 --- /dev/null +++ b/sdk/python/timr_api/models/break_time_base.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List +from timr_api.models.break_time_type import BreakTimeType +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class BreakTimeBase(BaseModel): + """ + Members shared by every kind of break time, including the discriminator. + """ # noqa: E501 + type: BreakTimeType + __properties: ClassVar[List[str]] = ["type"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BreakTimeBase from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BreakTimeBase from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/break_time_manual.py b/sdk/python/timr_api/models/break_time_manual.py new file mode 100644 index 0000000..502a402 --- /dev/null +++ b/sdk/python/timr_api/models/break_time_manual.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time_type import BreakTimeType +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class BreakTimeManual(BaseModel): + """ + BreakTimeManual + """ # noqa: E501 + type: BreakTimeType + duration_minutes: StrictInt = Field(description="Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given.") + start: Optional[datetime] = Field(default=None, description="start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes.") + end: Optional[datetime] = Field(default=None, description="start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes.") + __properties: ClassVar[List[str]] = ["type", "duration_minutes", "start", "end"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BreakTimeManual from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if start (nullable) is None + # and model_fields_set contains the field + if self.start is None and "start" in self.model_fields_set: + _dict['start'] = None + + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BreakTimeManual from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "duration_minutes": obj.get("duration_minutes"), + "start": obj.get("start"), + "end": obj.get("end") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/break_time_ongoing.py b/sdk/python/timr_api/models/break_time_ongoing.py new file mode 100644 index 0000000..e2fc5e6 --- /dev/null +++ b/sdk/python/timr_api/models/break_time_ongoing.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List +from timr_api.models.break_time_type import BreakTimeType +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class BreakTimeOngoing(BaseModel): + """ + BreakTimeOngoing + """ # noqa: E501 + type: BreakTimeType + start: datetime = Field(description="RFC 3339 date-time (ISO-8601)") + __properties: ClassVar[List[str]] = ["type", "start"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BreakTimeOngoing from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BreakTimeOngoing from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "start": obj.get("start") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/break_time_type.py b/sdk/python/timr_api/models/break_time_type.py new file mode 100644 index 0000000..8cefb06 --- /dev/null +++ b/sdk/python/timr_api/models/break_time_type.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class BreakTimeType(str, Enum): + """ + Kind of break. `manual` was entered by the user, `automatic` was deducted by timr, `ongoing` is a break that has started and not yet ended. + """ + + """ + allowed enum values + """ + MANUAL = 'manual' + ONGOING = 'ongoing' + AUTOMATIC = 'automatic' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of BreakTimeType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/break_time_update.py b/sdk/python/timr_api/models/break_time_update.py new file mode 100644 index 0000000..a8e374a --- /dev/null +++ b/sdk/python/timr_api/models/break_time_update.py @@ -0,0 +1,156 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from timr_api.models.break_time_manual import BreakTimeManual +from timr_api.models.break_time_ongoing import BreakTimeOngoing +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +BREAKTIMEUPDATE_ONE_OF_SCHEMAS = ["BreakTimeManual", "BreakTimeOngoing"] + +class BreakTimeUpdate(BaseModel): + """ + BreakTimeUpdate + """ + # data type: BreakTimeManual + oneof_schema_1_validator: Optional[BreakTimeManual] = None + # data type: BreakTimeOngoing + oneof_schema_2_validator: Optional[BreakTimeOngoing] = None + actual_instance: Optional[Union[BreakTimeManual, BreakTimeOngoing]] = None + one_of_schemas: Set[str] = { "BreakTimeManual", "BreakTimeOngoing" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + discriminator_value_class_map: Dict[str, str] = { + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = BreakTimeUpdate.model_construct() + error_messages = [] + match = 0 + # validate data type: BreakTimeManual + if not isinstance(v, BreakTimeManual): + error_messages.append(f"Error! Input type `{type(v)}` is not `BreakTimeManual`") + else: + match += 1 + # validate data type: BreakTimeOngoing + if not isinstance(v, BreakTimeOngoing): + error_messages.append(f"Error! Input type `{type(v)}` is not `BreakTimeOngoing`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in BreakTimeUpdate with oneOf schemas: BreakTimeManual, BreakTimeOngoing. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in BreakTimeUpdate with oneOf schemas: BreakTimeManual, BreakTimeOngoing. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # use oneOf discriminator to lookup the data type + _data_type = json.loads(json_str).get("type") + if not _data_type: + raise ValueError("Failed to lookup data type from the field `type` in the input.") + + # check if data type is `BreakTimeManual` + if _data_type == "manual": + instance.actual_instance = BreakTimeManual.from_json(json_str) + return instance + + # check if data type is `BreakTimeOngoing` + if _data_type == "ongoing": + instance.actual_instance = BreakTimeOngoing.from_json(json_str) + return instance + + # deserialize data into BreakTimeManual + try: + instance.actual_instance = BreakTimeManual.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into BreakTimeOngoing + try: + instance.actual_instance = BreakTimeOngoing.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into BreakTimeUpdate with oneOf schemas: BreakTimeManual, BreakTimeOngoing. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into BreakTimeUpdate with oneOf schemas: BreakTimeManual, BreakTimeOngoing. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], BreakTimeManual, BreakTimeOngoing]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/sdk/python/timr_api/models/budget_planning_type.py b/sdk/python/timr_api/models/budget_planning_type.py new file mode 100644 index 0000000..fe37822 --- /dev/null +++ b/sdk/python/timr_api/models/budget_planning_type.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class BudgetPlanningType(str, Enum): + """ + corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set for the remaining two types all budget properties are supported + """ + + """ + allowed enum values + """ + NONE = 'none' + TASK_HOURLY_RATE = 'task_hourly_rate' + USER_HOURLY_RATE = 'user_hourly_rate' + FIXED_PRICE = 'fixed_price' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of BudgetPlanningType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/budget_planning_type_request.py b/sdk/python/timr_api/models/budget_planning_type_request.py new file mode 100644 index 0000000..2b4fada --- /dev/null +++ b/sdk/python/timr_api/models/budget_planning_type_request.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class BudgetPlanningTypeRequest(str, Enum): + """ + corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set * inherited: budget settings are inherited from the parent task for the remaining two types all budget properties are supported + """ + + """ + allowed enum values + """ + NONE = 'none' + TASK_HOURLY_RATE = 'task_hourly_rate' + USER_HOURLY_RATE = 'user_hourly_rate' + FIXED_PRICE = 'fixed_price' + INHERITED = 'inherited' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of BudgetPlanningTypeRequest from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/car.py b/sdk/python/timr_api/models/car.py new file mode 100644 index 0000000..759cdef --- /dev/null +++ b/sdk/python/timr_api/models/car.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Car(BaseModel): + """ + A vehicle identified by `name` and license `plate`. `usable` says whether it can currently be selected. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + plate: StrictStr + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + usable: StrictBool + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["id", "name", "plate", "external_id", "usable", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Car from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Car from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "plate": obj.get("plate"), + "external_id": obj.get("external_id"), + "usable": obj.get("usable"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/car_create.py b/sdk/python/timr_api/models/car_create.py new file mode 100644 index 0000000..5efdb30 --- /dev/null +++ b/sdk/python/timr_api/models/car_create.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class CarCreate(BaseModel): + """ + CarCreate + """ # noqa: E501 + name: Annotated[str, Field(min_length=1, strict=True, max_length=191)] + plate: Annotated[str, Field(min_length=1, strict=True, max_length=191)] + external_id: Optional[StrictStr] = Field(default=None, description="Identifier of the corresponding object in an external system. Set and owned by the client.") + usable: Optional[StrictBool] = None + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["name", "plate", "external_id", "usable", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CarCreate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CarCreate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "plate": obj.get("plate"), + "external_id": obj.get("external_id"), + "usable": obj.get("usable"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/car_partial.py b/sdk/python/timr_api/models/car_partial.py new file mode 100644 index 0000000..990f6bb --- /dev/null +++ b/sdk/python/timr_api/models/car_partial.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class CarPartial(BaseModel): + """ + CarPartial + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + plate: StrictStr + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + __properties: ClassVar[List[str]] = ["id", "name", "plate", "external_id"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CarPartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CarPartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "plate": obj.get("plate"), + "external_id": obj.get("external_id") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/car_update.py b/sdk/python/timr_api/models/car_update.py new file mode 100644 index 0000000..5cd63fd --- /dev/null +++ b/sdk/python/timr_api/models/car_update.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class CarUpdate(BaseModel): + """ + CarUpdate + """ # noqa: E501 + name: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=191)]] = None + plate: Optional[Annotated[str, Field(min_length=1, strict=True, max_length=191)]] = None + external_id: Optional[StrictStr] = Field(default=None, description="Identifier of the corresponding object in an external system. Set and owned by the client.") + usable: Optional[StrictBool] = None + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["name", "plate", "external_id", "usable", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CarUpdate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CarUpdate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "plate": obj.get("plate"), + "external_id": obj.get("external_id"), + "usable": obj.get("usable"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/cars_page.py b/sdk/python/timr_api/models/cars_page.py new file mode 100644 index 0000000..c7d4247 --- /dev/null +++ b/sdk/python/timr_api/models/cars_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.car import Car +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class CarsPage(BaseModel): + """ + CarsPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[Car] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CarsPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CarsPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [Car.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/cars_sort_column.py b/sdk/python/timr_api/models/cars_sort_column.py new file mode 100644 index 0000000..5732f2a --- /dev/null +++ b/sdk/python/timr_api/models/cars_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class CarsSortColumn(str, Enum): + """ + Sort property for Cars. + """ + + """ + allowed enum values + """ + NAME = 'name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of CarsSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/daily_work_schedule.py b/sdk/python/timr_api/models/daily_work_schedule.py new file mode 100644 index 0000000..466821c --- /dev/null +++ b/sdk/python/timr_api/models/daily_work_schedule.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.normal_working_times import NormalWorkingTimes +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DailyWorkSchedule(BaseModel): + """ + DailyWorkSchedule + """ # noqa: E501 + target_duration_minutes: StrictInt = Field(description="value in minutes") + normal_working_times: Optional[List[NormalWorkingTimes]] = Field(default=None, description="this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set") + __properties: ClassVar[List[str]] = ["target_duration_minutes", "normal_working_times"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DailyWorkSchedule from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in normal_working_times (list) + _items = [] + if self.normal_working_times: + for _item_normal_working_times in self.normal_working_times: + if _item_normal_working_times: + _items.append(_item_normal_working_times.to_dict()) + _dict['normal_working_times'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DailyWorkSchedule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "target_duration_minutes": obj.get("target_duration_minutes"), + "normal_working_times": [NormalWorkingTimes.from_dict(_item) for _item in obj["normal_working_times"]] if obj.get("normal_working_times") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/deleted_entry_page.py b/sdk/python/timr_api/models/deleted_entry_page.py new file mode 100644 index 0000000..7841256 --- /dev/null +++ b/sdk/python/timr_api/models/deleted_entry_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.deleted_entry_partial import DeletedEntryPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DeletedEntryPage(BaseModel): + """ + DeletedEntryPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[DeletedEntryPartial] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DeletedEntryPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DeletedEntryPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [DeletedEntryPartial.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/deleted_entry_partial.py b/sdk/python/timr_api/models/deleted_entry_partial.py new file mode 100644 index 0000000..de51258 --- /dev/null +++ b/sdk/python/timr_api/models/deleted_entry_partial.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.user_partial import UserPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DeletedEntryPartial(BaseModel): + """ + DeletedEntryPartial + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + last_modified: datetime = Field(description="Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) ") + last_modified_by: Optional[UserPartial] = Field(description="Read-only. The User who last modified the entry, or null if the change was not made in a user context. ") + __properties: ClassVar[List[str]] = ["id", "last_modified", "last_modified_by"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DeletedEntryPartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of last_modified_by + if self.last_modified_by: + _dict['last_modified_by'] = self.last_modified_by.to_dict() + # set to None if last_modified_by (nullable) is None + # and model_fields_set contains the field + if self.last_modified_by is None and "last_modified_by" in self.model_fields_set: + _dict['last_modified_by'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DeletedEntryPartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "last_modified": obj.get("last_modified"), + "last_modified_by": UserPartial.from_dict(obj["last_modified_by"]) if obj.get("last_modified_by") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/deleted_entry_sort_column.py b/sdk/python/timr_api/models/deleted_entry_sort_column.py new file mode 100644 index 0000000..08b1d09 --- /dev/null +++ b/sdk/python/timr_api/models/deleted_entry_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class DeletedEntrySortColumn(str, Enum): + """ + Sort property for deleted entries. + """ + + """ + allowed enum values + """ + LAST_MODIFIED = 'last_modified' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DeletedEntrySortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/deleted_entry_with_metadata.py b/sdk/python/timr_api/models/deleted_entry_with_metadata.py new file mode 100644 index 0000000..ad03413 --- /dev/null +++ b/sdk/python/timr_api/models/deleted_entry_with_metadata.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.user_partial import UserPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DeletedEntryWithMetadata(BaseModel): + """ + DeletedEntryWithMetadata + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + last_modified: datetime = Field(description="Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) ") + last_modified_by: Optional[UserPartial] = Field(description="Read-only. The User who last modified the entry, or null if the change was not made in a user context. ") + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["id", "last_modified", "last_modified_by", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DeletedEntryWithMetadata from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of last_modified_by + if self.last_modified_by: + _dict['last_modified_by'] = self.last_modified_by.to_dict() + # set to None if last_modified_by (nullable) is None + # and model_fields_set contains the field + if self.last_modified_by is None and "last_modified_by" in self.model_fields_set: + _dict['last_modified_by'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DeletedEntryWithMetadata from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "last_modified": obj.get("last_modified"), + "last_modified_by": UserPartial.from_dict(obj["last_modified_by"]) if obj.get("last_modified_by") is not None else None, + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/deleted_entry_with_metadata_page.py b/sdk/python/timr_api/models/deleted_entry_with_metadata_page.py new file mode 100644 index 0000000..2538f1a --- /dev/null +++ b/sdk/python/timr_api/models/deleted_entry_with_metadata_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.deleted_entry_with_metadata import DeletedEntryWithMetadata +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DeletedEntryWithMetadataPage(BaseModel): + """ + DeletedEntryWithMetadataPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[DeletedEntryWithMetadata] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DeletedEntryWithMetadataPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DeletedEntryWithMetadataPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [DeletedEntryWithMetadata.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/drive_log.py b/sdk/python/timr_api/models/drive_log.py new file mode 100644 index 0000000..ab0a376 --- /dev/null +++ b/sdk/python/timr_api/models/drive_log.py @@ -0,0 +1,248 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.car_partial import CarPartial +from timr_api.models.drive_log_category_partial import DriveLogCategoryPartial +from timr_api.models.drive_log_status import DriveLogStatus +from timr_api.models.duration import Duration +from timr_api.models.location import Location +from timr_api.models.platform import Platform +from timr_api.models.user_partial import UserPartial +from timr_api.models.venue_partial import VenuePartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DriveLog(BaseModel): + """ + One trip in a `car`: `start` and `end`, `start_mileage` and `end_mileage` with the resulting `distance`, the `purpose`, the places `visited`, and its `drive_log_category`. May include a recorded GPS `route`. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + start: datetime = Field(description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(description="RFC 3339 date-time (ISO-8601)") + duration: Optional[Duration] + changed: StrictBool + start_mileage: StrictInt + end_mileage: Optional[StrictInt] + distance: Optional[StrictInt] = Field(description="Driven distance in kilometers") + route: Optional[StrictStr] + purpose: Optional[StrictStr] + visited: Optional[StrictStr] + user: UserPartial + car: CarPartial + drive_log_category: DriveLogCategoryPartial + start_venue: Optional[VenuePartial] + end_venue: Optional[VenuePartial] + has_track: StrictBool + start_location: Optional[Location] + end_location: Optional[Location] + start_platform: Optional[Platform] + end_platform: Optional[Platform] + last_modified: datetime = Field(description="Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) ") + last_modified_by: Optional[UserPartial] = Field(description="Read-only. The User who last modified the entry, or null if the change was not made in a user context. ") + status: DriveLogStatus + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["id", "start", "end", "duration", "changed", "start_mileage", "end_mileage", "distance", "route", "purpose", "visited", "user", "car", "drive_log_category", "start_venue", "end_venue", "has_track", "start_location", "end_location", "start_platform", "end_platform", "last_modified", "last_modified_by", "status", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DriveLog from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of duration + if self.duration: + _dict['duration'] = self.duration.to_dict() + # override the default output from pydantic by calling `to_dict()` of user + if self.user: + _dict['user'] = self.user.to_dict() + # override the default output from pydantic by calling `to_dict()` of car + if self.car: + _dict['car'] = self.car.to_dict() + # override the default output from pydantic by calling `to_dict()` of drive_log_category + if self.drive_log_category: + _dict['drive_log_category'] = self.drive_log_category.to_dict() + # override the default output from pydantic by calling `to_dict()` of start_venue + if self.start_venue: + _dict['start_venue'] = self.start_venue.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_venue + if self.end_venue: + _dict['end_venue'] = self.end_venue.to_dict() + # override the default output from pydantic by calling `to_dict()` of start_location + if self.start_location: + _dict['start_location'] = self.start_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_location + if self.end_location: + _dict['end_location'] = self.end_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of last_modified_by + if self.last_modified_by: + _dict['last_modified_by'] = self.last_modified_by.to_dict() + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if duration (nullable) is None + # and model_fields_set contains the field + if self.duration is None and "duration" in self.model_fields_set: + _dict['duration'] = None + + # set to None if end_mileage (nullable) is None + # and model_fields_set contains the field + if self.end_mileage is None and "end_mileage" in self.model_fields_set: + _dict['end_mileage'] = None + + # set to None if distance (nullable) is None + # and model_fields_set contains the field + if self.distance is None and "distance" in self.model_fields_set: + _dict['distance'] = None + + # set to None if route (nullable) is None + # and model_fields_set contains the field + if self.route is None and "route" in self.model_fields_set: + _dict['route'] = None + + # set to None if purpose (nullable) is None + # and model_fields_set contains the field + if self.purpose is None and "purpose" in self.model_fields_set: + _dict['purpose'] = None + + # set to None if visited (nullable) is None + # and model_fields_set contains the field + if self.visited is None and "visited" in self.model_fields_set: + _dict['visited'] = None + + # set to None if start_venue (nullable) is None + # and model_fields_set contains the field + if self.start_venue is None and "start_venue" in self.model_fields_set: + _dict['start_venue'] = None + + # set to None if end_venue (nullable) is None + # and model_fields_set contains the field + if self.end_venue is None and "end_venue" in self.model_fields_set: + _dict['end_venue'] = None + + # set to None if start_location (nullable) is None + # and model_fields_set contains the field + if self.start_location is None and "start_location" in self.model_fields_set: + _dict['start_location'] = None + + # set to None if end_location (nullable) is None + # and model_fields_set contains the field + if self.end_location is None and "end_location" in self.model_fields_set: + _dict['end_location'] = None + + # set to None if start_platform (nullable) is None + # and model_fields_set contains the field + if self.start_platform is None and "start_platform" in self.model_fields_set: + _dict['start_platform'] = None + + # set to None if end_platform (nullable) is None + # and model_fields_set contains the field + if self.end_platform is None and "end_platform" in self.model_fields_set: + _dict['end_platform'] = None + + # set to None if last_modified_by (nullable) is None + # and model_fields_set contains the field + if self.last_modified_by is None and "last_modified_by" in self.model_fields_set: + _dict['last_modified_by'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DriveLog from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "start": obj.get("start"), + "end": obj.get("end"), + "duration": Duration.from_dict(obj["duration"]) if obj.get("duration") is not None else None, + "changed": obj.get("changed"), + "start_mileage": obj.get("start_mileage"), + "end_mileage": obj.get("end_mileage"), + "distance": obj.get("distance"), + "route": obj.get("route"), + "purpose": obj.get("purpose"), + "visited": obj.get("visited"), + "user": UserPartial.from_dict(obj["user"]) if obj.get("user") is not None else None, + "car": CarPartial.from_dict(obj["car"]) if obj.get("car") is not None else None, + "drive_log_category": DriveLogCategoryPartial.from_dict(obj["drive_log_category"]) if obj.get("drive_log_category") is not None else None, + "start_venue": VenuePartial.from_dict(obj["start_venue"]) if obj.get("start_venue") is not None else None, + "end_venue": VenuePartial.from_dict(obj["end_venue"]) if obj.get("end_venue") is not None else None, + "has_track": obj.get("has_track"), + "start_location": Location.from_dict(obj["start_location"]) if obj.get("start_location") is not None else None, + "end_location": Location.from_dict(obj["end_location"]) if obj.get("end_location") is not None else None, + "start_platform": obj.get("start_platform"), + "end_platform": obj.get("end_platform"), + "last_modified": obj.get("last_modified"), + "last_modified_by": UserPartial.from_dict(obj["last_modified_by"]) if obj.get("last_modified_by") is not None else None, + "status": obj.get("status"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/drive_log_categories_page.py b/sdk/python/timr_api/models/drive_log_categories_page.py new file mode 100644 index 0000000..6d6646f --- /dev/null +++ b/sdk/python/timr_api/models/drive_log_categories_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.drive_log_category import DriveLogCategory +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DriveLogCategoriesPage(BaseModel): + """ + DriveLogCategoriesPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[DriveLogCategory] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DriveLogCategoriesPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DriveLogCategoriesPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [DriveLogCategory.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/drive_log_categories_sort_column.py b/sdk/python/timr_api/models/drive_log_categories_sort_column.py new file mode 100644 index 0000000..fcd3c05 --- /dev/null +++ b/sdk/python/timr_api/models/drive_log_categories_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class DriveLogCategoriesSortColumn(str, Enum): + """ + Sort property for Drive Log Categories. + """ + + """ + allowed enum values + """ + NAME = 'name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DriveLogCategoriesSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/drive_log_category.py b/sdk/python/timr_api/models/drive_log_category.py new file mode 100644 index 0000000..015e920 --- /dev/null +++ b/sdk/python/timr_api/models/drive_log_category.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.user_partial import UserPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DriveLogCategory(BaseModel): + """ + A drive log category with a `name` and a display `color`; `business` marks it as business travel. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + business: StrictBool + color: StrictStr + last_modified: datetime = Field(description="Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) ") + last_modified_by: Optional[UserPartial] = Field(description="Read-only. The User who last modified the entry, or null if the change was not made in a user context. ") + __properties: ClassVar[List[str]] = ["id", "name", "business", "color", "last_modified", "last_modified_by"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DriveLogCategory from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of last_modified_by + if self.last_modified_by: + _dict['last_modified_by'] = self.last_modified_by.to_dict() + # set to None if last_modified_by (nullable) is None + # and model_fields_set contains the field + if self.last_modified_by is None and "last_modified_by" in self.model_fields_set: + _dict['last_modified_by'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DriveLogCategory from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "business": obj.get("business"), + "color": obj.get("color"), + "last_modified": obj.get("last_modified"), + "last_modified_by": UserPartial.from_dict(obj["last_modified_by"]) if obj.get("last_modified_by") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/drive_log_category_partial.py b/sdk/python/timr_api/models/drive_log_category_partial.py new file mode 100644 index 0000000..e7458d7 --- /dev/null +++ b/sdk/python/timr_api/models/drive_log_category_partial.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DriveLogCategoryPartial(BaseModel): + """ + DriveLogCategoryPartial + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + business: StrictBool + color: StrictStr + __properties: ClassVar[List[str]] = ["id", "name", "business", "color"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DriveLogCategoryPartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DriveLogCategoryPartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "business": obj.get("business"), + "color": obj.get("color") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/drive_log_create.py b/sdk/python/timr_api/models/drive_log_create.py new file mode 100644 index 0000000..2f5095d --- /dev/null +++ b/sdk/python/timr_api/models/drive_log_create.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.drive_log_status import DriveLogStatus +from timr_api.models.location_create import LocationCreate +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DriveLogCreate(BaseModel): + """ + DriveLogCreate + """ # noqa: E501 + start: datetime = Field(description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + changed: StrictBool + start_mileage: StrictInt + end_mileage: Optional[StrictInt] = None + route: Optional[StrictStr] = None + purpose: Optional[StrictStr] = None + visited: Optional[StrictStr] = None + drive_log_category_id: StrictStr + status: DriveLogStatus + metadata: Optional[Dict[str, Any]] = None + user_id: StrictStr + car_id: StrictStr + start_location: Optional[LocationCreate] = None + end_location: Optional[LocationCreate] = None + __properties: ClassVar[List[str]] = ["start", "end", "changed", "start_mileage", "end_mileage", "route", "purpose", "visited", "drive_log_category_id", "status", "metadata", "user_id", "car_id", "start_location", "end_location"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DriveLogCreate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of start_location + if self.start_location: + _dict['start_location'] = self.start_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_location + if self.end_location: + _dict['end_location'] = self.end_location.to_dict() + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if end_mileage (nullable) is None + # and model_fields_set contains the field + if self.end_mileage is None and "end_mileage" in self.model_fields_set: + _dict['end_mileage'] = None + + # set to None if route (nullable) is None + # and model_fields_set contains the field + if self.route is None and "route" in self.model_fields_set: + _dict['route'] = None + + # set to None if purpose (nullable) is None + # and model_fields_set contains the field + if self.purpose is None and "purpose" in self.model_fields_set: + _dict['purpose'] = None + + # set to None if visited (nullable) is None + # and model_fields_set contains the field + if self.visited is None and "visited" in self.model_fields_set: + _dict['visited'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + # set to None if start_location (nullable) is None + # and model_fields_set contains the field + if self.start_location is None and "start_location" in self.model_fields_set: + _dict['start_location'] = None + + # set to None if end_location (nullable) is None + # and model_fields_set contains the field + if self.end_location is None and "end_location" in self.model_fields_set: + _dict['end_location'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DriveLogCreate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end"), + "changed": obj.get("changed"), + "start_mileage": obj.get("start_mileage"), + "end_mileage": obj.get("end_mileage"), + "route": obj.get("route"), + "purpose": obj.get("purpose"), + "visited": obj.get("visited"), + "drive_log_category_id": obj.get("drive_log_category_id"), + "status": obj.get("status"), + "metadata": obj.get("metadata"), + "user_id": obj.get("user_id"), + "car_id": obj.get("car_id"), + "start_location": LocationCreate.from_dict(obj["start_location"]) if obj.get("start_location") is not None else None, + "end_location": LocationCreate.from_dict(obj["end_location"]) if obj.get("end_location") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/drive_log_status.py b/sdk/python/timr_api/models/drive_log_status.py new file mode 100644 index 0000000..209884d --- /dev/null +++ b/sdk/python/timr_api/models/drive_log_status.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class DriveLogStatus(str, Enum): + """ + Processing state of a Drive Log. `running` means the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + """ + + """ + allowed enum values + """ + CHANGEABLE = 'changeable' + LOCKED = 'locked' + APPROVED = 'approved' + CLEARED = 'cleared' + CLOSED = 'closed' + ARCHIVED = 'archived' + RUNNING = 'running' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DriveLogStatus from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/drive_log_update.py b/sdk/python/timr_api/models/drive_log_update.py new file mode 100644 index 0000000..c1d5697 --- /dev/null +++ b/sdk/python/timr_api/models/drive_log_update.py @@ -0,0 +1,162 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.drive_log_status import DriveLogStatus +from timr_api.models.location_update import LocationUpdate +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DriveLogUpdate(BaseModel): + """ + DriveLogUpdate + """ # noqa: E501 + start: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + changed: Optional[StrictBool] = None + start_mileage: Optional[StrictInt] = None + end_mileage: Optional[StrictInt] = None + route: Optional[StrictStr] = None + purpose: Optional[StrictStr] = None + visited: Optional[StrictStr] = None + drive_log_category_id: Optional[StrictStr] = None + status: Optional[DriveLogStatus] = None + metadata: Optional[Dict[str, Any]] = None + start_location: Optional[LocationUpdate] = None + end_location: Optional[LocationUpdate] = None + __properties: ClassVar[List[str]] = ["start", "end", "changed", "start_mileage", "end_mileage", "route", "purpose", "visited", "drive_log_category_id", "status", "metadata", "start_location", "end_location"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DriveLogUpdate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of start_location + if self.start_location: + _dict['start_location'] = self.start_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_location + if self.end_location: + _dict['end_location'] = self.end_location.to_dict() + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if end_mileage (nullable) is None + # and model_fields_set contains the field + if self.end_mileage is None and "end_mileage" in self.model_fields_set: + _dict['end_mileage'] = None + + # set to None if route (nullable) is None + # and model_fields_set contains the field + if self.route is None and "route" in self.model_fields_set: + _dict['route'] = None + + # set to None if purpose (nullable) is None + # and model_fields_set contains the field + if self.purpose is None and "purpose" in self.model_fields_set: + _dict['purpose'] = None + + # set to None if visited (nullable) is None + # and model_fields_set contains the field + if self.visited is None and "visited" in self.model_fields_set: + _dict['visited'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + # set to None if start_location (nullable) is None + # and model_fields_set contains the field + if self.start_location is None and "start_location" in self.model_fields_set: + _dict['start_location'] = None + + # set to None if end_location (nullable) is None + # and model_fields_set contains the field + if self.end_location is None and "end_location" in self.model_fields_set: + _dict['end_location'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DriveLogUpdate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end"), + "changed": obj.get("changed"), + "start_mileage": obj.get("start_mileage"), + "end_mileage": obj.get("end_mileage"), + "route": obj.get("route"), + "purpose": obj.get("purpose"), + "visited": obj.get("visited"), + "drive_log_category_id": obj.get("drive_log_category_id"), + "status": obj.get("status"), + "metadata": obj.get("metadata"), + "start_location": LocationUpdate.from_dict(obj["start_location"]) if obj.get("start_location") is not None else None, + "end_location": LocationUpdate.from_dict(obj["end_location"]) if obj.get("end_location") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/drive_log_upsert.py b/sdk/python/timr_api/models/drive_log_upsert.py new file mode 100644 index 0000000..9fe5f26 --- /dev/null +++ b/sdk/python/timr_api/models/drive_log_upsert.py @@ -0,0 +1,141 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.drive_log_status import DriveLogStatus +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DriveLogUpsert(BaseModel): + """ + DriveLogUpsert + """ # noqa: E501 + start: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + changed: Optional[StrictBool] = None + start_mileage: Optional[StrictInt] = None + end_mileage: Optional[StrictInt] = None + route: Optional[StrictStr] = None + purpose: Optional[StrictStr] = None + visited: Optional[StrictStr] = None + drive_log_category_id: Optional[StrictStr] = None + status: Optional[DriveLogStatus] = None + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["start", "end", "changed", "start_mileage", "end_mileage", "route", "purpose", "visited", "drive_log_category_id", "status", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DriveLogUpsert from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if end_mileage (nullable) is None + # and model_fields_set contains the field + if self.end_mileage is None and "end_mileage" in self.model_fields_set: + _dict['end_mileage'] = None + + # set to None if route (nullable) is None + # and model_fields_set contains the field + if self.route is None and "route" in self.model_fields_set: + _dict['route'] = None + + # set to None if purpose (nullable) is None + # and model_fields_set contains the field + if self.purpose is None and "purpose" in self.model_fields_set: + _dict['purpose'] = None + + # set to None if visited (nullable) is None + # and model_fields_set contains the field + if self.visited is None and "visited" in self.model_fields_set: + _dict['visited'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DriveLogUpsert from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end"), + "changed": obj.get("changed"), + "start_mileage": obj.get("start_mileage"), + "end_mileage": obj.get("end_mileage"), + "route": obj.get("route"), + "purpose": obj.get("purpose"), + "visited": obj.get("visited"), + "drive_log_category_id": obj.get("drive_log_category_id"), + "status": obj.get("status"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/drive_logs_page.py b/sdk/python/timr_api/models/drive_logs_page.py new file mode 100644 index 0000000..629f835 --- /dev/null +++ b/sdk/python/timr_api/models/drive_logs_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.drive_log import DriveLog +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class DriveLogsPage(BaseModel): + """ + DriveLogsPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[DriveLog] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DriveLogsPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DriveLogsPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [DriveLog.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/drive_logs_sort_column.py b/sdk/python/timr_api/models/drive_logs_sort_column.py new file mode 100644 index 0000000..b2d45ca --- /dev/null +++ b/sdk/python/timr_api/models/drive_logs_sort_column.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class DriveLogsSortColumn(str, Enum): + """ + Sort property for Drive Logs. + """ + + """ + allowed enum values + """ + START = 'start' + LAST_MODIFIED = 'last_modified' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DriveLogsSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/duration.py b/sdk/python/timr_api/models/duration.py new file mode 100644 index 0000000..0d4474c --- /dev/null +++ b/sdk/python/timr_api/models/duration.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List +from timr_api.models.duration_type import DurationType +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Duration(BaseModel): + """ + Duration + """ # noqa: E501 + type: DurationType + minutes: StrictInt = Field(description="Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User ") + minutes_rounded: StrictInt = Field(description="Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User ") + __properties: ClassVar[List[str]] = ["type", "minutes", "minutes_rounded"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Duration from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Duration from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "minutes": obj.get("minutes"), + "minutes_rounded": obj.get("minutes_rounded") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/duration_type.py b/sdk/python/timr_api/models/duration_type.py new file mode 100644 index 0000000..e7d4e37 --- /dev/null +++ b/sdk/python/timr_api/models/duration_type.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class DurationType(str, Enum): + """ + How the duration of a single recording is expressed. Not to be confused with `DurationUnit`, which states the unit a Working Time Type is recorded in. + """ + + """ + allowed enum values + """ + MINUTES = 'minutes' + FULL_DAY = 'full_day' + HALF_DAY = 'half_day' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DurationType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/duration_unit.py b/sdk/python/timr_api/models/duration_unit.py new file mode 100644 index 0000000..3007d26 --- /dev/null +++ b/sdk/python/timr_api/models/duration_unit.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class DurationUnit(str, Enum): + """ + Unit a Working Time Type is recorded in. Not to be confused with `DurationType`, which states how an individual recording's duration is expressed. + """ + + """ + allowed enum values + """ + MINUTES = 'minutes' + HALF_DAYS = 'half_days' + DAYS = 'days' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DurationUnit from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/error.py b/sdk/python/timr_api/models/error.py new file mode 100644 index 0000000..8f5784a --- /dev/null +++ b/sdk/python/timr_api/models/error.py @@ -0,0 +1,122 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.error_entry import ErrorEntry +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Error(BaseModel): + """ + TIMR error response body, extending the Problem Details base with `timestamp`, `trace_id` and per-field `errors[]` for validation, binding, constraint, request-body deserialization, and reference-not-found errors. The semantic identifier is encoded in the `type` URI (e.g. `https://errors.timr.com/conflict/resource-outdated`). Slugs in the `type` URI are lowercase kebab-case: a top-level category (`validation`, `reference-not-found`, `conflict`, `forbidden`, `internal`) optionally followed by a specific sub-slug (`conflict/resource-outdated`, `validation/end-time-required`, `reference-not-found/user`). + """ # noqa: E501 + type: StrictStr + title: StrictStr + status: StrictInt + detail: Optional[StrictStr] = None + instance: Optional[StrictStr] = None + timestamp: datetime + trace_id: Optional[StrictStr] = None + errors: Optional[List[ErrorEntry]] = None + __properties: ClassVar[List[str]] = ["type", "title", "status", "detail", "instance", "timestamp", "trace_id", "errors"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Error from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in errors (list) + _items = [] + if self.errors: + for _item_errors in self.errors: + if _item_errors: + _items.append(_item_errors.to_dict()) + _dict['errors'] = _items + # set to None if trace_id (nullable) is None + # and model_fields_set contains the field + if self.trace_id is None and "trace_id" in self.model_fields_set: + _dict['trace_id'] = None + + # set to None if errors (nullable) is None + # and model_fields_set contains the field + if self.errors is None and "errors" in self.model_fields_set: + _dict['errors'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Error from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "title": obj.get("title"), + "status": obj.get("status"), + "detail": obj.get("detail"), + "instance": obj.get("instance"), + "timestamp": obj.get("timestamp"), + "trace_id": obj.get("trace_id"), + "errors": [ErrorEntry.from_dict(_item) for _item in obj["errors"]] if obj.get("errors") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/error_entry.py b/sdk/python/timr_api/models/error_entry.py new file mode 100644 index 0000000..3a82574 --- /dev/null +++ b/sdk/python/timr_api/models/error_entry.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class ErrorEntry(BaseModel): + """ + Field-level or sub-error entry, shaped like a sub-ProblemDetail. The `type` URI identifies the specific constraint or sub-error category (e.g. `validation/not-null` for a Bean Validation `@NotNull`, `validation/paused-working-time` for a TIMR custom validator code, `validation/type-mismatch` for a value that does not fit its target type, `validation/unknown-property` for a property the resource does not declare, `reference-not-found/user` for a `MappingException`). `field` is the JSONPath of the offending property in the request body, rooted at `$` — array elements included. An error about a query parameter names it plainly instead, without the `$.` prefix. + """ # noqa: E501 + type: StrictStr + var_field: Optional[StrictStr] = Field(default=None, alias="field") + detail: StrictStr + __properties: ClassVar[List[str]] = ["type", "field", "detail"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ErrorEntry from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if var_field (nullable) is None + # and model_fields_set contains the field + if self.var_field is None and "var_field" in self.model_fields_set: + _dict['field'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ErrorEntry from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "field": obj.get("field"), + "detail": obj.get("detail") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/flex_time_indicator.py b/sdk/python/timr_api/models/flex_time_indicator.py new file mode 100644 index 0000000..ec62bb2 --- /dev/null +++ b/sdk/python/timr_api/models/flex_time_indicator.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class FlexTimeIndicator(str, Enum): + """ + Traffic-light rating of the flex time balance. The thresholds are an account setting and are not part of this contract. + """ + + """ + allowed enum values + """ + GREEN = 'green' + YELLOW = 'yellow' + RED = 'red' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of FlexTimeIndicator from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/holiday.py b/sdk/python/timr_api/models/holiday.py new file mode 100644 index 0000000..b03f679 --- /dev/null +++ b/sdk/python/timr_api/models/holiday.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Holiday(BaseModel): + """ + Holiday + """ # noqa: E501 + var_date: date = Field(description="RFC 3339 date (ISO-8601)", alias="date") + description: StrictStr + half_day: StrictBool + __properties: ClassVar[List[str]] = ["date", "description", "half_day"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Holiday from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Holiday from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "date": obj.get("date"), + "description": obj.get("description"), + "half_day": obj.get("half_day") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/holiday_calendar_partial.py b/sdk/python/timr_api/models/holiday_calendar_partial.py new file mode 100644 index 0000000..3622678 --- /dev/null +++ b/sdk/python/timr_api/models/holiday_calendar_partial.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HolidayCalendarPartial(BaseModel): + """ + A holiday calendar. Its holidays are either generated automatically or maintained manually. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + description: StrictStr + __properties: ClassVar[List[str]] = ["id", "description"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HolidayCalendarPartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HolidayCalendarPartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "description": obj.get("description") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/holiday_calendars_page.py b/sdk/python/timr_api/models/holiday_calendars_page.py new file mode 100644 index 0000000..ba03f1c --- /dev/null +++ b/sdk/python/timr_api/models/holiday_calendars_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.holiday_calendar_partial import HolidayCalendarPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HolidayCalendarsPage(BaseModel): + """ + HolidayCalendarsPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[HolidayCalendarPartial] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HolidayCalendarsPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HolidayCalendarsPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [HolidayCalendarPartial.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/holiday_calendars_sort_column.py b/sdk/python/timr_api/models/holiday_calendars_sort_column.py new file mode 100644 index 0000000..624419a --- /dev/null +++ b/sdk/python/timr_api/models/holiday_calendars_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class HolidayCalendarsSortColumn(str, Enum): + """ + Sort property for Holiday Calendars. + """ + + """ + allowed enum values + """ + DESCRIPTION = 'description' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of HolidayCalendarsSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/holidays_page.py b/sdk/python/timr_api/models/holidays_page.py new file mode 100644 index 0000000..d450931 --- /dev/null +++ b/sdk/python/timr_api/models/holidays_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.holiday import Holiday +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class HolidaysPage(BaseModel): + """ + HolidaysPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[Holiday] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HolidaysPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HolidaysPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [Holiday.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/holidays_sort_column.py b/sdk/python/timr_api/models/holidays_sort_column.py new file mode 100644 index 0000000..c404476 --- /dev/null +++ b/sdk/python/timr_api/models/holidays_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class HolidaysSortColumn(str, Enum): + """ + Sort property for Holidays. + """ + + """ + allowed enum values + """ + DATE = 'date' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of HolidaysSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/location.py b/sdk/python/timr_api/models/location.py new file mode 100644 index 0000000..a297d51 --- /dev/null +++ b/sdk/python/timr_api/models/location.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Location(BaseModel): + """ + Location + """ # noqa: E501 + lat: Optional[Union[StrictFloat, StrictInt]] = Field(description="Latitude in decimal degrees.") + lon: Optional[Union[StrictFloat, StrictInt]] = Field(description="Longitude in decimal degrees.") + timestamp: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + formatted_address: Optional[StrictStr] = None + accuracy: Optional[Union[StrictFloat, StrictInt]] = Field(description="Horizontal GPS accuracy in meters.") + __properties: ClassVar[List[str]] = ["lat", "lon", "timestamp", "formatted_address", "accuracy"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Location from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if lat (nullable) is None + # and model_fields_set contains the field + if self.lat is None and "lat" in self.model_fields_set: + _dict['lat'] = None + + # set to None if lon (nullable) is None + # and model_fields_set contains the field + if self.lon is None and "lon" in self.model_fields_set: + _dict['lon'] = None + + # set to None if timestamp (nullable) is None + # and model_fields_set contains the field + if self.timestamp is None and "timestamp" in self.model_fields_set: + _dict['timestamp'] = None + + # set to None if formatted_address (nullable) is None + # and model_fields_set contains the field + if self.formatted_address is None and "formatted_address" in self.model_fields_set: + _dict['formatted_address'] = None + + # set to None if accuracy (nullable) is None + # and model_fields_set contains the field + if self.accuracy is None and "accuracy" in self.model_fields_set: + _dict['accuracy'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Location from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "lat": obj.get("lat"), + "lon": obj.get("lon"), + "timestamp": obj.get("timestamp"), + "formatted_address": obj.get("formatted_address"), + "accuracy": obj.get("accuracy") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/location_create.py b/sdk/python/timr_api/models/location_create.py new file mode 100644 index 0000000..95cfb1b --- /dev/null +++ b/sdk/python/timr_api/models/location_create.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class LocationCreate(BaseModel): + """ + LocationCreate + """ # noqa: E501 + lat: Union[StrictFloat, StrictInt] = Field(description="Latitude in decimal degrees.") + lon: Union[StrictFloat, StrictInt] = Field(description="Longitude in decimal degrees.") + timestamp: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + formatted_address: Optional[StrictStr] = None + accuracy: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Horizontal GPS accuracy in meters.") + __properties: ClassVar[List[str]] = ["lat", "lon", "timestamp", "formatted_address", "accuracy"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of LocationCreate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if timestamp (nullable) is None + # and model_fields_set contains the field + if self.timestamp is None and "timestamp" in self.model_fields_set: + _dict['timestamp'] = None + + # set to None if formatted_address (nullable) is None + # and model_fields_set contains the field + if self.formatted_address is None and "formatted_address" in self.model_fields_set: + _dict['formatted_address'] = None + + # set to None if accuracy (nullable) is None + # and model_fields_set contains the field + if self.accuracy is None and "accuracy" in self.model_fields_set: + _dict['accuracy'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of LocationCreate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "lat": obj.get("lat"), + "lon": obj.get("lon"), + "timestamp": obj.get("timestamp"), + "formatted_address": obj.get("formatted_address"), + "accuracy": obj.get("accuracy") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/location_update.py b/sdk/python/timr_api/models/location_update.py new file mode 100644 index 0000000..b2abd46 --- /dev/null +++ b/sdk/python/timr_api/models/location_update.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class LocationUpdate(BaseModel): + """ + LocationUpdate + """ # noqa: E501 + lat: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Latitude in decimal degrees.") + lon: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Longitude in decimal degrees.") + timestamp: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + formatted_address: Optional[StrictStr] = None + accuracy: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Horizontal GPS accuracy in meters.") + __properties: ClassVar[List[str]] = ["lat", "lon", "timestamp", "formatted_address", "accuracy"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of LocationUpdate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if timestamp (nullable) is None + # and model_fields_set contains the field + if self.timestamp is None and "timestamp" in self.model_fields_set: + _dict['timestamp'] = None + + # set to None if formatted_address (nullable) is None + # and model_fields_set contains the field + if self.formatted_address is None and "formatted_address" in self.model_fields_set: + _dict['formatted_address'] = None + + # set to None if accuracy (nullable) is None + # and model_fields_set contains the field + if self.accuracy is None and "accuracy" in self.model_fields_set: + _dict['accuracy'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of LocationUpdate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "lat": obj.get("lat"), + "lon": obj.get("lon"), + "timestamp": obj.get("timestamp"), + "formatted_address": obj.get("formatted_address"), + "accuracy": obj.get("accuracy") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/normal_working_times.py b/sdk/python/timr_api/models/normal_working_times.py new file mode 100644 index 0000000..491420a --- /dev/null +++ b/sdk/python/timr_api/models/normal_working_times.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class NormalWorkingTimes(BaseModel): + """ + NormalWorkingTimes + """ # noqa: E501 + start: Optional[StrictStr] = None + end: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["start", "end"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of NormalWorkingTimes from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if start (nullable) is None + # and model_fields_set contains the field + if self.start is None and "start" in self.model_fields_set: + _dict['start'] = None + + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of NormalWorkingTimes from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/overtime_surcharge_account.py b/sdk/python/timr_api/models/overtime_surcharge_account.py new file mode 100644 index 0000000..8b5d62a --- /dev/null +++ b/sdk/python/timr_api/models/overtime_surcharge_account.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class OvertimeSurchargeAccount(BaseModel): + """ + OvertimeSurchargeAccount + """ # noqa: E501 + balance_last_period_minutes: Optional[StrictInt] + new_minutes: Optional[StrictInt] + balance_total_minutes: Optional[StrictInt] + __properties: ClassVar[List[str]] = ["balance_last_period_minutes", "new_minutes", "balance_total_minutes"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of OvertimeSurchargeAccount from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if balance_last_period_minutes (nullable) is None + # and model_fields_set contains the field + if self.balance_last_period_minutes is None and "balance_last_period_minutes" in self.model_fields_set: + _dict['balance_last_period_minutes'] = None + + # set to None if new_minutes (nullable) is None + # and model_fields_set contains the field + if self.new_minutes is None and "new_minutes" in self.model_fields_set: + _dict['new_minutes'] = None + + # set to None if balance_total_minutes (nullable) is None + # and model_fields_set contains the field + if self.balance_total_minutes is None and "balance_total_minutes" in self.model_fields_set: + _dict['balance_total_minutes'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of OvertimeSurchargeAccount from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "balance_last_period_minutes": obj.get("balance_last_period_minutes"), + "new_minutes": obj.get("new_minutes"), + "balance_total_minutes": obj.get("balance_total_minutes") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/overtime_surcharge_accounts.py b/sdk/python/timr_api/models/overtime_surcharge_accounts.py new file mode 100644 index 0000000..efa42d0 --- /dev/null +++ b/sdk/python/timr_api/models/overtime_surcharge_accounts.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Optional, Union +from timr_api.models.overtime_surcharge_account import OvertimeSurchargeAccount +from timr_api.models.overtime_surcharge_rule import OvertimeSurchargeRule +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class OvertimeSurchargeAccounts(BaseModel): + """ + OvertimeSurchargeAccounts + """ # noqa: E501 + rule: OvertimeSurchargeRule + percentage: Optional[Union[StrictFloat, StrictInt]] + overtime: OvertimeSurchargeAccount + surcharge: OvertimeSurchargeAccount + __properties: ClassVar[List[str]] = ["rule", "percentage", "overtime", "surcharge"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of OvertimeSurchargeAccounts from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of rule + if self.rule: + _dict['rule'] = self.rule.to_dict() + # override the default output from pydantic by calling `to_dict()` of overtime + if self.overtime: + _dict['overtime'] = self.overtime.to_dict() + # override the default output from pydantic by calling `to_dict()` of surcharge + if self.surcharge: + _dict['surcharge'] = self.surcharge.to_dict() + # set to None if percentage (nullable) is None + # and model_fields_set contains the field + if self.percentage is None and "percentage" in self.model_fields_set: + _dict['percentage'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of OvertimeSurchargeAccounts from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "rule": OvertimeSurchargeRule.from_dict(obj["rule"]) if obj.get("rule") is not None else None, + "percentage": obj.get("percentage"), + "overtime": OvertimeSurchargeAccount.from_dict(obj["overtime"]) if obj.get("overtime") is not None else None, + "surcharge": OvertimeSurchargeAccount.from_dict(obj["surcharge"]) if obj.get("surcharge") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/overtime_surcharge_rule.py b/sdk/python/timr_api/models/overtime_surcharge_rule.py new file mode 100644 index 0000000..642b7ff --- /dev/null +++ b/sdk/python/timr_api/models/overtime_surcharge_rule.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from uuid import UUID +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class OvertimeSurchargeRule(BaseModel): + """ + OvertimeSurchargeRule + """ # noqa: E501 + id: UUID = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + short_name: StrictStr + __properties: ClassVar[List[str]] = ["id", "name", "short_name"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of OvertimeSurchargeRule from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of OvertimeSurchargeRule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "short_name": obj.get("short_name") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/paging_information.py b/sdk/python/timr_api/models/paging_information.py new file mode 100644 index 0000000..b07c93d --- /dev/null +++ b/sdk/python/timr_api/models/paging_information.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class PagingInformation(BaseModel): + """ + PagingInformation + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + __properties: ClassVar[List[str]] = ["next_page_token"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PagingInformation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PagingInformation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/platform.py b/sdk/python/timr_api/models/platform.py new file mode 100644 index 0000000..fca83bb --- /dev/null +++ b/sdk/python/timr_api/models/platform.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class Platform(str, Enum): + """ + Platform the entry was recorded on. + """ + + """ + allowed enum values + """ + TIMR_WEB = 'timr_web' + TIMR_MOBILE = 'timr_mobile' + TOUR_MOBILE = 'tour_mobile' + TIMR_TERMINAL = 'timr_terminal' + SYNC_API = 'sync_api' + TIMR_API = 'timr_api' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Platform from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/problem_detail.py b/sdk/python/timr_api/models/problem_detail.py new file mode 100644 index 0000000..e504a8e --- /dev/null +++ b/sdk/python/timr_api/models/problem_detail.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class ProblemDetail(BaseModel): + """ + RFC 9457 Problem Details base members (`type`, `title`, `status`, `detail`, `instance`) — the common shape of all error response bodies. + """ # noqa: E501 + type: StrictStr + title: StrictStr + status: StrictInt + detail: Optional[StrictStr] = None + instance: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["type", "title", "status", "detail", "instance"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ProblemDetail from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ProblemDetail from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "title": obj.get("title"), + "status": obj.get("status"), + "detail": obj.get("detail"), + "instance": obj.get("instance") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/project_time.py b/sdk/python/timr_api/models/project_time.py new file mode 100644 index 0000000..7437761 --- /dev/null +++ b/sdk/python/timr_api/models/project_time.py @@ -0,0 +1,203 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time import BreakTime +from timr_api.models.duration import Duration +from timr_api.models.location import Location +from timr_api.models.platform import Platform +from timr_api.models.project_time_status import ProjectTimeStatus +from timr_api.models.task_partial import TaskPartial +from timr_api.models.user_partial import UserPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class ProjectTime(BaseModel): + """ + One booking on a `task`, from `start` to `end`, optionally `billable`, with `break_times`, notes and locations. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + start: datetime = Field(description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(description="RFC 3339 date-time (ISO-8601)") + break_time_total_minutes: StrictInt = Field(description="Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties") + break_times: List[BreakTime] + duration: Optional[Duration] + changed: StrictBool + notes: Optional[StrictStr] + user: UserPartial + task: TaskPartial + billable: StrictBool + start_location: Optional[Location] + end_location: Optional[Location] + start_platform: Optional[Platform] + end_platform: Optional[Platform] + last_modified: datetime = Field(description="Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) ") + last_modified_by: Optional[UserPartial] = Field(description="Read-only. The User who last modified the entry, or null if the change was not made in a user context. ") + status: ProjectTimeStatus + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["id", "start", "end", "break_time_total_minutes", "break_times", "duration", "changed", "notes", "user", "task", "billable", "start_location", "end_location", "start_platform", "end_platform", "last_modified", "last_modified_by", "status", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ProjectTime from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in break_times (list) + _items = [] + if self.break_times: + for _item_break_times in self.break_times: + if _item_break_times: + _items.append(_item_break_times.to_dict()) + _dict['break_times'] = _items + # override the default output from pydantic by calling `to_dict()` of duration + if self.duration: + _dict['duration'] = self.duration.to_dict() + # override the default output from pydantic by calling `to_dict()` of user + if self.user: + _dict['user'] = self.user.to_dict() + # override the default output from pydantic by calling `to_dict()` of task + if self.task: + _dict['task'] = self.task.to_dict() + # override the default output from pydantic by calling `to_dict()` of start_location + if self.start_location: + _dict['start_location'] = self.start_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_location + if self.end_location: + _dict['end_location'] = self.end_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of last_modified_by + if self.last_modified_by: + _dict['last_modified_by'] = self.last_modified_by.to_dict() + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if duration (nullable) is None + # and model_fields_set contains the field + if self.duration is None and "duration" in self.model_fields_set: + _dict['duration'] = None + + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if start_location (nullable) is None + # and model_fields_set contains the field + if self.start_location is None and "start_location" in self.model_fields_set: + _dict['start_location'] = None + + # set to None if end_location (nullable) is None + # and model_fields_set contains the field + if self.end_location is None and "end_location" in self.model_fields_set: + _dict['end_location'] = None + + # set to None if start_platform (nullable) is None + # and model_fields_set contains the field + if self.start_platform is None and "start_platform" in self.model_fields_set: + _dict['start_platform'] = None + + # set to None if end_platform (nullable) is None + # and model_fields_set contains the field + if self.end_platform is None and "end_platform" in self.model_fields_set: + _dict['end_platform'] = None + + # set to None if last_modified_by (nullable) is None + # and model_fields_set contains the field + if self.last_modified_by is None and "last_modified_by" in self.model_fields_set: + _dict['last_modified_by'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ProjectTime from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "start": obj.get("start"), + "end": obj.get("end"), + "break_time_total_minutes": obj.get("break_time_total_minutes"), + "break_times": [BreakTime.from_dict(_item) for _item in obj["break_times"]] if obj.get("break_times") is not None else None, + "duration": Duration.from_dict(obj["duration"]) if obj.get("duration") is not None else None, + "changed": obj.get("changed"), + "notes": obj.get("notes"), + "user": UserPartial.from_dict(obj["user"]) if obj.get("user") is not None else None, + "task": TaskPartial.from_dict(obj["task"]) if obj.get("task") is not None else None, + "billable": obj.get("billable"), + "start_location": Location.from_dict(obj["start_location"]) if obj.get("start_location") is not None else None, + "end_location": Location.from_dict(obj["end_location"]) if obj.get("end_location") is not None else None, + "start_platform": obj.get("start_platform"), + "end_platform": obj.get("end_platform"), + "last_modified": obj.get("last_modified"), + "last_modified_by": UserPartial.from_dict(obj["last_modified_by"]) if obj.get("last_modified_by") is not None else None, + "status": obj.get("status"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/project_time_create.py b/sdk/python/timr_api/models/project_time_create.py new file mode 100644 index 0000000..20fb24f --- /dev/null +++ b/sdk/python/timr_api/models/project_time_create.py @@ -0,0 +1,153 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time_update import BreakTimeUpdate +from timr_api.models.location_create import LocationCreate +from timr_api.models.project_time_status import ProjectTimeStatus +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class ProjectTimeCreate(BaseModel): + """ + ProjectTimeCreate + """ # noqa: E501 + start: datetime = Field(description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + break_times: Optional[List[BreakTimeUpdate]] = None + changed: StrictBool + notes: Optional[StrictStr] = None + task_id: StrictStr + billable: Optional[StrictBool] = None + status: ProjectTimeStatus + metadata: Optional[Dict[str, Any]] = None + user_id: StrictStr + start_location: Optional[LocationCreate] = None + end_location: Optional[LocationCreate] = None + __properties: ClassVar[List[str]] = ["start", "end", "break_times", "changed", "notes", "task_id", "billable", "status", "metadata", "user_id", "start_location", "end_location"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ProjectTimeCreate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in break_times (list) + _items = [] + if self.break_times: + for _item_break_times in self.break_times: + if _item_break_times: + _items.append(_item_break_times.to_dict()) + _dict['break_times'] = _items + # override the default output from pydantic by calling `to_dict()` of start_location + if self.start_location: + _dict['start_location'] = self.start_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_location + if self.end_location: + _dict['end_location'] = self.end_location.to_dict() + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + # set to None if start_location (nullable) is None + # and model_fields_set contains the field + if self.start_location is None and "start_location" in self.model_fields_set: + _dict['start_location'] = None + + # set to None if end_location (nullable) is None + # and model_fields_set contains the field + if self.end_location is None and "end_location" in self.model_fields_set: + _dict['end_location'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ProjectTimeCreate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end"), + "break_times": [BreakTimeUpdate.from_dict(_item) for _item in obj["break_times"]] if obj.get("break_times") is not None else None, + "changed": obj.get("changed"), + "notes": obj.get("notes"), + "task_id": obj.get("task_id"), + "billable": obj.get("billable"), + "status": obj.get("status"), + "metadata": obj.get("metadata"), + "user_id": obj.get("user_id"), + "start_location": LocationCreate.from_dict(obj["start_location"]) if obj.get("start_location") is not None else None, + "end_location": LocationCreate.from_dict(obj["end_location"]) if obj.get("end_location") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/project_time_status.py b/sdk/python/timr_api/models/project_time_status.py new file mode 100644 index 0000000..71c899a --- /dev/null +++ b/sdk/python/timr_api/models/project_time_status.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class ProjectTimeStatus(str, Enum): + """ + Processing state of a Project Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + """ + + """ + allowed enum values + """ + RUNNING = 'running' + PAUSED = 'paused' + CHANGEABLE = 'changeable' + LOCKED = 'locked' + APPROVED = 'approved' + CLEARED = 'cleared' + CLOSED = 'closed' + ARCHIVED = 'archived' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ProjectTimeStatus from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/project_time_update.py b/sdk/python/timr_api/models/project_time_update.py new file mode 100644 index 0000000..0e9dd50 --- /dev/null +++ b/sdk/python/timr_api/models/project_time_update.py @@ -0,0 +1,151 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time_update import BreakTimeUpdate +from timr_api.models.location_update import LocationUpdate +from timr_api.models.project_time_status import ProjectTimeStatus +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class ProjectTimeUpdate(BaseModel): + """ + ProjectTimeUpdate + """ # noqa: E501 + start: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + break_times: Optional[List[BreakTimeUpdate]] = None + changed: Optional[StrictBool] = None + notes: Optional[StrictStr] = None + task_id: Optional[StrictStr] = None + billable: Optional[StrictBool] = None + status: Optional[ProjectTimeStatus] = None + metadata: Optional[Dict[str, Any]] = None + start_location: Optional[LocationUpdate] = None + end_location: Optional[LocationUpdate] = None + __properties: ClassVar[List[str]] = ["start", "end", "break_times", "changed", "notes", "task_id", "billable", "status", "metadata", "start_location", "end_location"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ProjectTimeUpdate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in break_times (list) + _items = [] + if self.break_times: + for _item_break_times in self.break_times: + if _item_break_times: + _items.append(_item_break_times.to_dict()) + _dict['break_times'] = _items + # override the default output from pydantic by calling `to_dict()` of start_location + if self.start_location: + _dict['start_location'] = self.start_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_location + if self.end_location: + _dict['end_location'] = self.end_location.to_dict() + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + # set to None if start_location (nullable) is None + # and model_fields_set contains the field + if self.start_location is None and "start_location" in self.model_fields_set: + _dict['start_location'] = None + + # set to None if end_location (nullable) is None + # and model_fields_set contains the field + if self.end_location is None and "end_location" in self.model_fields_set: + _dict['end_location'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ProjectTimeUpdate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end"), + "break_times": [BreakTimeUpdate.from_dict(_item) for _item in obj["break_times"]] if obj.get("break_times") is not None else None, + "changed": obj.get("changed"), + "notes": obj.get("notes"), + "task_id": obj.get("task_id"), + "billable": obj.get("billable"), + "status": obj.get("status"), + "metadata": obj.get("metadata"), + "start_location": LocationUpdate.from_dict(obj["start_location"]) if obj.get("start_location") is not None else None, + "end_location": LocationUpdate.from_dict(obj["end_location"]) if obj.get("end_location") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/project_time_upsert.py b/sdk/python/timr_api/models/project_time_upsert.py new file mode 100644 index 0000000..e07f4b0 --- /dev/null +++ b/sdk/python/timr_api/models/project_time_upsert.py @@ -0,0 +1,130 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time_update import BreakTimeUpdate +from timr_api.models.project_time_status import ProjectTimeStatus +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class ProjectTimeUpsert(BaseModel): + """ + ProjectTimeUpsert + """ # noqa: E501 + start: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(default=None, description="RFC 3339 date-time (ISO-8601)") + break_times: Optional[List[BreakTimeUpdate]] = None + changed: Optional[StrictBool] = None + notes: Optional[StrictStr] = None + task_id: Optional[StrictStr] = None + billable: Optional[StrictBool] = None + status: Optional[ProjectTimeStatus] = None + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["start", "end", "break_times", "changed", "notes", "task_id", "billable", "status", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ProjectTimeUpsert from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in break_times (list) + _items = [] + if self.break_times: + for _item_break_times in self.break_times: + if _item_break_times: + _items.append(_item_break_times.to_dict()) + _dict['break_times'] = _items + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ProjectTimeUpsert from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end"), + "break_times": [BreakTimeUpdate.from_dict(_item) for _item in obj["break_times"]] if obj.get("break_times") is not None else None, + "changed": obj.get("changed"), + "notes": obj.get("notes"), + "task_id": obj.get("task_id"), + "billable": obj.get("billable"), + "status": obj.get("status"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/project_times_page.py b/sdk/python/timr_api/models/project_times_page.py new file mode 100644 index 0000000..e920595 --- /dev/null +++ b/sdk/python/timr_api/models/project_times_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.project_time import ProjectTime +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class ProjectTimesPage(BaseModel): + """ + ProjectTimesPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[ProjectTime] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ProjectTimesPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ProjectTimesPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [ProjectTime.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/project_times_sort_column.py b/sdk/python/timr_api/models/project_times_sort_column.py new file mode 100644 index 0000000..ab01467 --- /dev/null +++ b/sdk/python/timr_api/models/project_times_sort_column.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class ProjectTimesSortColumn(str, Enum): + """ + Sort property for Project Times. + """ + + """ + allowed enum values + """ + START = 'start' + LAST_MODIFIED = 'last_modified' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ProjectTimesSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/recording_lock_type.py b/sdk/python/timr_api/models/recording_lock_type.py new file mode 100644 index 0000000..3b9a0a9 --- /dev/null +++ b/sdk/python/timr_api/models/recording_lock_type.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class RecordingLockType(str, Enum): + """ + Whether the assigned User may record on the Task, and where the lock comes from. `recordable` allows recording; `locked_automatically` follows the Task's lock date; `locked_manually` and `unlocked_manually` are explicit overrides for this assignment. + """ + + """ + allowed enum values + """ + RECORDABLE = 'recordable' + LOCKED_AUTOMATICALLY = 'locked_automatically' + LOCKED_MANUALLY = 'locked_manually' + UNLOCKED_MANUALLY = 'unlocked_manually' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of RecordingLockType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/recording_mode_user.py b/sdk/python/timr_api/models/recording_mode_user.py new file mode 100644 index 0000000..754c8b7 --- /dev/null +++ b/sdk/python/timr_api/models/recording_mode_user.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class RecordingModeUser(str, Enum): + """ + Whether a User may record this Working Time Type themselves. Only meaningful for day-based types. + """ + + """ + allowed enum values + """ + NOT_ALLOWED = 'not_allowed' + ALLOWED = 'allowed' + BY_REQUEST = 'by_request' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of RecordingModeUser from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/sort_direction.py b/sdk/python/timr_api/models/sort_direction.py new file mode 100644 index 0000000..197f37d --- /dev/null +++ b/sdk/python/timr_api/models/sort_direction.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class SortDirection(str, Enum): + """ + Sort direction — `asc` for ascending, `dsc` for descending. + """ + + """ + allowed enum values + """ + ASC = 'asc' + DSC = 'dsc' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of SortDirection from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/task.py b/sdk/python/timr_api/models/task.py new file mode 100644 index 0000000..f0fd596 --- /dev/null +++ b/sdk/python/timr_api/models/task.py @@ -0,0 +1,257 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from timr_api.models.budget_planning_type import BudgetPlanningType +from timr_api.models.task_location import TaskLocation +from timr_api.models.task_partial import TaskPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Task(BaseModel): + """ + A task, placed in the tree by `parent_task`, with the full path from the root in `breadcrumbs`. `bookable` and `billable` control recording and invoicing; `lock_date`, time windows and location constrain what may be recorded. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + breadcrumbs: StrictStr = Field(description="Full path of the entry within its hierarchy, including its own name.") + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + parent_task: Optional[TaskPartial] + description: Optional[StrictStr] + description_external: Optional[StrictStr] + bookable: StrictBool + billable: StrictBool + project_time_notes_required: StrictBool + start_date: Optional[date] = Field(description="RFC 3339 date (ISO-8601)") + end_date: Optional[date] = Field(description="RFC 3339 date (ISO-8601)") + lock_date: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + earliest_start_time: Optional[StrictStr] = Field(default=None, description="time of day (ISO-8601)") + latest_end_time: Optional[StrictStr] = Field(default=None, description="time of day (ISO-8601)") + active_from: Optional[date] = Field(description="RFC 3339 date (ISO-8601)") + active_to: Optional[date] = Field(description="RFC 3339 date (ISO-8601)") + budget_inherited: Optional[StrictBool] = None + budget_planning_type: Optional[BudgetPlanningType] = None + budget_hours_planned: Optional[Union[StrictFloat, StrictInt]] = None + budget_hourly_rate: Optional[Union[StrictFloat, StrictInt]] = None + budget_planned: Optional[Union[StrictFloat, StrictInt]] = None + budget_include_non_billable_project_times: Optional[StrictBool] = None + location_inherited: Optional[StrictBool] = None + location: Optional[TaskLocation] = None + location_restriction_radius_meters: Optional[StrictInt] = None + custom_field_1: Optional[StrictStr] + custom_field_2: Optional[StrictStr] + custom_field_3: Optional[StrictStr] + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["id", "name", "breadcrumbs", "external_id", "parent_task", "description", "description_external", "bookable", "billable", "project_time_notes_required", "start_date", "end_date", "lock_date", "earliest_start_time", "latest_end_time", "active_from", "active_to", "budget_inherited", "budget_planning_type", "budget_hours_planned", "budget_hourly_rate", "budget_planned", "budget_include_non_billable_project_times", "location_inherited", "location", "location_restriction_radius_meters", "custom_field_1", "custom_field_2", "custom_field_3", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Task from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of parent_task + if self.parent_task: + _dict['parent_task'] = self.parent_task.to_dict() + # override the default output from pydantic by calling `to_dict()` of location + if self.location: + _dict['location'] = self.location.to_dict() + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if parent_task (nullable) is None + # and model_fields_set contains the field + if self.parent_task is None and "parent_task" in self.model_fields_set: + _dict['parent_task'] = None + + # set to None if description (nullable) is None + # and model_fields_set contains the field + if self.description is None and "description" in self.model_fields_set: + _dict['description'] = None + + # set to None if description_external (nullable) is None + # and model_fields_set contains the field + if self.description_external is None and "description_external" in self.model_fields_set: + _dict['description_external'] = None + + # set to None if start_date (nullable) is None + # and model_fields_set contains the field + if self.start_date is None and "start_date" in self.model_fields_set: + _dict['start_date'] = None + + # set to None if end_date (nullable) is None + # and model_fields_set contains the field + if self.end_date is None and "end_date" in self.model_fields_set: + _dict['end_date'] = None + + # set to None if lock_date (nullable) is None + # and model_fields_set contains the field + if self.lock_date is None and "lock_date" in self.model_fields_set: + _dict['lock_date'] = None + + # set to None if earliest_start_time (nullable) is None + # and model_fields_set contains the field + if self.earliest_start_time is None and "earliest_start_time" in self.model_fields_set: + _dict['earliest_start_time'] = None + + # set to None if latest_end_time (nullable) is None + # and model_fields_set contains the field + if self.latest_end_time is None and "latest_end_time" in self.model_fields_set: + _dict['latest_end_time'] = None + + # set to None if active_from (nullable) is None + # and model_fields_set contains the field + if self.active_from is None and "active_from" in self.model_fields_set: + _dict['active_from'] = None + + # set to None if active_to (nullable) is None + # and model_fields_set contains the field + if self.active_to is None and "active_to" in self.model_fields_set: + _dict['active_to'] = None + + # set to None if budget_hours_planned (nullable) is None + # and model_fields_set contains the field + if self.budget_hours_planned is None and "budget_hours_planned" in self.model_fields_set: + _dict['budget_hours_planned'] = None + + # set to None if budget_hourly_rate (nullable) is None + # and model_fields_set contains the field + if self.budget_hourly_rate is None and "budget_hourly_rate" in self.model_fields_set: + _dict['budget_hourly_rate'] = None + + # set to None if budget_planned (nullable) is None + # and model_fields_set contains the field + if self.budget_planned is None and "budget_planned" in self.model_fields_set: + _dict['budget_planned'] = None + + # set to None if location (nullable) is None + # and model_fields_set contains the field + if self.location is None and "location" in self.model_fields_set: + _dict['location'] = None + + # set to None if location_restriction_radius_meters (nullable) is None + # and model_fields_set contains the field + if self.location_restriction_radius_meters is None and "location_restriction_radius_meters" in self.model_fields_set: + _dict['location_restriction_radius_meters'] = None + + # set to None if custom_field_1 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_1 is None and "custom_field_1" in self.model_fields_set: + _dict['custom_field_1'] = None + + # set to None if custom_field_2 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_2 is None and "custom_field_2" in self.model_fields_set: + _dict['custom_field_2'] = None + + # set to None if custom_field_3 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_3 is None and "custom_field_3" in self.model_fields_set: + _dict['custom_field_3'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Task from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "breadcrumbs": obj.get("breadcrumbs"), + "external_id": obj.get("external_id"), + "parent_task": TaskPartial.from_dict(obj["parent_task"]) if obj.get("parent_task") is not None else None, + "description": obj.get("description"), + "description_external": obj.get("description_external"), + "bookable": obj.get("bookable"), + "billable": obj.get("billable"), + "project_time_notes_required": obj.get("project_time_notes_required"), + "start_date": obj.get("start_date"), + "end_date": obj.get("end_date"), + "lock_date": obj.get("lock_date"), + "earliest_start_time": obj.get("earliest_start_time"), + "latest_end_time": obj.get("latest_end_time"), + "active_from": obj.get("active_from"), + "active_to": obj.get("active_to"), + "budget_inherited": obj.get("budget_inherited"), + "budget_planning_type": obj.get("budget_planning_type"), + "budget_hours_planned": obj.get("budget_hours_planned"), + "budget_hourly_rate": obj.get("budget_hourly_rate"), + "budget_planned": obj.get("budget_planned"), + "budget_include_non_billable_project_times": obj.get("budget_include_non_billable_project_times"), + "location_inherited": obj.get("location_inherited"), + "location": TaskLocation.from_dict(obj["location"]) if obj.get("location") is not None else None, + "location_restriction_radius_meters": obj.get("location_restriction_radius_meters"), + "custom_field_1": obj.get("custom_field_1"), + "custom_field_2": obj.get("custom_field_2"), + "custom_field_3": obj.get("custom_field_3"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_base.py b/sdk/python/timr_api/models/task_base.py new file mode 100644 index 0000000..3f81968 --- /dev/null +++ b/sdk/python/timr_api/models/task_base.py @@ -0,0 +1,233 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from timr_api.models.budget_planning_type_request import BudgetPlanningTypeRequest +from timr_api.models.task_location import TaskLocation +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskBase(BaseModel): + """ + TaskBase + """ # noqa: E501 + name: Optional[StrictStr] = None + parent_task_id: Optional[StrictStr] = Field(default=None, description="returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree.") + external_id: Optional[StrictStr] = Field(default=None, description="Identifier of the corresponding object in an external system. Set and owned by the client.") + description: Optional[StrictStr] = None + description_external: Optional[StrictStr] = None + bookable: Optional[StrictBool] = Field(default=None, description="when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task.") + billable: Optional[StrictBool] = None + project_time_notes_required: Optional[StrictBool] = Field(default=None, description="depending on this property project times booked on this task have to include notes or not") + start_date: Optional[date] = Field(default=None, description="the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible.") + end_date: Optional[date] = Field(default=None, description="the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible.") + lock_date: Optional[date] = Field(default=None, description="with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later ") + earliest_start_time: Optional[StrictStr] = Field(default=None, description="set this property to limit the task so that it cannot be booked before this time") + latest_end_time: Optional[StrictStr] = Field(default=None, description="set this property to limit the task so that it cannot be booked after this time") + budget_planning_type: Optional[BudgetPlanningTypeRequest] = Field(default=None, description="when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. ") + budget_hours_planned: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned ") + budget_hourly_rate: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value ") + budget_planned: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned ") + budget_include_non_billable_project_times: Optional[StrictBool] = Field(default=None, description="set this property to true, if you want to include not billable hours for all project times booked on this task") + location_inherited: Optional[StrictBool] = Field(default=None, description="set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent") + location: Optional[TaskLocation] = None + location_restriction_radius_meters: Optional[StrictInt] = Field(default=None, description="set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius") + custom_field_1: Optional[StrictStr] = Field(default=None, description="you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field.") + custom_field_2: Optional[StrictStr] = Field(default=None, description="you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field.") + custom_field_3: Optional[StrictStr] = Field(default=None, description="you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field.") + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["name", "parent_task_id", "external_id", "description", "description_external", "bookable", "billable", "project_time_notes_required", "start_date", "end_date", "lock_date", "earliest_start_time", "latest_end_time", "budget_planning_type", "budget_hours_planned", "budget_hourly_rate", "budget_planned", "budget_include_non_billable_project_times", "location_inherited", "location", "location_restriction_radius_meters", "custom_field_1", "custom_field_2", "custom_field_3", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskBase from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of location + if self.location: + _dict['location'] = self.location.to_dict() + # set to None if parent_task_id (nullable) is None + # and model_fields_set contains the field + if self.parent_task_id is None and "parent_task_id" in self.model_fields_set: + _dict['parent_task_id'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if description (nullable) is None + # and model_fields_set contains the field + if self.description is None and "description" in self.model_fields_set: + _dict['description'] = None + + # set to None if description_external (nullable) is None + # and model_fields_set contains the field + if self.description_external is None and "description_external" in self.model_fields_set: + _dict['description_external'] = None + + # set to None if start_date (nullable) is None + # and model_fields_set contains the field + if self.start_date is None and "start_date" in self.model_fields_set: + _dict['start_date'] = None + + # set to None if end_date (nullable) is None + # and model_fields_set contains the field + if self.end_date is None and "end_date" in self.model_fields_set: + _dict['end_date'] = None + + # set to None if lock_date (nullable) is None + # and model_fields_set contains the field + if self.lock_date is None and "lock_date" in self.model_fields_set: + _dict['lock_date'] = None + + # set to None if earliest_start_time (nullable) is None + # and model_fields_set contains the field + if self.earliest_start_time is None and "earliest_start_time" in self.model_fields_set: + _dict['earliest_start_time'] = None + + # set to None if latest_end_time (nullable) is None + # and model_fields_set contains the field + if self.latest_end_time is None and "latest_end_time" in self.model_fields_set: + _dict['latest_end_time'] = None + + # set to None if budget_hours_planned (nullable) is None + # and model_fields_set contains the field + if self.budget_hours_planned is None and "budget_hours_planned" in self.model_fields_set: + _dict['budget_hours_planned'] = None + + # set to None if budget_hourly_rate (nullable) is None + # and model_fields_set contains the field + if self.budget_hourly_rate is None and "budget_hourly_rate" in self.model_fields_set: + _dict['budget_hourly_rate'] = None + + # set to None if budget_planned (nullable) is None + # and model_fields_set contains the field + if self.budget_planned is None and "budget_planned" in self.model_fields_set: + _dict['budget_planned'] = None + + # set to None if location (nullable) is None + # and model_fields_set contains the field + if self.location is None and "location" in self.model_fields_set: + _dict['location'] = None + + # set to None if location_restriction_radius_meters (nullable) is None + # and model_fields_set contains the field + if self.location_restriction_radius_meters is None and "location_restriction_radius_meters" in self.model_fields_set: + _dict['location_restriction_radius_meters'] = None + + # set to None if custom_field_1 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_1 is None and "custom_field_1" in self.model_fields_set: + _dict['custom_field_1'] = None + + # set to None if custom_field_2 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_2 is None and "custom_field_2" in self.model_fields_set: + _dict['custom_field_2'] = None + + # set to None if custom_field_3 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_3 is None and "custom_field_3" in self.model_fields_set: + _dict['custom_field_3'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskBase from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "parent_task_id": obj.get("parent_task_id"), + "external_id": obj.get("external_id"), + "description": obj.get("description"), + "description_external": obj.get("description_external"), + "bookable": obj.get("bookable"), + "billable": obj.get("billable"), + "project_time_notes_required": obj.get("project_time_notes_required"), + "start_date": obj.get("start_date"), + "end_date": obj.get("end_date"), + "lock_date": obj.get("lock_date"), + "earliest_start_time": obj.get("earliest_start_time"), + "latest_end_time": obj.get("latest_end_time"), + "budget_planning_type": obj.get("budget_planning_type"), + "budget_hours_planned": obj.get("budget_hours_planned"), + "budget_hourly_rate": obj.get("budget_hourly_rate"), + "budget_planned": obj.get("budget_planned"), + "budget_include_non_billable_project_times": obj.get("budget_include_non_billable_project_times"), + "location_inherited": obj.get("location_inherited"), + "location": TaskLocation.from_dict(obj["location"]) if obj.get("location") is not None else None, + "location_restriction_radius_meters": obj.get("location_restriction_radius_meters"), + "custom_field_1": obj.get("custom_field_1"), + "custom_field_2": obj.get("custom_field_2"), + "custom_field_3": obj.get("custom_field_3"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_create.py b/sdk/python/timr_api/models/task_create.py new file mode 100644 index 0000000..e3d3e08 --- /dev/null +++ b/sdk/python/timr_api/models/task_create.py @@ -0,0 +1,233 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from timr_api.models.budget_planning_type_request import BudgetPlanningTypeRequest +from timr_api.models.task_location import TaskLocation +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskCreate(BaseModel): + """ + TaskCreate + """ # noqa: E501 + name: StrictStr + parent_task_id: Optional[StrictStr] = Field(default=None, description="returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree.") + external_id: Optional[StrictStr] = Field(default=None, description="Identifier of the corresponding object in an external system. Set and owned by the client.") + description: Optional[StrictStr] = None + description_external: Optional[StrictStr] = None + bookable: StrictBool = Field(description="when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task.") + billable: StrictBool + project_time_notes_required: Optional[StrictBool] = Field(default=None, description="depending on this property project times booked on this task have to include notes or not") + start_date: Optional[date] = Field(default=None, description="the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible.") + end_date: Optional[date] = Field(default=None, description="the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible.") + lock_date: Optional[date] = Field(default=None, description="with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later ") + earliest_start_time: Optional[StrictStr] = Field(default=None, description="set this property to limit the task so that it cannot be booked before this time") + latest_end_time: Optional[StrictStr] = Field(default=None, description="set this property to limit the task so that it cannot be booked after this time") + budget_planning_type: Optional[BudgetPlanningTypeRequest] = Field(default=None, description="when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. ") + budget_hours_planned: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned ") + budget_hourly_rate: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value ") + budget_planned: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned ") + budget_include_non_billable_project_times: Optional[StrictBool] = Field(default=None, description="set this property to true, if you want to include not billable hours for all project times booked on this task") + location_inherited: Optional[StrictBool] = Field(default=None, description="set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent") + location: Optional[TaskLocation] = None + location_restriction_radius_meters: Optional[StrictInt] = Field(default=None, description="set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius") + custom_field_1: Optional[StrictStr] = Field(default=None, description="you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field.") + custom_field_2: Optional[StrictStr] = Field(default=None, description="you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field.") + custom_field_3: Optional[StrictStr] = Field(default=None, description="you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field.") + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["name", "parent_task_id", "external_id", "description", "description_external", "bookable", "billable", "project_time_notes_required", "start_date", "end_date", "lock_date", "earliest_start_time", "latest_end_time", "budget_planning_type", "budget_hours_planned", "budget_hourly_rate", "budget_planned", "budget_include_non_billable_project_times", "location_inherited", "location", "location_restriction_radius_meters", "custom_field_1", "custom_field_2", "custom_field_3", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskCreate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of location + if self.location: + _dict['location'] = self.location.to_dict() + # set to None if parent_task_id (nullable) is None + # and model_fields_set contains the field + if self.parent_task_id is None and "parent_task_id" in self.model_fields_set: + _dict['parent_task_id'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if description (nullable) is None + # and model_fields_set contains the field + if self.description is None and "description" in self.model_fields_set: + _dict['description'] = None + + # set to None if description_external (nullable) is None + # and model_fields_set contains the field + if self.description_external is None and "description_external" in self.model_fields_set: + _dict['description_external'] = None + + # set to None if start_date (nullable) is None + # and model_fields_set contains the field + if self.start_date is None and "start_date" in self.model_fields_set: + _dict['start_date'] = None + + # set to None if end_date (nullable) is None + # and model_fields_set contains the field + if self.end_date is None and "end_date" in self.model_fields_set: + _dict['end_date'] = None + + # set to None if lock_date (nullable) is None + # and model_fields_set contains the field + if self.lock_date is None and "lock_date" in self.model_fields_set: + _dict['lock_date'] = None + + # set to None if earliest_start_time (nullable) is None + # and model_fields_set contains the field + if self.earliest_start_time is None and "earliest_start_time" in self.model_fields_set: + _dict['earliest_start_time'] = None + + # set to None if latest_end_time (nullable) is None + # and model_fields_set contains the field + if self.latest_end_time is None and "latest_end_time" in self.model_fields_set: + _dict['latest_end_time'] = None + + # set to None if budget_hours_planned (nullable) is None + # and model_fields_set contains the field + if self.budget_hours_planned is None and "budget_hours_planned" in self.model_fields_set: + _dict['budget_hours_planned'] = None + + # set to None if budget_hourly_rate (nullable) is None + # and model_fields_set contains the field + if self.budget_hourly_rate is None and "budget_hourly_rate" in self.model_fields_set: + _dict['budget_hourly_rate'] = None + + # set to None if budget_planned (nullable) is None + # and model_fields_set contains the field + if self.budget_planned is None and "budget_planned" in self.model_fields_set: + _dict['budget_planned'] = None + + # set to None if location (nullable) is None + # and model_fields_set contains the field + if self.location is None and "location" in self.model_fields_set: + _dict['location'] = None + + # set to None if location_restriction_radius_meters (nullable) is None + # and model_fields_set contains the field + if self.location_restriction_radius_meters is None and "location_restriction_radius_meters" in self.model_fields_set: + _dict['location_restriction_radius_meters'] = None + + # set to None if custom_field_1 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_1 is None and "custom_field_1" in self.model_fields_set: + _dict['custom_field_1'] = None + + # set to None if custom_field_2 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_2 is None and "custom_field_2" in self.model_fields_set: + _dict['custom_field_2'] = None + + # set to None if custom_field_3 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_3 is None and "custom_field_3" in self.model_fields_set: + _dict['custom_field_3'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskCreate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "parent_task_id": obj.get("parent_task_id"), + "external_id": obj.get("external_id"), + "description": obj.get("description"), + "description_external": obj.get("description_external"), + "bookable": obj.get("bookable"), + "billable": obj.get("billable"), + "project_time_notes_required": obj.get("project_time_notes_required"), + "start_date": obj.get("start_date"), + "end_date": obj.get("end_date"), + "lock_date": obj.get("lock_date"), + "earliest_start_time": obj.get("earliest_start_time"), + "latest_end_time": obj.get("latest_end_time"), + "budget_planning_type": obj.get("budget_planning_type"), + "budget_hours_planned": obj.get("budget_hours_planned"), + "budget_hourly_rate": obj.get("budget_hourly_rate"), + "budget_planned": obj.get("budget_planned"), + "budget_include_non_billable_project_times": obj.get("budget_include_non_billable_project_times"), + "location_inherited": obj.get("location_inherited"), + "location": TaskLocation.from_dict(obj["location"]) if obj.get("location") is not None else None, + "location_restriction_radius_meters": obj.get("location_restriction_radius_meters"), + "custom_field_1": obj.get("custom_field_1"), + "custom_field_2": obj.get("custom_field_2"), + "custom_field_3": obj.get("custom_field_3"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_location.py b/sdk/python/timr_api/models/task_location.py new file mode 100644 index 0000000..3fa5ec3 --- /dev/null +++ b/sdk/python/timr_api/models/task_location.py @@ -0,0 +1,136 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskLocation(BaseModel): + """ + You can define the location of a task by setting this property. If the task has a parent task, the location is inherited if nothing else is explicitly defined. If you set this property to null, the location will be deleted. + """ # noqa: E501 + lat: Optional[Union[StrictFloat, StrictInt]] = Field(description="Latitude in decimal degrees.") + lon: Optional[Union[StrictFloat, StrictInt]] = Field(description="Longitude in decimal degrees.") + address: Optional[StrictStr] + city: Optional[StrictStr] + zip_code: Optional[StrictStr] + state: Optional[StrictStr] + country: Optional[StrictStr] = Field(description="the country's international country code") + __properties: ClassVar[List[str]] = ["lat", "lon", "address", "city", "zip_code", "state", "country"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskLocation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if lat (nullable) is None + # and model_fields_set contains the field + if self.lat is None and "lat" in self.model_fields_set: + _dict['lat'] = None + + # set to None if lon (nullable) is None + # and model_fields_set contains the field + if self.lon is None and "lon" in self.model_fields_set: + _dict['lon'] = None + + # set to None if address (nullable) is None + # and model_fields_set contains the field + if self.address is None and "address" in self.model_fields_set: + _dict['address'] = None + + # set to None if city (nullable) is None + # and model_fields_set contains the field + if self.city is None and "city" in self.model_fields_set: + _dict['city'] = None + + # set to None if zip_code (nullable) is None + # and model_fields_set contains the field + if self.zip_code is None and "zip_code" in self.model_fields_set: + _dict['zip_code'] = None + + # set to None if state (nullable) is None + # and model_fields_set contains the field + if self.state is None and "state" in self.model_fields_set: + _dict['state'] = None + + # set to None if country (nullable) is None + # and model_fields_set contains the field + if self.country is None and "country" in self.model_fields_set: + _dict['country'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskLocation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "lat": obj.get("lat"), + "lon": obj.get("lon"), + "address": obj.get("address"), + "city": obj.get("city"), + "zip_code": obj.get("zip_code"), + "state": obj.get("state"), + "country": obj.get("country") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_partial.py b/sdk/python/timr_api/models/task_partial.py new file mode 100644 index 0000000..86e7f95 --- /dev/null +++ b/sdk/python/timr_api/models/task_partial.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskPartial(BaseModel): + """ + TaskPartial + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + breadcrumbs: StrictStr = Field(description="Full path of the entry within its hierarchy, including its own name.") + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + __properties: ClassVar[List[str]] = ["id", "name", "breadcrumbs", "external_id"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskPartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskPartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "breadcrumbs": obj.get("breadcrumbs"), + "external_id": obj.get("external_id") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_reduced.py b/sdk/python/timr_api/models/task_reduced.py new file mode 100644 index 0000000..61b273b --- /dev/null +++ b/sdk/python/timr_api/models/task_reduced.py @@ -0,0 +1,204 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.budget_planning_type import BudgetPlanningType +from timr_api.models.task_location import TaskLocation +from timr_api.models.task_partial import TaskPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskReduced(BaseModel): + """ + TaskReduced + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + breadcrumbs: StrictStr = Field(description="Full path of the entry within its hierarchy, including its own name.") + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + parent_task: Optional[TaskPartial] + description: Optional[StrictStr] + bookable: StrictBool + billable: StrictBool + project_time_notes_required: StrictBool + lock_date: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + earliest_start_time: Optional[StrictStr] = Field(default=None, description="time of day (ISO-8601)") + latest_end_time: Optional[StrictStr] = Field(default=None, description="time of day (ISO-8601)") + active_from: Optional[date] = Field(description="RFC 3339 date (ISO-8601)") + active_to: Optional[date] = Field(description="RFC 3339 date (ISO-8601)") + budget_planning_type: Optional[BudgetPlanningType] = None + location_inherited: Optional[StrictBool] = None + location: Optional[TaskLocation] = None + location_restriction_radius_meters: Optional[StrictInt] = None + custom_field_1: Optional[StrictStr] + custom_field_2: Optional[StrictStr] + custom_field_3: Optional[StrictStr] + __properties: ClassVar[List[str]] = ["id", "name", "breadcrumbs", "external_id", "parent_task", "description", "bookable", "billable", "project_time_notes_required", "lock_date", "earliest_start_time", "latest_end_time", "active_from", "active_to", "budget_planning_type", "location_inherited", "location", "location_restriction_radius_meters", "custom_field_1", "custom_field_2", "custom_field_3"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskReduced from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of parent_task + if self.parent_task: + _dict['parent_task'] = self.parent_task.to_dict() + # override the default output from pydantic by calling `to_dict()` of location + if self.location: + _dict['location'] = self.location.to_dict() + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if parent_task (nullable) is None + # and model_fields_set contains the field + if self.parent_task is None and "parent_task" in self.model_fields_set: + _dict['parent_task'] = None + + # set to None if description (nullable) is None + # and model_fields_set contains the field + if self.description is None and "description" in self.model_fields_set: + _dict['description'] = None + + # set to None if lock_date (nullable) is None + # and model_fields_set contains the field + if self.lock_date is None and "lock_date" in self.model_fields_set: + _dict['lock_date'] = None + + # set to None if earliest_start_time (nullable) is None + # and model_fields_set contains the field + if self.earliest_start_time is None and "earliest_start_time" in self.model_fields_set: + _dict['earliest_start_time'] = None + + # set to None if latest_end_time (nullable) is None + # and model_fields_set contains the field + if self.latest_end_time is None and "latest_end_time" in self.model_fields_set: + _dict['latest_end_time'] = None + + # set to None if active_from (nullable) is None + # and model_fields_set contains the field + if self.active_from is None and "active_from" in self.model_fields_set: + _dict['active_from'] = None + + # set to None if active_to (nullable) is None + # and model_fields_set contains the field + if self.active_to is None and "active_to" in self.model_fields_set: + _dict['active_to'] = None + + # set to None if location (nullable) is None + # and model_fields_set contains the field + if self.location is None and "location" in self.model_fields_set: + _dict['location'] = None + + # set to None if location_restriction_radius_meters (nullable) is None + # and model_fields_set contains the field + if self.location_restriction_radius_meters is None and "location_restriction_radius_meters" in self.model_fields_set: + _dict['location_restriction_radius_meters'] = None + + # set to None if custom_field_1 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_1 is None and "custom_field_1" in self.model_fields_set: + _dict['custom_field_1'] = None + + # set to None if custom_field_2 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_2 is None and "custom_field_2" in self.model_fields_set: + _dict['custom_field_2'] = None + + # set to None if custom_field_3 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_3 is None and "custom_field_3" in self.model_fields_set: + _dict['custom_field_3'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskReduced from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "breadcrumbs": obj.get("breadcrumbs"), + "external_id": obj.get("external_id"), + "parent_task": TaskPartial.from_dict(obj["parent_task"]) if obj.get("parent_task") is not None else None, + "description": obj.get("description"), + "bookable": obj.get("bookable"), + "billable": obj.get("billable"), + "project_time_notes_required": obj.get("project_time_notes_required"), + "lock_date": obj.get("lock_date"), + "earliest_start_time": obj.get("earliest_start_time"), + "latest_end_time": obj.get("latest_end_time"), + "active_from": obj.get("active_from"), + "active_to": obj.get("active_to"), + "budget_planning_type": obj.get("budget_planning_type"), + "location_inherited": obj.get("location_inherited"), + "location": TaskLocation.from_dict(obj["location"]) if obj.get("location") is not None else None, + "location_restriction_radius_meters": obj.get("location_restriction_radius_meters"), + "custom_field_1": obj.get("custom_field_1"), + "custom_field_2": obj.get("custom_field_2"), + "custom_field_3": obj.get("custom_field_3") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_to_leader_assignment.py b/sdk/python/timr_api/models/task_to_leader_assignment.py new file mode 100644 index 0000000..2469484 --- /dev/null +++ b/sdk/python/timr_api/models/task_to_leader_assignment.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictBool +from typing import Any, ClassVar, Dict, List +from timr_api.models.user_partial import UserPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskToLeaderAssignment(BaseModel): + """ + TaskToLeaderAssignment + """ # noqa: E501 + user: UserPartial + automatically_assigned: StrictBool + __properties: ClassVar[List[str]] = ["user", "automatically_assigned"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskToLeaderAssignment from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of user + if self.user: + _dict['user'] = self.user.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskToLeaderAssignment from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "user": UserPartial.from_dict(obj["user"]) if obj.get("user") is not None else None, + "automatically_assigned": obj.get("automatically_assigned") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_to_leader_assignments_page.py b/sdk/python/timr_api/models/task_to_leader_assignments_page.py new file mode 100644 index 0000000..77ea528 --- /dev/null +++ b/sdk/python/timr_api/models/task_to_leader_assignments_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.task_to_leader_assignment import TaskToLeaderAssignment +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskToLeaderAssignmentsPage(BaseModel): + """ + TaskToLeaderAssignmentsPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[TaskToLeaderAssignment] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskToLeaderAssignmentsPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskToLeaderAssignmentsPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [TaskToLeaderAssignment.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_to_leader_assignments_sort_column.py b/sdk/python/timr_api/models/task_to_leader_assignments_sort_column.py new file mode 100644 index 0000000..e83e730 --- /dev/null +++ b/sdk/python/timr_api/models/task_to_leader_assignments_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class TaskToLeaderAssignmentsSortColumn(str, Enum): + """ + Sort property for Task to Leader Assignments. `user_name` orders by the assigned User's last name, then first name. + """ + + """ + allowed enum values + """ + USER_NAME = 'user_name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TaskToLeaderAssignmentsSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/task_to_team_assignment.py b/sdk/python/timr_api/models/task_to_team_assignment.py new file mode 100644 index 0000000..89e8bde --- /dev/null +++ b/sdk/python/timr_api/models/task_to_team_assignment.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictBool +from typing import Any, ClassVar, Dict, List +from timr_api.models.team_partial import TeamPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskToTeamAssignment(BaseModel): + """ + TaskToTeamAssignment + """ # noqa: E501 + team: TeamPartial + automatically_assigned: StrictBool + __properties: ClassVar[List[str]] = ["team", "automatically_assigned"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskToTeamAssignment from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of team + if self.team: + _dict['team'] = self.team.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskToTeamAssignment from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "team": TeamPartial.from_dict(obj["team"]) if obj.get("team") is not None else None, + "automatically_assigned": obj.get("automatically_assigned") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_to_team_assignments_page.py b/sdk/python/timr_api/models/task_to_team_assignments_page.py new file mode 100644 index 0000000..5d927ef --- /dev/null +++ b/sdk/python/timr_api/models/task_to_team_assignments_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.task_to_team_assignment import TaskToTeamAssignment +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskToTeamAssignmentsPage(BaseModel): + """ + TaskToTeamAssignmentsPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[TaskToTeamAssignment] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskToTeamAssignmentsPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskToTeamAssignmentsPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [TaskToTeamAssignment.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_to_team_assignments_sort_column.py b/sdk/python/timr_api/models/task_to_team_assignments_sort_column.py new file mode 100644 index 0000000..393e63c --- /dev/null +++ b/sdk/python/timr_api/models/task_to_team_assignments_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class TaskToTeamAssignmentsSortColumn(str, Enum): + """ + Sort property for Task to Team Assignments. `team_name` orders by the assigned Team's name. + """ + + """ + allowed enum values + """ + TEAM_NAME = 'team_name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TaskToTeamAssignmentsSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/task_to_user_assignment.py b/sdk/python/timr_api/models/task_to_user_assignment.py new file mode 100644 index 0000000..b23b2c8 --- /dev/null +++ b/sdk/python/timr_api/models/task_to_user_assignment.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictBool, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Optional, Union +from timr_api.models.recording_lock_type import RecordingLockType +from timr_api.models.user_partial import UserPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskToUserAssignment(BaseModel): + """ + TaskToUserAssignment + """ # noqa: E501 + user: UserPartial + hours_planned: Optional[Union[StrictFloat, StrictInt]] = None + recording_lock: RecordingLockType + automatically_assigned: StrictBool + __properties: ClassVar[List[str]] = ["user", "hours_planned", "recording_lock", "automatically_assigned"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskToUserAssignment from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of user + if self.user: + _dict['user'] = self.user.to_dict() + # set to None if hours_planned (nullable) is None + # and model_fields_set contains the field + if self.hours_planned is None and "hours_planned" in self.model_fields_set: + _dict['hours_planned'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskToUserAssignment from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "user": UserPartial.from_dict(obj["user"]) if obj.get("user") is not None else None, + "hours_planned": obj.get("hours_planned"), + "recording_lock": obj.get("recording_lock"), + "automatically_assigned": obj.get("automatically_assigned") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_to_user_assignment_upsert.py b/sdk/python/timr_api/models/task_to_user_assignment_upsert.py new file mode 100644 index 0000000..4a8673a --- /dev/null +++ b/sdk/python/timr_api/models/task_to_user_assignment_upsert.py @@ -0,0 +1,102 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Optional, Union +from timr_api.models.recording_lock_type import RecordingLockType +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskToUserAssignmentUpsert(BaseModel): + """ + TaskToUserAssignmentUpsert + """ # noqa: E501 + hours_planned: Optional[Union[StrictFloat, StrictInt]] = None + recording_lock: Optional[RecordingLockType] = None + __properties: ClassVar[List[str]] = ["hours_planned", "recording_lock"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskToUserAssignmentUpsert from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if hours_planned (nullable) is None + # and model_fields_set contains the field + if self.hours_planned is None and "hours_planned" in self.model_fields_set: + _dict['hours_planned'] = None + + # set to None if recording_lock (nullable) is None + # and model_fields_set contains the field + if self.recording_lock is None and "recording_lock" in self.model_fields_set: + _dict['recording_lock'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskToUserAssignmentUpsert from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "hours_planned": obj.get("hours_planned"), + "recording_lock": obj.get("recording_lock") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_to_user_assignments_page.py b/sdk/python/timr_api/models/task_to_user_assignments_page.py new file mode 100644 index 0000000..0837773 --- /dev/null +++ b/sdk/python/timr_api/models/task_to_user_assignments_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.task_to_user_assignment import TaskToUserAssignment +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskToUserAssignmentsPage(BaseModel): + """ + TaskToUserAssignmentsPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[TaskToUserAssignment] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskToUserAssignmentsPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskToUserAssignmentsPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [TaskToUserAssignment.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/task_to_user_assignments_sort_column.py b/sdk/python/timr_api/models/task_to_user_assignments_sort_column.py new file mode 100644 index 0000000..f050dc3 --- /dev/null +++ b/sdk/python/timr_api/models/task_to_user_assignments_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class TaskToUserAssignmentsSortColumn(str, Enum): + """ + Sort property for Task to User Assignments. `user_name` orders by the assigned User's last name, then first name. + """ + + """ + allowed enum values + """ + USER_NAME = 'user_name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TaskToUserAssignmentsSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/task_update.py b/sdk/python/timr_api/models/task_update.py new file mode 100644 index 0000000..772608a --- /dev/null +++ b/sdk/python/timr_api/models/task_update.py @@ -0,0 +1,235 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from timr_api.models.budget_planning_type_request import BudgetPlanningTypeRequest +from timr_api.models.task_location import TaskLocation +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TaskUpdate(BaseModel): + """ + TaskUpdate + """ # noqa: E501 + name: Optional[StrictStr] = None + parent_task_id: Optional[StrictStr] = Field(default=None, description="returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree.") + external_id: Optional[StrictStr] = Field(default=None, description="Identifier of the corresponding object in an external system. Set and owned by the client.") + description: Optional[StrictStr] = None + description_external: Optional[StrictStr] = None + bookable: Optional[StrictBool] = Field(default=None, description="when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task.") + billable: Optional[StrictBool] = None + project_time_notes_required: Optional[StrictBool] = Field(default=None, description="depending on this property project times booked on this task have to include notes or not") + start_date: Optional[date] = Field(default=None, description="the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible.") + end_date: Optional[date] = Field(default=None, description="the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible.") + lock_date: Optional[date] = Field(default=None, description="with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later ") + earliest_start_time: Optional[StrictStr] = Field(default=None, description="set this property to limit the task so that it cannot be booked before this time") + latest_end_time: Optional[StrictStr] = Field(default=None, description="set this property to limit the task so that it cannot be booked after this time") + budget_planning_type: Optional[BudgetPlanningTypeRequest] = Field(default=None, description="when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. ") + budget_hours_planned: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned ") + budget_hourly_rate: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value ") + budget_planned: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned ") + budget_include_non_billable_project_times: Optional[StrictBool] = Field(default=None, description="set this property to true, if you want to include not billable hours for all project times booked on this task") + location_inherited: Optional[StrictBool] = Field(default=None, description="set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent") + location: Optional[TaskLocation] = None + location_restriction_radius_meters: Optional[StrictInt] = Field(default=None, description="set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius") + custom_field_1: Optional[StrictStr] = Field(default=None, description="you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field.") + custom_field_2: Optional[StrictStr] = Field(default=None, description="you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field.") + custom_field_3: Optional[StrictStr] = Field(default=None, description="you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field.") + metadata: Optional[Dict[str, Any]] = None + budget_update_project_times: Optional[StrictBool] = Field(default=None, description="this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. ") + __properties: ClassVar[List[str]] = ["name", "parent_task_id", "external_id", "description", "description_external", "bookable", "billable", "project_time_notes_required", "start_date", "end_date", "lock_date", "earliest_start_time", "latest_end_time", "budget_planning_type", "budget_hours_planned", "budget_hourly_rate", "budget_planned", "budget_include_non_billable_project_times", "location_inherited", "location", "location_restriction_radius_meters", "custom_field_1", "custom_field_2", "custom_field_3", "metadata", "budget_update_project_times"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaskUpdate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of location + if self.location: + _dict['location'] = self.location.to_dict() + # set to None if parent_task_id (nullable) is None + # and model_fields_set contains the field + if self.parent_task_id is None and "parent_task_id" in self.model_fields_set: + _dict['parent_task_id'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if description (nullable) is None + # and model_fields_set contains the field + if self.description is None and "description" in self.model_fields_set: + _dict['description'] = None + + # set to None if description_external (nullable) is None + # and model_fields_set contains the field + if self.description_external is None and "description_external" in self.model_fields_set: + _dict['description_external'] = None + + # set to None if start_date (nullable) is None + # and model_fields_set contains the field + if self.start_date is None and "start_date" in self.model_fields_set: + _dict['start_date'] = None + + # set to None if end_date (nullable) is None + # and model_fields_set contains the field + if self.end_date is None and "end_date" in self.model_fields_set: + _dict['end_date'] = None + + # set to None if lock_date (nullable) is None + # and model_fields_set contains the field + if self.lock_date is None and "lock_date" in self.model_fields_set: + _dict['lock_date'] = None + + # set to None if earliest_start_time (nullable) is None + # and model_fields_set contains the field + if self.earliest_start_time is None and "earliest_start_time" in self.model_fields_set: + _dict['earliest_start_time'] = None + + # set to None if latest_end_time (nullable) is None + # and model_fields_set contains the field + if self.latest_end_time is None and "latest_end_time" in self.model_fields_set: + _dict['latest_end_time'] = None + + # set to None if budget_hours_planned (nullable) is None + # and model_fields_set contains the field + if self.budget_hours_planned is None and "budget_hours_planned" in self.model_fields_set: + _dict['budget_hours_planned'] = None + + # set to None if budget_hourly_rate (nullable) is None + # and model_fields_set contains the field + if self.budget_hourly_rate is None and "budget_hourly_rate" in self.model_fields_set: + _dict['budget_hourly_rate'] = None + + # set to None if budget_planned (nullable) is None + # and model_fields_set contains the field + if self.budget_planned is None and "budget_planned" in self.model_fields_set: + _dict['budget_planned'] = None + + # set to None if location (nullable) is None + # and model_fields_set contains the field + if self.location is None and "location" in self.model_fields_set: + _dict['location'] = None + + # set to None if location_restriction_radius_meters (nullable) is None + # and model_fields_set contains the field + if self.location_restriction_radius_meters is None and "location_restriction_radius_meters" in self.model_fields_set: + _dict['location_restriction_radius_meters'] = None + + # set to None if custom_field_1 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_1 is None and "custom_field_1" in self.model_fields_set: + _dict['custom_field_1'] = None + + # set to None if custom_field_2 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_2 is None and "custom_field_2" in self.model_fields_set: + _dict['custom_field_2'] = None + + # set to None if custom_field_3 (nullable) is None + # and model_fields_set contains the field + if self.custom_field_3 is None and "custom_field_3" in self.model_fields_set: + _dict['custom_field_3'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaskUpdate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "parent_task_id": obj.get("parent_task_id"), + "external_id": obj.get("external_id"), + "description": obj.get("description"), + "description_external": obj.get("description_external"), + "bookable": obj.get("bookable"), + "billable": obj.get("billable"), + "project_time_notes_required": obj.get("project_time_notes_required"), + "start_date": obj.get("start_date"), + "end_date": obj.get("end_date"), + "lock_date": obj.get("lock_date"), + "earliest_start_time": obj.get("earliest_start_time"), + "latest_end_time": obj.get("latest_end_time"), + "budget_planning_type": obj.get("budget_planning_type"), + "budget_hours_planned": obj.get("budget_hours_planned"), + "budget_hourly_rate": obj.get("budget_hourly_rate"), + "budget_planned": obj.get("budget_planned"), + "budget_include_non_billable_project_times": obj.get("budget_include_non_billable_project_times"), + "location_inherited": obj.get("location_inherited"), + "location": TaskLocation.from_dict(obj["location"]) if obj.get("location") is not None else None, + "location_restriction_radius_meters": obj.get("location_restriction_radius_meters"), + "custom_field_1": obj.get("custom_field_1"), + "custom_field_2": obj.get("custom_field_2"), + "custom_field_3": obj.get("custom_field_3"), + "metadata": obj.get("metadata"), + "budget_update_project_times": obj.get("budget_update_project_times") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/tasks_page.py b/sdk/python/timr_api/models/tasks_page.py new file mode 100644 index 0000000..26ecf3e --- /dev/null +++ b/sdk/python/timr_api/models/tasks_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.task import Task +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TasksPage(BaseModel): + """ + TasksPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[Task] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TasksPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TasksPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [Task.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/tasks_reduced_page.py b/sdk/python/timr_api/models/tasks_reduced_page.py new file mode 100644 index 0000000..fd64454 --- /dev/null +++ b/sdk/python/timr_api/models/tasks_reduced_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.task_reduced import TaskReduced +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TasksReducedPage(BaseModel): + """ + TasksReducedPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[TaskReduced] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TasksReducedPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TasksReducedPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [TaskReduced.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/tasks_sort_column.py b/sdk/python/timr_api/models/tasks_sort_column.py new file mode 100644 index 0000000..2a41788 --- /dev/null +++ b/sdk/python/timr_api/models/tasks_sort_column.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class TasksSortColumn(str, Enum): + """ + Sort property for Tasks. `breadcrumbs` orders by the Task's full path, `name` by its own name only. + """ + + """ + allowed enum values + """ + BREADCRUMBS = 'breadcrumbs' + NAME = 'name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TasksSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/team.py b/sdk/python/timr_api/models/team.py new file mode 100644 index 0000000..f130590 --- /dev/null +++ b/sdk/python/timr_api/models/team.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.team_partial import TeamPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Team(BaseModel): + """ + A team, placed in the hierarchy by `parent_team`, with the full path from the root in `breadcrumbs`. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + breadcrumbs: StrictStr = Field(description="Full path of the entry within its hierarchy, including its own name.") + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + description: Optional[StrictStr] + parent_team: Optional[TeamPartial] + __properties: ClassVar[List[str]] = ["id", "name", "breadcrumbs", "external_id", "description", "parent_team"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Team from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of parent_team + if self.parent_team: + _dict['parent_team'] = self.parent_team.to_dict() + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if description (nullable) is None + # and model_fields_set contains the field + if self.description is None and "description" in self.model_fields_set: + _dict['description'] = None + + # set to None if parent_team (nullable) is None + # and model_fields_set contains the field + if self.parent_team is None and "parent_team" in self.model_fields_set: + _dict['parent_team'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Team from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "breadcrumbs": obj.get("breadcrumbs"), + "external_id": obj.get("external_id"), + "description": obj.get("description"), + "parent_team": TeamPartial.from_dict(obj["parent_team"]) if obj.get("parent_team") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/team_create.py b/sdk/python/timr_api/models/team_create.py new file mode 100644 index 0000000..9c78bf3 --- /dev/null +++ b/sdk/python/timr_api/models/team_create.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TeamCreate(BaseModel): + """ + TeamCreate + """ # noqa: E501 + name: StrictStr + description: Optional[StrictStr] = None + parent_team_id: Optional[StrictStr] = None + external_id: Optional[StrictStr] = Field(default=None, description="Identifier of the corresponding object in an external system. Set and owned by the client.") + __properties: ClassVar[List[str]] = ["name", "description", "parent_team_id", "external_id"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TeamCreate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if description (nullable) is None + # and model_fields_set contains the field + if self.description is None and "description" in self.model_fields_set: + _dict['description'] = None + + # set to None if parent_team_id (nullable) is None + # and model_fields_set contains the field + if self.parent_team_id is None and "parent_team_id" in self.model_fields_set: + _dict['parent_team_id'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TeamCreate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "description": obj.get("description"), + "parent_team_id": obj.get("parent_team_id"), + "external_id": obj.get("external_id") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/team_partial.py b/sdk/python/timr_api/models/team_partial.py new file mode 100644 index 0000000..0eb6145 --- /dev/null +++ b/sdk/python/timr_api/models/team_partial.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TeamPartial(BaseModel): + """ + TeamPartial + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + breadcrumbs: StrictStr = Field(description="Full path of the entry within its hierarchy, including its own name.") + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + __properties: ClassVar[List[str]] = ["id", "name", "breadcrumbs", "external_id"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TeamPartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TeamPartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "breadcrumbs": obj.get("breadcrumbs"), + "external_id": obj.get("external_id") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/team_update.py b/sdk/python/timr_api/models/team_update.py new file mode 100644 index 0000000..a5cfc7f --- /dev/null +++ b/sdk/python/timr_api/models/team_update.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TeamUpdate(BaseModel): + """ + TeamUpdate + """ # noqa: E501 + name: Optional[StrictStr] = None + description: Optional[StrictStr] = None + parent_team_id: Optional[StrictStr] = None + external_id: Optional[StrictStr] = Field(default=None, description="Identifier of the corresponding object in an external system. Set and owned by the client.") + __properties: ClassVar[List[str]] = ["name", "description", "parent_team_id", "external_id"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TeamUpdate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if description (nullable) is None + # and model_fields_set contains the field + if self.description is None and "description" in self.model_fields_set: + _dict['description'] = None + + # set to None if parent_team_id (nullable) is None + # and model_fields_set contains the field + if self.parent_team_id is None and "parent_team_id" in self.model_fields_set: + _dict['parent_team_id'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TeamUpdate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "description": obj.get("description"), + "parent_team_id": obj.get("parent_team_id"), + "external_id": obj.get("external_id") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/teams_page.py b/sdk/python/timr_api/models/teams_page.py new file mode 100644 index 0000000..98c9de7 --- /dev/null +++ b/sdk/python/timr_api/models/teams_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.team import Team +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TeamsPage(BaseModel): + """ + TeamsPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[Team] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TeamsPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TeamsPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [Team.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/teams_partial_page.py b/sdk/python/timr_api/models/teams_partial_page.py new file mode 100644 index 0000000..e8f56e6 --- /dev/null +++ b/sdk/python/timr_api/models/teams_partial_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.team_partial import TeamPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TeamsPartialPage(BaseModel): + """ + TeamsPartialPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[TeamPartial] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TeamsPartialPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TeamsPartialPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [TeamPartial.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/teams_sort_column.py b/sdk/python/timr_api/models/teams_sort_column.py new file mode 100644 index 0000000..10d5e08 --- /dev/null +++ b/sdk/python/timr_api/models/teams_sort_column.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class TeamsSortColumn(str, Enum): + """ + Sort property for Teams. `breadcrumbs` orders by the Team's full path, `name` by its own name only. + """ + + """ + allowed enum values + """ + BREADCRUMBS = 'breadcrumbs' + NAME = 'name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TeamsSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/time_account.py b/sdk/python/timr_api/models/time_account.py new file mode 100644 index 0000000..f5ca4a2 --- /dev/null +++ b/sdk/python/timr_api/models/time_account.py @@ -0,0 +1,144 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.flex_time_indicator import FlexTimeIndicator +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class TimeAccount(BaseModel): + """ + TimeAccount + """ # noqa: E501 + balance_last_period_minutes: Optional[StrictInt] + duration_actual_minutes: Optional[StrictInt] = Field(description="sum of durations in current period") + duration_target_minutes: Optional[StrictInt] = Field(description="target duration in current period") + balance_current_period_minutes: Optional[StrictInt] = Field(description="difference between target duration and actual duration") + balance_total_minutes: Optional[StrictInt] = Field(description="total duration until balancing date") + work_from_home_days_full: Optional[StrictInt] = Field(description="complete days worked from home in current period") + work_from_home_days_partial: Optional[StrictInt] = Field(description="partial days worked from home in current period") + flex_time_indicator: Optional[FlexTimeIndicator] = None + __properties: ClassVar[List[str]] = ["balance_last_period_minutes", "duration_actual_minutes", "duration_target_minutes", "balance_current_period_minutes", "balance_total_minutes", "work_from_home_days_full", "work_from_home_days_partial", "flex_time_indicator"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TimeAccount from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if balance_last_period_minutes (nullable) is None + # and model_fields_set contains the field + if self.balance_last_period_minutes is None and "balance_last_period_minutes" in self.model_fields_set: + _dict['balance_last_period_minutes'] = None + + # set to None if duration_actual_minutes (nullable) is None + # and model_fields_set contains the field + if self.duration_actual_minutes is None and "duration_actual_minutes" in self.model_fields_set: + _dict['duration_actual_minutes'] = None + + # set to None if duration_target_minutes (nullable) is None + # and model_fields_set contains the field + if self.duration_target_minutes is None and "duration_target_minutes" in self.model_fields_set: + _dict['duration_target_minutes'] = None + + # set to None if balance_current_period_minutes (nullable) is None + # and model_fields_set contains the field + if self.balance_current_period_minutes is None and "balance_current_period_minutes" in self.model_fields_set: + _dict['balance_current_period_minutes'] = None + + # set to None if balance_total_minutes (nullable) is None + # and model_fields_set contains the field + if self.balance_total_minutes is None and "balance_total_minutes" in self.model_fields_set: + _dict['balance_total_minutes'] = None + + # set to None if work_from_home_days_full (nullable) is None + # and model_fields_set contains the field + if self.work_from_home_days_full is None and "work_from_home_days_full" in self.model_fields_set: + _dict['work_from_home_days_full'] = None + + # set to None if work_from_home_days_partial (nullable) is None + # and model_fields_set contains the field + if self.work_from_home_days_partial is None and "work_from_home_days_partial" in self.model_fields_set: + _dict['work_from_home_days_partial'] = None + + # set to None if flex_time_indicator (nullable) is None + # and model_fields_set contains the field + if self.flex_time_indicator is None and "flex_time_indicator" in self.model_fields_set: + _dict['flex_time_indicator'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TimeAccount from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "balance_last_period_minutes": obj.get("balance_last_period_minutes"), + "duration_actual_minutes": obj.get("duration_actual_minutes"), + "duration_target_minutes": obj.get("duration_target_minutes"), + "balance_current_period_minutes": obj.get("balance_current_period_minutes"), + "balance_total_minutes": obj.get("balance_total_minutes"), + "work_from_home_days_full": obj.get("work_from_home_days_full"), + "work_from_home_days_partial": obj.get("work_from_home_days_partial"), + "flex_time_indicator": obj.get("flex_time_indicator") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/user.py b/sdk/python/timr_api/models/user.py new file mode 100644 index 0000000..6cb7c25 --- /dev/null +++ b/sdk/python/timr_api/models/user.py @@ -0,0 +1,206 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from timr_api.models.holiday_calendar_partial import HolidayCalendarPartial +from timr_api.models.work_schedule_model_partial import WorkScheduleModelPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class User(BaseModel): + """ + A user's identity (`firstname`, `lastname`, `email`), employment dates (`entry_date`, `resign_date`), and the assigned `work_schedule_model` and `holiday_calendar`. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + firstname: Optional[StrictStr] + lastname: Optional[StrictStr] + fullname: Optional[StrictStr] + email: Optional[Annotated[str, Field(min_length=1, strict=True)]] = Field(description="Email address must be either valid or null.") + employee_number: Optional[StrictStr] + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + login: Optional[Annotated[str, Field(strict=True)]] = None + entry_date: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + resign_date: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + work_schedule_model: Optional[WorkScheduleModelPartial] = None + holiday_calendar: Optional[HolidayCalendarPartial] = None + vacation_year_start: Optional[Annotated[str, Field(strict=True)]] = Field(default=None, description="recurring month and day on which the user's vacation year starts") + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["id", "firstname", "lastname", "fullname", "email", "employee_number", "external_id", "login", "entry_date", "resign_date", "work_schedule_model", "holiday_calendar", "vacation_year_start", "metadata"] + + @field_validator('login') + def login_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not isinstance(value, str): + value = str(value) + + if not re.match(r"^[A-Za-z0-9!#$%&\'*+\/=@\.?^_`{|}~-]*$", value): + raise ValueError(r"must validate the regular expression /^[A-Za-z0-9!#$%&'*+\/=@\.?^_`{|}~-]*$/") + return value + + @field_validator('vacation_year_start') + def vacation_year_start_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not isinstance(value, str): + value = str(value) + + if not re.match(r"^--(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$", value): + raise ValueError(r"must validate the regular expression /^--(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of User from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of work_schedule_model + if self.work_schedule_model: + _dict['work_schedule_model'] = self.work_schedule_model.to_dict() + # override the default output from pydantic by calling `to_dict()` of holiday_calendar + if self.holiday_calendar: + _dict['holiday_calendar'] = self.holiday_calendar.to_dict() + # set to None if firstname (nullable) is None + # and model_fields_set contains the field + if self.firstname is None and "firstname" in self.model_fields_set: + _dict['firstname'] = None + + # set to None if lastname (nullable) is None + # and model_fields_set contains the field + if self.lastname is None and "lastname" in self.model_fields_set: + _dict['lastname'] = None + + # set to None if fullname (nullable) is None + # and model_fields_set contains the field + if self.fullname is None and "fullname" in self.model_fields_set: + _dict['fullname'] = None + + # set to None if email (nullable) is None + # and model_fields_set contains the field + if self.email is None and "email" in self.model_fields_set: + _dict['email'] = None + + # set to None if employee_number (nullable) is None + # and model_fields_set contains the field + if self.employee_number is None and "employee_number" in self.model_fields_set: + _dict['employee_number'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if entry_date (nullable) is None + # and model_fields_set contains the field + if self.entry_date is None and "entry_date" in self.model_fields_set: + _dict['entry_date'] = None + + # set to None if resign_date (nullable) is None + # and model_fields_set contains the field + if self.resign_date is None and "resign_date" in self.model_fields_set: + _dict['resign_date'] = None + + # set to None if work_schedule_model (nullable) is None + # and model_fields_set contains the field + if self.work_schedule_model is None and "work_schedule_model" in self.model_fields_set: + _dict['work_schedule_model'] = None + + # set to None if vacation_year_start (nullable) is None + # and model_fields_set contains the field + if self.vacation_year_start is None and "vacation_year_start" in self.model_fields_set: + _dict['vacation_year_start'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of User from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "firstname": obj.get("firstname"), + "lastname": obj.get("lastname"), + "fullname": obj.get("fullname"), + "email": obj.get("email"), + "employee_number": obj.get("employee_number"), + "external_id": obj.get("external_id"), + "login": obj.get("login"), + "entry_date": obj.get("entry_date"), + "resign_date": obj.get("resign_date"), + "work_schedule_model": WorkScheduleModelPartial.from_dict(obj["work_schedule_model"]) if obj.get("work_schedule_model") is not None else None, + "holiday_calendar": HolidayCalendarPartial.from_dict(obj["holiday_calendar"]) if obj.get("holiday_calendar") is not None else None, + "vacation_year_start": obj.get("vacation_year_start"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/user_create.py b/sdk/python/timr_api/models/user_create.py new file mode 100644 index 0000000..f44386b --- /dev/null +++ b/sdk/python/timr_api/models/user_create.py @@ -0,0 +1,171 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class UserCreate(BaseModel): + """ + UserCreate + """ # noqa: E501 + login: Annotated[str, Field(min_length=1, strict=True)] + firstname: Optional[StrictStr] = None + lastname: Optional[StrictStr] = None + email: Optional[Annotated[str, Field(min_length=1, strict=True)]] = None + entry_date: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + resign_date: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + employee_number: Optional[StrictStr] = None + external_id: Optional[StrictStr] = None + metadata: Optional[Dict[str, Any]] = None + auth_provider: Optional[StrictStr] = None + auth_identifier: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["login", "firstname", "lastname", "email", "entry_date", "resign_date", "employee_number", "external_id", "metadata", "auth_provider", "auth_identifier"] + + @field_validator('login') + def login_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not isinstance(value, str): + value = str(value) + + if not re.match(r"^[A-Za-z0-9!#$%&\'*+\/=@\.?^_`{|}~-]*$", value): + raise ValueError(r"must validate the regular expression /^[A-Za-z0-9!#$%&'*+\/=@\.?^_`{|}~-]*$/") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UserCreate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if firstname (nullable) is None + # and model_fields_set contains the field + if self.firstname is None and "firstname" in self.model_fields_set: + _dict['firstname'] = None + + # set to None if lastname (nullable) is None + # and model_fields_set contains the field + if self.lastname is None and "lastname" in self.model_fields_set: + _dict['lastname'] = None + + # set to None if email (nullable) is None + # and model_fields_set contains the field + if self.email is None and "email" in self.model_fields_set: + _dict['email'] = None + + # set to None if entry_date (nullable) is None + # and model_fields_set contains the field + if self.entry_date is None and "entry_date" in self.model_fields_set: + _dict['entry_date'] = None + + # set to None if resign_date (nullable) is None + # and model_fields_set contains the field + if self.resign_date is None and "resign_date" in self.model_fields_set: + _dict['resign_date'] = None + + # set to None if employee_number (nullable) is None + # and model_fields_set contains the field + if self.employee_number is None and "employee_number" in self.model_fields_set: + _dict['employee_number'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + # set to None if auth_provider (nullable) is None + # and model_fields_set contains the field + if self.auth_provider is None and "auth_provider" in self.model_fields_set: + _dict['auth_provider'] = None + + # set to None if auth_identifier (nullable) is None + # and model_fields_set contains the field + if self.auth_identifier is None and "auth_identifier" in self.model_fields_set: + _dict['auth_identifier'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UserCreate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "login": obj.get("login"), + "firstname": obj.get("firstname"), + "lastname": obj.get("lastname"), + "email": obj.get("email"), + "entry_date": obj.get("entry_date"), + "resign_date": obj.get("resign_date"), + "employee_number": obj.get("employee_number"), + "external_id": obj.get("external_id"), + "metadata": obj.get("metadata"), + "auth_provider": obj.get("auth_provider"), + "auth_identifier": obj.get("auth_identifier") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/user_partial.py b/sdk/python/timr_api/models/user_partial.py new file mode 100644 index 0000000..24be0b3 --- /dev/null +++ b/sdk/python/timr_api/models/user_partial.py @@ -0,0 +1,132 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class UserPartial(BaseModel): + """ + UserPartial + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + firstname: Optional[StrictStr] + lastname: Optional[StrictStr] + fullname: Optional[StrictStr] + email: Optional[Annotated[str, Field(min_length=1, strict=True)]] = Field(description="Email address must be either valid or null.") + employee_number: Optional[StrictStr] + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + __properties: ClassVar[List[str]] = ["id", "firstname", "lastname", "fullname", "email", "employee_number", "external_id"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UserPartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if firstname (nullable) is None + # and model_fields_set contains the field + if self.firstname is None and "firstname" in self.model_fields_set: + _dict['firstname'] = None + + # set to None if lastname (nullable) is None + # and model_fields_set contains the field + if self.lastname is None and "lastname" in self.model_fields_set: + _dict['lastname'] = None + + # set to None if fullname (nullable) is None + # and model_fields_set contains the field + if self.fullname is None and "fullname" in self.model_fields_set: + _dict['fullname'] = None + + # set to None if email (nullable) is None + # and model_fields_set contains the field + if self.email is None and "email" in self.model_fields_set: + _dict['email'] = None + + # set to None if employee_number (nullable) is None + # and model_fields_set contains the field + if self.employee_number is None and "employee_number" in self.model_fields_set: + _dict['employee_number'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UserPartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "firstname": obj.get("firstname"), + "lastname": obj.get("lastname"), + "fullname": obj.get("fullname"), + "email": obj.get("email"), + "employee_number": obj.get("employee_number"), + "external_id": obj.get("external_id") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/user_update.py b/sdk/python/timr_api/models/user_update.py new file mode 100644 index 0000000..a24ea6a --- /dev/null +++ b/sdk/python/timr_api/models/user_update.py @@ -0,0 +1,160 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class UserUpdate(BaseModel): + """ + UserUpdate + """ # noqa: E501 + login: Optional[Annotated[str, Field(min_length=1, strict=True)]] = None + firstname: Optional[StrictStr] = None + lastname: Optional[StrictStr] = None + email: Optional[Annotated[str, Field(min_length=1, strict=True)]] = None + entry_date: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + resign_date: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + employee_number: Optional[StrictStr] = None + external_id: Optional[StrictStr] = None + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["login", "firstname", "lastname", "email", "entry_date", "resign_date", "employee_number", "external_id", "metadata"] + + @field_validator('login') + def login_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not isinstance(value, str): + value = str(value) + + if not re.match(r"^[A-Za-z0-9!#$%&\'*+\/=@\.?^_`{|}~-]*$", value): + raise ValueError(r"must validate the regular expression /^[A-Za-z0-9!#$%&'*+\/=@\.?^_`{|}~-]*$/") + return value + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UserUpdate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if firstname (nullable) is None + # and model_fields_set contains the field + if self.firstname is None and "firstname" in self.model_fields_set: + _dict['firstname'] = None + + # set to None if lastname (nullable) is None + # and model_fields_set contains the field + if self.lastname is None and "lastname" in self.model_fields_set: + _dict['lastname'] = None + + # set to None if email (nullable) is None + # and model_fields_set contains the field + if self.email is None and "email" in self.model_fields_set: + _dict['email'] = None + + # set to None if entry_date (nullable) is None + # and model_fields_set contains the field + if self.entry_date is None and "entry_date" in self.model_fields_set: + _dict['entry_date'] = None + + # set to None if resign_date (nullable) is None + # and model_fields_set contains the field + if self.resign_date is None and "resign_date" in self.model_fields_set: + _dict['resign_date'] = None + + # set to None if employee_number (nullable) is None + # and model_fields_set contains the field + if self.employee_number is None and "employee_number" in self.model_fields_set: + _dict['employee_number'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UserUpdate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "login": obj.get("login"), + "firstname": obj.get("firstname"), + "lastname": obj.get("lastname"), + "email": obj.get("email"), + "entry_date": obj.get("entry_date"), + "resign_date": obj.get("resign_date"), + "employee_number": obj.get("employee_number"), + "external_id": obj.get("external_id"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/users_page.py b/sdk/python/timr_api/models/users_page.py new file mode 100644 index 0000000..9a0ef52 --- /dev/null +++ b/sdk/python/timr_api/models/users_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.user import User +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class UsersPage(BaseModel): + """ + UsersPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[User] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UsersPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UsersPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [User.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/users_partial_page.py b/sdk/python/timr_api/models/users_partial_page.py new file mode 100644 index 0000000..7347847 --- /dev/null +++ b/sdk/python/timr_api/models/users_partial_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.user_partial import UserPartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class UsersPartialPage(BaseModel): + """ + UsersPartialPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[UserPartial] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UsersPartialPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UsersPartialPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [UserPartial.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/users_sort_column.py b/sdk/python/timr_api/models/users_sort_column.py new file mode 100644 index 0000000..7aa0e18 --- /dev/null +++ b/sdk/python/timr_api/models/users_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class UsersSortColumn(str, Enum): + """ + Sort property for Users. `name` orders by last name, then first name. + """ + + """ + allowed enum values + """ + NAME = 'name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of UsersSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/vacation_account.py b/sdk/python/timr_api/models/vacation_account.py new file mode 100644 index 0000000..ec801ed --- /dev/null +++ b/sdk/python/timr_api/models/vacation_account.py @@ -0,0 +1,156 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional +from timr_api.models.vacation_account_days import VacationAccountDays +from timr_api.models.vacation_account_minutes import VacationAccountMinutes +from pydantic import StrictStr, Field +from typing import Union, List, Set, Optional, Dict +from typing_extensions import Literal, Self + +VACATIONACCOUNT_ONE_OF_SCHEMAS = ["VacationAccountDays", "VacationAccountMinutes"] + +class VacationAccount(BaseModel): + """ + VacationAccount + """ + # data type: VacationAccountDays + oneof_schema_1_validator: Optional[VacationAccountDays] = None + # data type: VacationAccountMinutes + oneof_schema_2_validator: Optional[VacationAccountMinutes] = None + actual_instance: Optional[Union[VacationAccountDays, VacationAccountMinutes]] = None + one_of_schemas: Set[str] = { "VacationAccountDays", "VacationAccountMinutes" } + + model_config = ConfigDict( + validate_assignment=True, + protected_namespaces=(), + ) + + + discriminator_value_class_map: Dict[str, str] = { + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = VacationAccount.model_construct() + error_messages = [] + match = 0 + # validate data type: VacationAccountDays + if not isinstance(v, VacationAccountDays): + error_messages.append(f"Error! Input type `{type(v)}` is not `VacationAccountDays`") + else: + match += 1 + # validate data type: VacationAccountMinutes + if not isinstance(v, VacationAccountMinutes): + error_messages.append(f"Error! Input type `{type(v)}` is not `VacationAccountMinutes`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in VacationAccount with oneOf schemas: VacationAccountDays, VacationAccountMinutes. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in VacationAccount with oneOf schemas: VacationAccountDays, VacationAccountMinutes. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # use oneOf discriminator to lookup the data type + _data_type = json.loads(json_str).get("unit") + if not _data_type: + raise ValueError("Failed to lookup data type from the field `unit` in the input.") + + # check if data type is `VacationAccountDays` + if _data_type == "days": + instance.actual_instance = VacationAccountDays.from_json(json_str) + return instance + + # check if data type is `VacationAccountMinutes` + if _data_type == "minutes": + instance.actual_instance = VacationAccountMinutes.from_json(json_str) + return instance + + # deserialize data into VacationAccountDays + try: + instance.actual_instance = VacationAccountDays.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into VacationAccountMinutes + try: + instance.actual_instance = VacationAccountMinutes.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into VacationAccount with oneOf schemas: VacationAccountDays, VacationAccountMinutes. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into VacationAccount with oneOf schemas: VacationAccountDays, VacationAccountMinutes. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], VacationAccountDays, VacationAccountMinutes]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/sdk/python/timr_api/models/vacation_account_base.py b/sdk/python/timr_api/models/vacation_account_base.py new file mode 100644 index 0000000..63be82e --- /dev/null +++ b/sdk/python/timr_api/models/vacation_account_base.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List +from timr_api.models.vacation_unit import VacationUnit +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class VacationAccountBase(BaseModel): + """ + Members shared by every kind of vacation account, including the discriminator. + """ # noqa: E501 + unit: VacationUnit + __properties: ClassVar[List[str]] = ["unit"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of VacationAccountBase from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of VacationAccountBase from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "unit": obj.get("unit") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/vacation_account_days.py b/sdk/python/timr_api/models/vacation_account_days.py new file mode 100644 index 0000000..1df84a4 --- /dev/null +++ b/sdk/python/timr_api/models/vacation_account_days.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Optional, Union +from timr_api.models.vacation_unit import VacationUnit +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class VacationAccountDays(BaseModel): + """ + VacationAccountDays + """ # noqa: E501 + unit: VacationUnit + balance_last_period_days: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="vacation balance carried over from the previous vacation period, in days") + consumed_days: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="vacation consumed in the current vacation period, in days") + new_days: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="vacation newly granted in the current vacation period, in days") + balance_total_days: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="total vacation balance for the current vacation period, in days") + __properties: ClassVar[List[str]] = ["unit", "balance_last_period_days", "consumed_days", "new_days", "balance_total_days"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of VacationAccountDays from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if balance_last_period_days (nullable) is None + # and model_fields_set contains the field + if self.balance_last_period_days is None and "balance_last_period_days" in self.model_fields_set: + _dict['balance_last_period_days'] = None + + # set to None if consumed_days (nullable) is None + # and model_fields_set contains the field + if self.consumed_days is None and "consumed_days" in self.model_fields_set: + _dict['consumed_days'] = None + + # set to None if new_days (nullable) is None + # and model_fields_set contains the field + if self.new_days is None and "new_days" in self.model_fields_set: + _dict['new_days'] = None + + # set to None if balance_total_days (nullable) is None + # and model_fields_set contains the field + if self.balance_total_days is None and "balance_total_days" in self.model_fields_set: + _dict['balance_total_days'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of VacationAccountDays from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "unit": obj.get("unit"), + "balance_last_period_days": obj.get("balance_last_period_days"), + "consumed_days": obj.get("consumed_days"), + "new_days": obj.get("new_days"), + "balance_total_days": obj.get("balance_total_days") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/vacation_account_minutes.py b/sdk/python/timr_api/models/vacation_account_minutes.py new file mode 100644 index 0000000..d70938e --- /dev/null +++ b/sdk/python/timr_api/models/vacation_account_minutes.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Optional, Union +from timr_api.models.vacation_unit import VacationUnit +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class VacationAccountMinutes(BaseModel): + """ + VacationAccountMinutes + """ # noqa: E501 + unit: VacationUnit + balance_last_period_minutes: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="vacation balance carried over from the previous vacation period, in minutes") + consumed_minutes: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="vacation consumed in the current vacation period, in minutes") + new_minutes: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="vacation newly granted in the current vacation period, in minutes") + balance_total_minutes: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="total vacation balance for the current vacation period, in minutes") + __properties: ClassVar[List[str]] = ["unit", "balance_last_period_minutes", "consumed_minutes", "new_minutes", "balance_total_minutes"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of VacationAccountMinutes from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if balance_last_period_minutes (nullable) is None + # and model_fields_set contains the field + if self.balance_last_period_minutes is None and "balance_last_period_minutes" in self.model_fields_set: + _dict['balance_last_period_minutes'] = None + + # set to None if consumed_minutes (nullable) is None + # and model_fields_set contains the field + if self.consumed_minutes is None and "consumed_minutes" in self.model_fields_set: + _dict['consumed_minutes'] = None + + # set to None if new_minutes (nullable) is None + # and model_fields_set contains the field + if self.new_minutes is None and "new_minutes" in self.model_fields_set: + _dict['new_minutes'] = None + + # set to None if balance_total_minutes (nullable) is None + # and model_fields_set contains the field + if self.balance_total_minutes is None and "balance_total_minutes" in self.model_fields_set: + _dict['balance_total_minutes'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of VacationAccountMinutes from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "unit": obj.get("unit"), + "balance_last_period_minutes": obj.get("balance_last_period_minutes"), + "consumed_minutes": obj.get("consumed_minutes"), + "new_minutes": obj.get("new_minutes"), + "balance_total_minutes": obj.get("balance_total_minutes") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/vacation_unit.py b/sdk/python/timr_api/models/vacation_unit.py new file mode 100644 index 0000000..1537a06 --- /dev/null +++ b/sdk/python/timr_api/models/vacation_unit.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class VacationUnit(str, Enum): + """ + Unit a vacation entitlement is expressed in. + """ + + """ + allowed enum values + """ + DAYS = 'days' + MINUTES = 'minutes' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of VacationUnit from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/venue_partial.py b/sdk/python/timr_api/models/venue_partial.py new file mode 100644 index 0000000..425a419 --- /dev/null +++ b/sdk/python/timr_api/models/venue_partial.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictFloat, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class VenuePartial(BaseModel): + """ + VenuePartial + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + city: StrictStr + zip_code: StrictStr + street: StrictStr + street_number: StrictStr + country: StrictStr + lat: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Latitude in decimal degrees.") + lon: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, description="Longitude in decimal degrees.") + __properties: ClassVar[List[str]] = ["id", "name", "city", "zip_code", "street", "street_number", "country", "lat", "lon"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of VenuePartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of VenuePartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "city": obj.get("city"), + "zip_code": obj.get("zip_code"), + "street": obj.get("street"), + "street_number": obj.get("street_number"), + "country": obj.get("country"), + "lat": obj.get("lat"), + "lon": obj.get("lon") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/waypoint.py b/sdk/python/timr_api/models/waypoint.py new file mode 100644 index 0000000..c016827 --- /dev/null +++ b/sdk/python/timr_api/models/waypoint.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Union +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class Waypoint(BaseModel): + """ + Waypoint + """ # noqa: E501 + lat: Union[StrictFloat, StrictInt] + lon: Union[StrictFloat, StrictInt] + __properties: ClassVar[List[str]] = ["lat", "lon"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Waypoint from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Waypoint from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "lat": obj.get("lat"), + "lon": obj.get("lon") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/work_schedule_model.py b/sdk/python/timr_api/models/work_schedule_model.py new file mode 100644 index 0000000..8c3157a --- /dev/null +++ b/sdk/python/timr_api/models/work_schedule_model.py @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.work_schedule_model_type import WorkScheduleModelType +from timr_api.models.work_schedule_model_week import WorkScheduleModelWeek +from timr_api.models.working_time_rules import WorkingTimeRules +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkScheduleModel(BaseModel): + """ + The weekday targets a user is measured against: `weeks` holds the layout, `type` selects the calculation mode, and `working_time_rules` the recording constraints. + """ # noqa: E501 + id: StrictStr + name: StrictStr + type: WorkScheduleModelType = Field(description="working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks)") + weeks: List[WorkScheduleModelWeek] = Field(description="for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name ") + working_time_rules: Optional[WorkingTimeRules] + __properties: ClassVar[List[str]] = ["id", "name", "type", "weeks", "working_time_rules"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkScheduleModel from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in weeks (list) + _items = [] + if self.weeks: + for _item_weeks in self.weeks: + if _item_weeks: + _items.append(_item_weeks.to_dict()) + _dict['weeks'] = _items + # override the default output from pydantic by calling `to_dict()` of working_time_rules + if self.working_time_rules: + _dict['working_time_rules'] = self.working_time_rules.to_dict() + # set to None if working_time_rules (nullable) is None + # and model_fields_set contains the field + if self.working_time_rules is None and "working_time_rules" in self.model_fields_set: + _dict['working_time_rules'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkScheduleModel from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "type": obj.get("type"), + "weeks": [WorkScheduleModelWeek.from_dict(_item) for _item in obj["weeks"]] if obj.get("weeks") is not None else None, + "working_time_rules": WorkingTimeRules.from_dict(obj["working_time_rules"]) if obj.get("working_time_rules") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/work_schedule_model_partial.py b/sdk/python/timr_api/models/work_schedule_model_partial.py new file mode 100644 index 0000000..1c48841 --- /dev/null +++ b/sdk/python/timr_api/models/work_schedule_model_partial.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkScheduleModelPartial(BaseModel): + """ + WorkScheduleModelPartial + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + __properties: ClassVar[List[str]] = ["id", "name"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkScheduleModelPartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkScheduleModelPartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/work_schedule_model_sort_column.py b/sdk/python/timr_api/models/work_schedule_model_sort_column.py new file mode 100644 index 0000000..fb0a307 --- /dev/null +++ b/sdk/python/timr_api/models/work_schedule_model_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class WorkScheduleModelSortColumn(str, Enum): + """ + Sort property for Work Schedule Models. + """ + + """ + allowed enum values + """ + NAME = 'name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WorkScheduleModelSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/work_schedule_model_type.py b/sdk/python/timr_api/models/work_schedule_model_type.py new file mode 100644 index 0000000..a62a0c0 --- /dev/null +++ b/sdk/python/timr_api/models/work_schedule_model_type.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class WorkScheduleModelType(str, Enum): + """ + How the target working time of the model is defined. + """ + + """ + allowed enum values + """ + DAILY_TARGET_HOURS = 'daily_target_hours' + NORMAL_WORKING_TIME = 'normal_working_time' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WorkScheduleModelType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/work_schedule_model_week.py b/sdk/python/timr_api/models/work_schedule_model_week.py new file mode 100644 index 0000000..cb7ea6b --- /dev/null +++ b/sdk/python/timr_api/models/work_schedule_model_week.py @@ -0,0 +1,139 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.daily_work_schedule import DailyWorkSchedule +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkScheduleModelWeek(BaseModel): + """ + WorkScheduleModelWeek + """ # noqa: E501 + week_number: Optional[StrictInt] = Field(default=None, description="index of the week in alternating_weeks models (0-based); omitted for fixed_week models") + name: Optional[StrictStr] = Field(default=None, description="display name of the week in alternating_weeks models; omitted for fixed_week models") + target_duration_weekly_minutes: StrictInt = Field(description="value in minutes") + monday: DailyWorkSchedule + tuesday: DailyWorkSchedule + wednesday: DailyWorkSchedule + thursday: DailyWorkSchedule + friday: DailyWorkSchedule + saturday: DailyWorkSchedule + sunday: DailyWorkSchedule + __properties: ClassVar[List[str]] = ["week_number", "name", "target_duration_weekly_minutes", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkScheduleModelWeek from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of monday + if self.monday: + _dict['monday'] = self.monday.to_dict() + # override the default output from pydantic by calling `to_dict()` of tuesday + if self.tuesday: + _dict['tuesday'] = self.tuesday.to_dict() + # override the default output from pydantic by calling `to_dict()` of wednesday + if self.wednesday: + _dict['wednesday'] = self.wednesday.to_dict() + # override the default output from pydantic by calling `to_dict()` of thursday + if self.thursday: + _dict['thursday'] = self.thursday.to_dict() + # override the default output from pydantic by calling `to_dict()` of friday + if self.friday: + _dict['friday'] = self.friday.to_dict() + # override the default output from pydantic by calling `to_dict()` of saturday + if self.saturday: + _dict['saturday'] = self.saturday.to_dict() + # override the default output from pydantic by calling `to_dict()` of sunday + if self.sunday: + _dict['sunday'] = self.sunday.to_dict() + # set to None if week_number (nullable) is None + # and model_fields_set contains the field + if self.week_number is None and "week_number" in self.model_fields_set: + _dict['week_number'] = None + + # set to None if name (nullable) is None + # and model_fields_set contains the field + if self.name is None and "name" in self.model_fields_set: + _dict['name'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkScheduleModelWeek from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "week_number": obj.get("week_number"), + "name": obj.get("name"), + "target_duration_weekly_minutes": obj.get("target_duration_weekly_minutes"), + "monday": DailyWorkSchedule.from_dict(obj["monday"]) if obj.get("monday") is not None else None, + "tuesday": DailyWorkSchedule.from_dict(obj["tuesday"]) if obj.get("tuesday") is not None else None, + "wednesday": DailyWorkSchedule.from_dict(obj["wednesday"]) if obj.get("wednesday") is not None else None, + "thursday": DailyWorkSchedule.from_dict(obj["thursday"]) if obj.get("thursday") is not None else None, + "friday": DailyWorkSchedule.from_dict(obj["friday"]) if obj.get("friday") is not None else None, + "saturday": DailyWorkSchedule.from_dict(obj["saturday"]) if obj.get("saturday") is not None else None, + "sunday": DailyWorkSchedule.from_dict(obj["sunday"]) if obj.get("sunday") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/work_schedule_models_page.py b/sdk/python/timr_api/models/work_schedule_models_page.py new file mode 100644 index 0000000..7a6b13c --- /dev/null +++ b/sdk/python/timr_api/models/work_schedule_models_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.work_schedule_model import WorkScheduleModel +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkScheduleModelsPage(BaseModel): + """ + WorkScheduleModelsPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[WorkScheduleModel] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkScheduleModelsPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkScheduleModelsPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [WorkScheduleModel.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time.py b/sdk/python/timr_api/models/working_time.py new file mode 100644 index 0000000..30409c1 --- /dev/null +++ b/sdk/python/timr_api/models/working_time.py @@ -0,0 +1,212 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time import BreakTime +from timr_api.models.duration import Duration +from timr_api.models.location import Location +from timr_api.models.platform import Platform +from timr_api.models.user_partial import UserPartial +from timr_api.models.working_time_date_span_partial import WorkingTimeDateSpanPartial +from timr_api.models.working_time_status import WorkingTimeStatus +from timr_api.models.working_time_type_partial import WorkingTimeTypePartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTime(BaseModel): + """ + One continuous stretch from `start` to `end`, classified by its `working_time_type`. Attendance entries carry `break_times`, locations and the platform they were recorded on; an entry derived from a multi-day absence links back to its `working_time_date_span`. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + start: datetime = Field(description="RFC 3339 date-time (ISO-8601)") + end: Optional[datetime] = Field(description="RFC 3339 date-time (ISO-8601)") + break_time_total_minutes: StrictInt = Field(description="Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties") + break_times: List[BreakTime] + duration: Optional[Duration] + changed: StrictBool + notes: Optional[StrictStr] + user: UserPartial + working_time_type: WorkingTimeTypePartial + working_time_date_span: Optional[WorkingTimeDateSpanPartial] + start_location: Optional[Location] + end_location: Optional[Location] + start_platform: Optional[Platform] + end_platform: Optional[Platform] + last_modified: datetime = Field(description="Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) ") + last_modified_by: Optional[UserPartial] = Field(description="Read-only. The User who last modified the entry, or null if the change was not made in a user context. ") + status: WorkingTimeStatus + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["id", "start", "end", "break_time_total_minutes", "break_times", "duration", "changed", "notes", "user", "working_time_type", "working_time_date_span", "start_location", "end_location", "start_platform", "end_platform", "last_modified", "last_modified_by", "status", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTime from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in break_times (list) + _items = [] + if self.break_times: + for _item_break_times in self.break_times: + if _item_break_times: + _items.append(_item_break_times.to_dict()) + _dict['break_times'] = _items + # override the default output from pydantic by calling `to_dict()` of duration + if self.duration: + _dict['duration'] = self.duration.to_dict() + # override the default output from pydantic by calling `to_dict()` of user + if self.user: + _dict['user'] = self.user.to_dict() + # override the default output from pydantic by calling `to_dict()` of working_time_type + if self.working_time_type: + _dict['working_time_type'] = self.working_time_type.to_dict() + # override the default output from pydantic by calling `to_dict()` of working_time_date_span + if self.working_time_date_span: + _dict['working_time_date_span'] = self.working_time_date_span.to_dict() + # override the default output from pydantic by calling `to_dict()` of start_location + if self.start_location: + _dict['start_location'] = self.start_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_location + if self.end_location: + _dict['end_location'] = self.end_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of last_modified_by + if self.last_modified_by: + _dict['last_modified_by'] = self.last_modified_by.to_dict() + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if duration (nullable) is None + # and model_fields_set contains the field + if self.duration is None and "duration" in self.model_fields_set: + _dict['duration'] = None + + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if working_time_date_span (nullable) is None + # and model_fields_set contains the field + if self.working_time_date_span is None and "working_time_date_span" in self.model_fields_set: + _dict['working_time_date_span'] = None + + # set to None if start_location (nullable) is None + # and model_fields_set contains the field + if self.start_location is None and "start_location" in self.model_fields_set: + _dict['start_location'] = None + + # set to None if end_location (nullable) is None + # and model_fields_set contains the field + if self.end_location is None and "end_location" in self.model_fields_set: + _dict['end_location'] = None + + # set to None if start_platform (nullable) is None + # and model_fields_set contains the field + if self.start_platform is None and "start_platform" in self.model_fields_set: + _dict['start_platform'] = None + + # set to None if end_platform (nullable) is None + # and model_fields_set contains the field + if self.end_platform is None and "end_platform" in self.model_fields_set: + _dict['end_platform'] = None + + # set to None if last_modified_by (nullable) is None + # and model_fields_set contains the field + if self.last_modified_by is None and "last_modified_by" in self.model_fields_set: + _dict['last_modified_by'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTime from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "start": obj.get("start"), + "end": obj.get("end"), + "break_time_total_minutes": obj.get("break_time_total_minutes"), + "break_times": [BreakTime.from_dict(_item) for _item in obj["break_times"]] if obj.get("break_times") is not None else None, + "duration": Duration.from_dict(obj["duration"]) if obj.get("duration") is not None else None, + "changed": obj.get("changed"), + "notes": obj.get("notes"), + "user": UserPartial.from_dict(obj["user"]) if obj.get("user") is not None else None, + "working_time_type": WorkingTimeTypePartial.from_dict(obj["working_time_type"]) if obj.get("working_time_type") is not None else None, + "working_time_date_span": WorkingTimeDateSpanPartial.from_dict(obj["working_time_date_span"]) if obj.get("working_time_date_span") is not None else None, + "start_location": Location.from_dict(obj["start_location"]) if obj.get("start_location") is not None else None, + "end_location": Location.from_dict(obj["end_location"]) if obj.get("end_location") is not None else None, + "start_platform": obj.get("start_platform"), + "end_platform": obj.get("end_platform"), + "last_modified": obj.get("last_modified"), + "last_modified_by": UserPartial.from_dict(obj["last_modified_by"]) if obj.get("last_modified_by") is not None else None, + "status": obj.get("status"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_create.py b/sdk/python/timr_api/models/working_time_create.py new file mode 100644 index 0000000..12c6969 --- /dev/null +++ b/sdk/python/timr_api/models/working_time_create.py @@ -0,0 +1,159 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time_update import BreakTimeUpdate +from timr_api.models.duration_type import DurationType +from timr_api.models.location_create import LocationCreate +from timr_api.models.working_time_status import WorkingTimeStatus +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeCreate(BaseModel): + """ + WorkingTimeCreate + """ # noqa: E501 + start: datetime = Field(description="For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) ") + end: Optional[datetime] = Field(default=None, description="For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) ") + break_times: Optional[List[BreakTimeUpdate]] = None + duration_type: Optional[DurationType] = Field(default=None, description="Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only") + changed: StrictBool + notes: Optional[StrictStr] = None + working_time_type_id: StrictStr + status: WorkingTimeStatus + metadata: Optional[Dict[str, Any]] = None + user_id: StrictStr + start_location: Optional[LocationCreate] = None + end_location: Optional[LocationCreate] = None + __properties: ClassVar[List[str]] = ["start", "end", "break_times", "duration_type", "changed", "notes", "working_time_type_id", "status", "metadata", "user_id", "start_location", "end_location"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeCreate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in break_times (list) + _items = [] + if self.break_times: + for _item_break_times in self.break_times: + if _item_break_times: + _items.append(_item_break_times.to_dict()) + _dict['break_times'] = _items + # override the default output from pydantic by calling `to_dict()` of start_location + if self.start_location: + _dict['start_location'] = self.start_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_location + if self.end_location: + _dict['end_location'] = self.end_location.to_dict() + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if duration_type (nullable) is None + # and model_fields_set contains the field + if self.duration_type is None and "duration_type" in self.model_fields_set: + _dict['duration_type'] = None + + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + # set to None if start_location (nullable) is None + # and model_fields_set contains the field + if self.start_location is None and "start_location" in self.model_fields_set: + _dict['start_location'] = None + + # set to None if end_location (nullable) is None + # and model_fields_set contains the field + if self.end_location is None and "end_location" in self.model_fields_set: + _dict['end_location'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeCreate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end"), + "break_times": [BreakTimeUpdate.from_dict(_item) for _item in obj["break_times"]] if obj.get("break_times") is not None else None, + "duration_type": obj.get("duration_type"), + "changed": obj.get("changed"), + "notes": obj.get("notes"), + "working_time_type_id": obj.get("working_time_type_id"), + "status": obj.get("status"), + "metadata": obj.get("metadata"), + "user_id": obj.get("user_id"), + "start_location": LocationCreate.from_dict(obj["start_location"]) if obj.get("start_location") is not None else None, + "end_location": LocationCreate.from_dict(obj["end_location"]) if obj.get("end_location") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_date_span.py b/sdk/python/timr_api/models/working_time_date_span.py new file mode 100644 index 0000000..b83748b --- /dev/null +++ b/sdk/python/timr_api/models/working_time_date_span.py @@ -0,0 +1,146 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date, datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.user_partial import UserPartial +from timr_api.models.working_time_type_partial import WorkingTimeTypePartial +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeDateSpan(BaseModel): + """ + A span from `start` to `end` of a single `working_time_type`. Every working time derived for a covered day links back to it via `WorkingTime.working_time_date_span`. It can be created directly or become effective through an approved request. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + start: date = Field(description="RFC 3339 date (ISO-8601)") + start_half_day: StrictBool = Field(description="Marks the first day of the working time date span as a half day.") + end: date = Field(description="RFC 3339 date (ISO-8601)") + end_half_day: StrictBool = Field(description="Marks the last day of the working time date span as a half day.") + notes: Optional[StrictStr] + user: UserPartial + working_time_type: WorkingTimeTypePartial + substitute: Optional[UserPartial] = None + last_modified: datetime = Field(description="Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) ") + last_modified_by: Optional[UserPartial] = Field(description="Read-only. The User who last modified the entry, or null if the change was not made in a user context. ") + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["id", "start", "start_half_day", "end", "end_half_day", "notes", "user", "working_time_type", "substitute", "last_modified", "last_modified_by", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpan from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of user + if self.user: + _dict['user'] = self.user.to_dict() + # override the default output from pydantic by calling `to_dict()` of working_time_type + if self.working_time_type: + _dict['working_time_type'] = self.working_time_type.to_dict() + # override the default output from pydantic by calling `to_dict()` of substitute + if self.substitute: + _dict['substitute'] = self.substitute.to_dict() + # override the default output from pydantic by calling `to_dict()` of last_modified_by + if self.last_modified_by: + _dict['last_modified_by'] = self.last_modified_by.to_dict() + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if substitute (nullable) is None + # and model_fields_set contains the field + if self.substitute is None and "substitute" in self.model_fields_set: + _dict['substitute'] = None + + # set to None if last_modified_by (nullable) is None + # and model_fields_set contains the field + if self.last_modified_by is None and "last_modified_by" in self.model_fields_set: + _dict['last_modified_by'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpan from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "start": obj.get("start"), + "start_half_day": obj.get("start_half_day"), + "end": obj.get("end"), + "end_half_day": obj.get("end_half_day"), + "notes": obj.get("notes"), + "user": UserPartial.from_dict(obj["user"]) if obj.get("user") is not None else None, + "working_time_type": WorkingTimeTypePartial.from_dict(obj["working_time_type"]) if obj.get("working_time_type") is not None else None, + "substitute": UserPartial.from_dict(obj["substitute"]) if obj.get("substitute") is not None else None, + "last_modified": obj.get("last_modified"), + "last_modified_by": UserPartial.from_dict(obj["last_modified_by"]) if obj.get("last_modified_by") is not None else None, + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_date_span_create.py b/sdk/python/timr_api/models/working_time_date_span_create.py new file mode 100644 index 0000000..667dca9 --- /dev/null +++ b/sdk/python/timr_api/models/working_time_date_span_create.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeDateSpanCreate(BaseModel): + """ + WorkingTimeDateSpanCreate + """ # noqa: E501 + start: date = Field(description="RFC 3339 date (ISO-8601)") + start_half_day: Optional[StrictBool] = None + end: date = Field(description="RFC 3339 date (ISO-8601)") + end_half_day: Optional[StrictBool] = None + notes: Optional[StrictStr] = None + working_time_type_id: StrictStr + substitute_id: Optional[StrictStr] = None + metadata: Optional[Dict[str, Any]] = None + user_id: StrictStr + __properties: ClassVar[List[str]] = ["start", "start_half_day", "end", "end_half_day", "notes", "working_time_type_id", "substitute_id", "metadata", "user_id"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpanCreate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if substitute_id (nullable) is None + # and model_fields_set contains the field + if self.substitute_id is None and "substitute_id" in self.model_fields_set: + _dict['substitute_id'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpanCreate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "start_half_day": obj.get("start_half_day"), + "end": obj.get("end"), + "end_half_day": obj.get("end_half_day"), + "notes": obj.get("notes"), + "working_time_type_id": obj.get("working_time_type_id"), + "substitute_id": obj.get("substitute_id"), + "metadata": obj.get("metadata"), + "user_id": obj.get("user_id") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_date_span_page.py b/sdk/python/timr_api/models/working_time_date_span_page.py new file mode 100644 index 0000000..2b4125a --- /dev/null +++ b/sdk/python/timr_api/models/working_time_date_span_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.working_time_date_span import WorkingTimeDateSpan +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeDateSpanPage(BaseModel): + """ + WorkingTimeDateSpanPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[WorkingTimeDateSpan] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpanPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpanPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [WorkingTimeDateSpan.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_date_span_partial.py b/sdk/python/timr_api/models/working_time_date_span_partial.py new file mode 100644 index 0000000..e665abc --- /dev/null +++ b/sdk/python/timr_api/models/working_time_date_span_partial.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeDateSpanPartial(BaseModel): + """ + References the date span this working time belongs to, if any. All working times generated for a date span reference the same span; working times recorded on their own have none. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + __properties: ClassVar[List[str]] = ["id"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpanPartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpanPartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_date_span_update.py b/sdk/python/timr_api/models/working_time_date_span_update.py new file mode 100644 index 0000000..5091f5a --- /dev/null +++ b/sdk/python/timr_api/models/working_time_date_span_update.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import date +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeDateSpanUpdate(BaseModel): + """ + WorkingTimeDateSpanUpdate + """ # noqa: E501 + start: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + start_half_day: Optional[StrictBool] = None + end: Optional[date] = Field(default=None, description="RFC 3339 date (ISO-8601)") + end_half_day: Optional[StrictBool] = None + notes: Optional[StrictStr] = None + working_time_type_id: Optional[StrictStr] = None + substitute_id: Optional[StrictStr] = None + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["start", "start_half_day", "end", "end_half_day", "notes", "working_time_type_id", "substitute_id", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpanUpdate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if substitute_id (nullable) is None + # and model_fields_set contains the field + if self.substitute_id is None and "substitute_id" in self.model_fields_set: + _dict['substitute_id'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeDateSpanUpdate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "start_half_day": obj.get("start_half_day"), + "end": obj.get("end"), + "end_half_day": obj.get("end_half_day"), + "notes": obj.get("notes"), + "working_time_type_id": obj.get("working_time_type_id"), + "substitute_id": obj.get("substitute_id"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_date_spans_sort_column.py b/sdk/python/timr_api/models/working_time_date_spans_sort_column.py new file mode 100644 index 0000000..d52f40f --- /dev/null +++ b/sdk/python/timr_api/models/working_time_date_spans_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class WorkingTimeDateSpansSortColumn(str, Enum): + """ + Sort property for Working Time Date Spans. + """ + + """ + allowed enum values + """ + START = 'start' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WorkingTimeDateSpansSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/working_time_rules.py b/sdk/python/timr_api/models/working_time_rules.py new file mode 100644 index 0000000..2dd7a04 --- /dev/null +++ b/sdk/python/timr_api/models/working_time_rules.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeRules(BaseModel): + """ + WorkingTimeRules + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + __properties: ClassVar[List[str]] = ["id", "name"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeRules from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeRules from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_status.py b/sdk/python/timr_api/models/working_time_status.py new file mode 100644 index 0000000..249671c --- /dev/null +++ b/sdk/python/timr_api/models/working_time_status.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class WorkingTimeStatus(str, Enum): + """ + Processing state of a Working Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, closed and archived. + """ + + """ + allowed enum values + """ + RUNNING = 'running' + PAUSED = 'paused' + CHANGEABLE = 'changeable' + LOCKED = 'locked' + APPROVED = 'approved' + CLOSED = 'closed' + ARCHIVED = 'archived' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WorkingTimeStatus from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/working_time_type.py b/sdk/python/timr_api/models/working_time_type.py new file mode 100644 index 0000000..28e76cb --- /dev/null +++ b/sdk/python/timr_api/models/working_time_type.py @@ -0,0 +1,133 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.duration_unit import DurationUnit +from timr_api.models.recording_mode_user import RecordingModeUser +from timr_api.models.working_time_type_category import WorkingTimeTypeCategory +from timr_api.models.working_time_type_sub_category import WorkingTimeTypeSubCategory +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeType(BaseModel): + """ + A working time type. `category` and `sub_category` place it in the classification, `edit_unit` decides whether it is recorded by time or by day, and `requires_substitute` governs how it is recorded. + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + short_name: Optional[StrictStr] + description: Optional[StrictStr] + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + edit_unit: DurationUnit + category: WorkingTimeTypeCategory + sub_category: Optional[WorkingTimeTypeSubCategory] + recording_mode_user: RecordingModeUser = Field(description="Specifies how the user can record this working time type. ") + archived: StrictBool + requires_substitute: Optional[StrictBool] = None + __properties: ClassVar[List[str]] = ["id", "name", "short_name", "description", "external_id", "edit_unit", "category", "sub_category", "recording_mode_user", "archived", "requires_substitute"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeType from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if short_name (nullable) is None + # and model_fields_set contains the field + if self.short_name is None and "short_name" in self.model_fields_set: + _dict['short_name'] = None + + # set to None if description (nullable) is None + # and model_fields_set contains the field + if self.description is None and "description" in self.model_fields_set: + _dict['description'] = None + + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + # set to None if sub_category (nullable) is None + # and model_fields_set contains the field + if self.sub_category is None and "sub_category" in self.model_fields_set: + _dict['sub_category'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeType from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "short_name": obj.get("short_name"), + "description": obj.get("description"), + "external_id": obj.get("external_id"), + "edit_unit": obj.get("edit_unit"), + "category": obj.get("category"), + "sub_category": obj.get("sub_category"), + "recording_mode_user": obj.get("recording_mode_user"), + "archived": obj.get("archived"), + "requires_substitute": obj.get("requires_substitute") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_type_category.py b/sdk/python/timr_api/models/working_time_type_category.py new file mode 100644 index 0000000..f742fac --- /dev/null +++ b/sdk/python/timr_api/models/working_time_type_category.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class WorkingTimeTypeCategory(str, Enum): + """ + Category of a Working Time Type. `attendance_time` counts as time at work, the remaining categories describe kinds of absence. + """ + + """ + allowed enum values + """ + ATTENDANCE_TIME = 'attendance_time' + VACATION = 'vacation' + PAID_TIME_OFF = 'paid_time_off' + UNPAID_TIME_OFF = 'unpaid_time_off' + SUSPENSION = 'suspension' + BREAK_TIME = 'break_time' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WorkingTimeTypeCategory from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/working_time_type_partial.py b/sdk/python/timr_api/models/working_time_type_partial.py new file mode 100644 index 0000000..c886e22 --- /dev/null +++ b/sdk/python/timr_api/models/working_time_type_partial.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeTypePartial(BaseModel): + """ + WorkingTimeTypePartial + """ # noqa: E501 + id: StrictStr = Field(description="Unique identifier. Treat it as an opaque string.") + name: StrictStr + external_id: Optional[StrictStr] = Field(description="Identifier of the corresponding object in an external system. Set and owned by the client.") + __properties: ClassVar[List[str]] = ["id", "name", "external_id"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeTypePartial from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # set to None if external_id (nullable) is None + # and model_fields_set contains the field + if self.external_id is None and "external_id" in self.model_fields_set: + _dict['external_id'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeTypePartial from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "external_id": obj.get("external_id") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_type_sub_category.py b/sdk/python/timr_api/models/working_time_type_sub_category.py new file mode 100644 index 0000000..d1b233a --- /dev/null +++ b/sdk/python/timr_api/models/working_time_type_sub_category.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class WorkingTimeTypeSubCategory(str, Enum): + """ + Further classification of a Working Time Type within its category. + """ + + """ + allowed enum values + """ + PRESENT = 'present' + WORK_FROM_HOME = 'work_from_home' + AWAY = 'away' + ACTIVE_DRIVING_TIME = 'active_driving_time' + PASSIVE_TRAVELLING_TIME = 'passive_travelling_time' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WorkingTimeTypeSubCategory from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/working_time_types_page.py b/sdk/python/timr_api/models/working_time_types_page.py new file mode 100644 index 0000000..bf5b3ab --- /dev/null +++ b/sdk/python/timr_api/models/working_time_types_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.working_time_type import WorkingTimeType +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeTypesPage(BaseModel): + """ + WorkingTimeTypesPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[WorkingTimeType] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeTypesPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeTypesPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [WorkingTimeType.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_types_sort_column.py b/sdk/python/timr_api/models/working_time_types_sort_column.py new file mode 100644 index 0000000..96cdf7f --- /dev/null +++ b/sdk/python/timr_api/models/working_time_types_sort_column.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class WorkingTimeTypesSortColumn(str, Enum): + """ + Sort property for Working Time Types. + """ + + """ + allowed enum values + """ + NAME = 'name' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WorkingTimeTypesSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/models/working_time_update.py b/sdk/python/timr_api/models/working_time_update.py new file mode 100644 index 0000000..820ec20 --- /dev/null +++ b/sdk/python/timr_api/models/working_time_update.py @@ -0,0 +1,157 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time_update import BreakTimeUpdate +from timr_api.models.duration_type import DurationType +from timr_api.models.location_update import LocationUpdate +from timr_api.models.working_time_status import WorkingTimeStatus +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeUpdate(BaseModel): + """ + WorkingTimeUpdate + """ # noqa: E501 + start: Optional[datetime] = Field(default=None, description="For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) ") + end: Optional[datetime] = Field(default=None, description="For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) ") + break_times: Optional[List[BreakTimeUpdate]] = None + duration_type: Optional[DurationType] = Field(default=None, description="Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only") + changed: Optional[StrictBool] = None + notes: Optional[StrictStr] = None + working_time_type_id: Optional[StrictStr] = None + status: Optional[WorkingTimeStatus] = None + metadata: Optional[Dict[str, Any]] = None + start_location: Optional[LocationUpdate] = None + end_location: Optional[LocationUpdate] = None + __properties: ClassVar[List[str]] = ["start", "end", "break_times", "duration_type", "changed", "notes", "working_time_type_id", "status", "metadata", "start_location", "end_location"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeUpdate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in break_times (list) + _items = [] + if self.break_times: + for _item_break_times in self.break_times: + if _item_break_times: + _items.append(_item_break_times.to_dict()) + _dict['break_times'] = _items + # override the default output from pydantic by calling `to_dict()` of start_location + if self.start_location: + _dict['start_location'] = self.start_location.to_dict() + # override the default output from pydantic by calling `to_dict()` of end_location + if self.end_location: + _dict['end_location'] = self.end_location.to_dict() + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if duration_type (nullable) is None + # and model_fields_set contains the field + if self.duration_type is None and "duration_type" in self.model_fields_set: + _dict['duration_type'] = None + + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + # set to None if start_location (nullable) is None + # and model_fields_set contains the field + if self.start_location is None and "start_location" in self.model_fields_set: + _dict['start_location'] = None + + # set to None if end_location (nullable) is None + # and model_fields_set contains the field + if self.end_location is None and "end_location" in self.model_fields_set: + _dict['end_location'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeUpdate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end"), + "break_times": [BreakTimeUpdate.from_dict(_item) for _item in obj["break_times"]] if obj.get("break_times") is not None else None, + "duration_type": obj.get("duration_type"), + "changed": obj.get("changed"), + "notes": obj.get("notes"), + "working_time_type_id": obj.get("working_time_type_id"), + "status": obj.get("status"), + "metadata": obj.get("metadata"), + "start_location": LocationUpdate.from_dict(obj["start_location"]) if obj.get("start_location") is not None else None, + "end_location": LocationUpdate.from_dict(obj["end_location"]) if obj.get("end_location") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_time_upsert.py b/sdk/python/timr_api/models/working_time_upsert.py new file mode 100644 index 0000000..7875335 --- /dev/null +++ b/sdk/python/timr_api/models/working_time_upsert.py @@ -0,0 +1,136 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.break_time_update import BreakTimeUpdate +from timr_api.models.duration_type import DurationType +from timr_api.models.working_time_status import WorkingTimeStatus +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimeUpsert(BaseModel): + """ + WorkingTimeUpsert + """ # noqa: E501 + start: Optional[datetime] = Field(default=None, description="For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) ") + end: Optional[datetime] = Field(default=None, description="For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) ") + break_times: Optional[List[BreakTimeUpdate]] = None + duration_type: Optional[DurationType] = Field(default=None, description="Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only") + changed: Optional[StrictBool] = None + notes: Optional[StrictStr] = None + working_time_type_id: Optional[StrictStr] = None + status: Optional[WorkingTimeStatus] = None + metadata: Optional[Dict[str, Any]] = None + __properties: ClassVar[List[str]] = ["start", "end", "break_times", "duration_type", "changed", "notes", "working_time_type_id", "status", "metadata"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimeUpsert from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in break_times (list) + _items = [] + if self.break_times: + for _item_break_times in self.break_times: + if _item_break_times: + _items.append(_item_break_times.to_dict()) + _dict['break_times'] = _items + # set to None if end (nullable) is None + # and model_fields_set contains the field + if self.end is None and "end" in self.model_fields_set: + _dict['end'] = None + + # set to None if duration_type (nullable) is None + # and model_fields_set contains the field + if self.duration_type is None and "duration_type" in self.model_fields_set: + _dict['duration_type'] = None + + # set to None if notes (nullable) is None + # and model_fields_set contains the field + if self.notes is None and "notes" in self.model_fields_set: + _dict['notes'] = None + + # set to None if metadata (nullable) is None + # and model_fields_set contains the field + if self.metadata is None and "metadata" in self.model_fields_set: + _dict['metadata'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimeUpsert from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "start": obj.get("start"), + "end": obj.get("end"), + "break_times": [BreakTimeUpdate.from_dict(_item) for _item in obj["break_times"]] if obj.get("break_times") is not None else None, + "duration_type": obj.get("duration_type"), + "changed": obj.get("changed"), + "notes": obj.get("notes"), + "working_time_type_id": obj.get("working_time_type_id"), + "status": obj.get("status"), + "metadata": obj.get("metadata") + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_times_page.py b/sdk/python/timr_api/models/working_times_page.py new file mode 100644 index 0000000..0058c5d --- /dev/null +++ b/sdk/python/timr_api/models/working_times_page.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from timr_api.models.working_time import WorkingTime +from typing import Optional, Set +from typing_extensions import Self +from pydantic_core import to_jsonable_python + +class WorkingTimesPage(BaseModel): + """ + WorkingTimesPage + """ # noqa: E501 + next_page_token: Optional[StrictStr] = Field(description="Token for the next page, or null when this is the last page.") + data: List[WorkingTime] + __properties: ClassVar[List[str]] = ["next_page_token", "data"] + + model_config = ConfigDict( + validate_by_name=True, + validate_by_alias=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(to_jsonable_python(self.to_dict())) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of WorkingTimesPage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data (list) + _items = [] + if self.data: + for _item_data in self.data: + if _item_data: + _items.append(_item_data.to_dict()) + _dict['data'] = _items + # set to None if next_page_token (nullable) is None + # and model_fields_set contains the field + if self.next_page_token is None and "next_page_token" in self.model_fields_set: + _dict['next_page_token'] = None + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of WorkingTimesPage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "next_page_token": obj.get("next_page_token"), + "data": [WorkingTime.from_dict(_item) for _item in obj["data"]] if obj.get("data") is not None else None + }) + return _obj + + diff --git a/sdk/python/timr_api/models/working_times_sort_column.py b/sdk/python/timr_api/models/working_times_sort_column.py new file mode 100644 index 0000000..89bbb01 --- /dev/null +++ b/sdk/python/timr_api/models/working_times_sort_column.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class WorkingTimesSortColumn(str, Enum): + """ + Sort property for Working Times. + """ + + """ + allowed enum values + """ + START = 'start' + LAST_MODIFIED = 'last_modified' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of WorkingTimesSortColumn from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sdk/python/timr_api/py.typed b/sdk/python/timr_api/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/sdk/python/timr_api/rest.py b/sdk/python/timr_api/rest.py new file mode 100644 index 0000000..cac7c73 --- /dev/null +++ b/sdk/python/timr_api/rest.py @@ -0,0 +1,264 @@ +# coding: utf-8 + +""" + timr API + + REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + + The version of the OpenAPI document: 1.0.0 + Contact: info@timr.com + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import json +import re +import ssl + +import urllib3 + +from timr_api.exceptions import ApiException, ApiValueError + +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse + + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + + +class RESTResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status + self.reason = resp.reason + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data + + @property + def headers(self): + """Returns a dictionary of response headers.""" + return self.response.headers + + def getheaders(self): + """Returns a dictionary of the response headers; use ``headers`` instead.""" + return self.response.headers + + def getheader(self, name, default=None): + """Returns a given response header; use ``headers.get()`` instead.""" + return self.response.headers.get(name, default) + + +class RESTClientObject: + + def __init__(self, configuration) -> None: + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + "ca_cert_data": configuration.ca_cert_data, + } + if configuration.assert_hostname is not None: + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) + + if configuration.retries is not None: + pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + pool_args['socket_options'] = configuration.socket_options + + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize + + # https pool manager + self.pool_manager: urllib3.PoolManager + + if configuration.proxy: + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) + else: + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): + timeout = urllib3.Timeout(total=_request_timeout) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], + read=_request_timeout[1] + ) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + timeout=timeout, + headers=headers, + preload_content=False + ) + # Pass a `string` parameter directly in the body to support + # other content types than JSON when `body` argument is + # provided in serialized form. + elif isinstance(body, str) or isinstance(body, bytes): + r = self.pool_manager.request( + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'].startswith('text/') and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=False, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) + except urllib3.exceptions.SSLError as e: + msg = "\n".join([type(e).__name__, str(e)]) + raise ApiException(status=0, reason=msg) + + return RESTResponse(r) diff --git a/sdk/python/tox.ini b/sdk/python/tox.ini new file mode 100644 index 0000000..b0be635 --- /dev/null +++ b/sdk/python/tox.ini @@ -0,0 +1,9 @@ +[tox] +envlist = py3 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + pytest --cov=timr_api diff --git a/sdk/swift/.gitignore b/sdk/swift/.gitignore new file mode 100644 index 0000000..d919f54 --- /dev/null +++ b/sdk/swift/.gitignore @@ -0,0 +1,2 @@ +# OpenApiGenerator generated meta files +.openapi-generator diff --git a/sdk/swift/.openapi-generator-ignore b/sdk/swift/.openapi-generator-ignore new file mode 100644 index 0000000..5ab6de1 --- /dev/null +++ b/sdk/swift/.openapi-generator-ignore @@ -0,0 +1,12 @@ +.gitignore +Cartfile +git_push.sh +# Scaffolding is hand-maintained: it names the package/module TimrApi while projectName only +# drives the generated API class (TimrAPI). Regenerating these would rename the module. +project.yml +README.md +Package.swift +*.podspec +# Markdown docs are repo-only: neither the wheel nor the SPM/CocoaPods package ships them, +# and the reference lives at developer.timr.com. +docs/** diff --git a/sdk/swift/.swiftformat b/sdk/swift/.swiftformat new file mode 100644 index 0000000..9300725 --- /dev/null +++ b/sdk/swift/.swiftformat @@ -0,0 +1,45 @@ +# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/ +# +# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md +# +# file options + +# uncomment below to exclude files, folders +#--exclude path/to/test1.swift,Snapshots,Build + +# format options + +--allman false +--binarygrouping 4,8 +--commas always +--comments indent +--decimalgrouping 3,6 +--elseposition same-line +--empty void +--exponentcase lowercase +--exponentgrouping disabled +--fractiongrouping disabled +--header ignore +--hexgrouping 4,8 +--hexliteralcase uppercase +--ifdef indent +--indent 4 +--indentcase false +--importgrouping testable-bottom +--linebreaks lf +--maxwidth none +--octalgrouping 4,8 +--operatorfunc spaced +--patternlet hoist +--ranges spaced +--self remove +--semicolons inline +--stripunusedargs always +--swiftversion 5.4 +--trimwhitespace always +--wraparguments preserve +--wrapcollections preserve + +# rules + +--enable isEmpty diff --git a/sdk/swift/LICENSE b/sdk/swift/LICENSE new file mode 100644 index 0000000..a8e1185 --- /dev/null +++ b/sdk/swift/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 troii Software GmbH + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sdk/swift/Package.swift b/sdk/swift/Package.swift new file mode 100644 index 0000000..14e46c4 --- /dev/null +++ b/sdk/swift/Package.swift @@ -0,0 +1,34 @@ +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "TimrApi", + platforms: [ + .iOS(.v11), + .macOS(.v10_13), + .tvOS(.v11), + .watchOS(.v4), + ], + products: [ + // Products define the executables and libraries produced by a package, and make them visible to other packages. + .library( + name: "TimrApi", + targets: ["TimrApi"] + ), + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", .upToNextMajor(from: "0.6.1")), + .package(url: "https://github.com/Alamofire/Alamofire", .upToNextMajor(from: "5.7.0")), + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "TimrApi", + dependencies: ["AnyCodable", "Alamofire", ], + path: "TimrApi" + ), + ] +) diff --git a/sdk/swift/README.md b/sdk/swift/README.md new file mode 100644 index 0000000..0d983f9 --- /dev/null +++ b/sdk/swift/README.md @@ -0,0 +1,60 @@ +# TimrApi + +Official Swift client for the [timr](https://www.timr.com) API. + +The timr API exposes the recordings a user makes — working times, project times and drive +logs — together with the master data they refer to: users, teams, tasks, cars, working time +types, work schedule models and holiday calendars. + +**Full API reference: [developer.timr.com](https://developer.timr.com)** + +## Installation + +### Swift Package Manager + +```swift +.package(url: "https://github.com/troii/timr-api-swift", from: "1.0.0") +``` + +### CocoaPods + +```ruby +pod 'TimrApi' +``` + +## Usage + +The generated client is `TimrAPI`. Requests are `async`/`await` and run through Alamofire. + +```swift +import TimrApi + +TimrAPI.customHeaders = ["Authorization": "Bearer \(accessToken)"] + +let cars = try await CarAPI.fetchCars() +for car in cars.data { + print("\(car.name) (\(car.plate))") +} +``` + +`TimrAPI.basePath` defaults to `https://api.timr.com/v1`; set it to point at another +environment. + +## Authentication + +The API uses OAuth 2.0. Two flows are supported: + +| Flow | Use for | Scopes | +| --- | --- | --- | +| `client_credentials` | server-to-server integrations acting as the client | `openid`, `timrclient` | +| `authorization_code` (with PKCE) | acting on behalf of a timr user | `openid`, `offline_access` | + +Authorization endpoint: `https://system.timr.com/id/oauth2/authorize` + +## Support + +[info@timr.com](mailto:info@timr.com) + +## License + +Apache License 2.0 diff --git a/sdk/swift/TimrApi/APIHelper.swift b/sdk/swift/TimrApi/APIHelper.swift new file mode 100644 index 0000000..7c975bb --- /dev/null +++ b/sdk/swift/TimrApi/APIHelper.swift @@ -0,0 +1,121 @@ +// APIHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct APIHelper { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { + let destination = source.reduce(into: [String: Any]()) { result, item in + if let value = item.value { + result[item.key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { + return source.reduce(into: [String: String]()) { result, item in + if let collection = item.value as? [Any?] { + result[item.key] = collection + .compactMap { value in convertAnyToString(value) } + .joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = convertAnyToString(value) + } + } + } + + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { + guard let source = source else { + return nil + } + + return source.reduce(into: [String: Any]()) { result, item in + switch item.value { + case let x as Bool: + result[item.key] = x.description + default: + result[item.key] = item.value + } + } + } + + public static func convertAnyToString(_ value: Any?) -> String? { + guard let value = value else { return nil } + if let value = value as? any RawRepresentable { + return "\(value.rawValue)" + } else { + return "\(value)" + } + } + + public static func mapValueToPathItem(_ source: Any) -> Any { + if let collection = source as? [Any?] { + return collection + .compactMap { value in convertAnyToString(value) } + .joined(separator: ",") + } else if let value = source as? any RawRepresentable { + return "\(value.rawValue)" + } + return source + } + + /// maps all values from source to query parameters + /// + /// explode attribute is respected: collection values might be either joined or split up into separate key value pairs + public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? { + let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value.wrappedValue as? [Any?] { + + let collectionValues: [String] = collection.compactMap { value in convertAnyToString(value) } + + if !item.value.isExplode { + result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ","))) + } else { + collectionValues + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } + + } else if let value = item.value.wrappedValue { + result.append(URLQueryItem(name: item.key, value: convertAnyToString(value))) + } + } + + if destination.isEmpty { + return nil + } + return destination.sorted { $0.name < $1.name } + } + + /// maps all values from source to query parameters + /// + /// collection values are always exploded + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { + let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value as? [Any?] { + collection + .compactMap { value in convertAnyToString(value) } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: convertAnyToString(value))) + } + } + + if destination.isEmpty { + return nil + } + return destination.sorted { $0.name < $1.name } + } +} diff --git a/sdk/swift/TimrApi/APIs.swift b/sdk/swift/TimrApi/APIs.swift new file mode 100644 index 0000000..352ddb8 --- /dev/null +++ b/sdk/swift/TimrApi/APIs.swift @@ -0,0 +1,93 @@ +// APIs.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif +open class TimrAPI { + public static var basePath = "https://api.timr.com/v1" + public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? + public static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() + public static var apiResponseQueue: DispatchQueue = .main +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String: String] + public let parameters: [String: Any]? + public let method: String + public let URLString: String + public let requestTask: RequestTask = RequestTask() + public let requiresAuthentication: Bool + + /// Optional block to obtain a reference to the request's progress instance when available. + public var onProgressReady: ((Progress) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.headers = headers + self.requiresAuthentication = requiresAuthentication + + addHeaders(TimrAPI.customHeaders) + } + + open func addHeaders(_ aHeaders: [String: String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + @discardableResult + open func execute(_ apiResponseQueue: DispatchQueue = TimrAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> RequestTask { + return requestTask + } + + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + @discardableResult + open func execute() async throws -> Response { + return try await withTaskCancellationHandler { + try _Concurrency.Task.checkCancellation() + return try await withCheckedThrowingContinuation { continuation in + guard !_Concurrency.Task.isCancelled else { + continuation.resume(throwing: CancellationError()) + return + } + + self.execute { result in + switch result { + case let .success(response): + continuation.resume(returning: response) + case let .failure(error): + continuation.resume(throwing: error) + } + } + } + } onCancel: { + self.requestTask.cancel() + } + } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + credential = TimrAPI.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/sdk/swift/TimrApi/APIs/CarAPI.swift b/sdk/swift/TimrApi/APIs/CarAPI.swift new file mode 100644 index 0000000..c64ec6e --- /dev/null +++ b/sdk/swift/TimrApi/APIs/CarAPI.swift @@ -0,0 +1,209 @@ +// +// CarAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class CarAPI { + + /** + Create a Car + + - parameter carCreate: (body) Car entity + - returns: Car + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createCar(carCreate: CarCreate) async throws -> Car { + return try await createCarWithRequestBuilder(carCreate: carCreate).execute().body + } + + /** + Create a Car + - POST /cars + - Creates a Car from the data in the request body. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter carCreate: (body) Car entity + - returns: RequestBuilder + */ + open class func createCarWithRequestBuilder(carCreate: CarCreate) -> RequestBuilder { + let localVariablePath = "/cars" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: carCreate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Cars + + - parameter nameOrPlate: (query) Only return Cars whose name or plate contains this text. (optional) + - parameter usable: (query) Only return Cars that are usable (true) or not usable (false). (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: CarsPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchCars(nameOrPlate: String? = nil, usable: Bool? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: CarsSortColumn? = nil) async throws -> CarsPage { + return try await fetchCarsWithRequestBuilder(nameOrPlate: nameOrPlate, usable: usable, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Cars + - GET /cars + - Lists the Cars the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter nameOrPlate: (query) Only return Cars whose name or plate contains this text. (optional) + - parameter usable: (query) Only return Cars that are usable (true) or not usable (false). (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchCarsWithRequestBuilder(nameOrPlate: String? = nil, usable: Bool? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: CarsSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/cars" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "name_or_plate": (wrappedValue: nameOrPlate?.encodeToJSON(), isExplode: true), + "usable": (wrappedValue: usable?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Car + + - parameter id: (path) ID of the Car. + - returns: Car + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getCar(id: String) async throws -> Car { + return try await getCarWithRequestBuilder(id: id).execute().body + } + + /** + Get a Car + - GET /cars/{id} + - Returns a single Car by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Car. + - returns: RequestBuilder + */ + open class func getCarWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/cars/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Update a Car + + - parameter id: (path) ID of the Car. + - parameter carUpdate: (body) Car entity + - returns: Car + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func updateCar(id: String, carUpdate: CarUpdate) async throws -> Car { + return try await updateCarWithRequestBuilder(id: id, carUpdate: carUpdate).execute().body + } + + /** + Update a Car + - PATCH /cars/{id} + - Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Car. + - parameter carUpdate: (body) Car entity + - returns: RequestBuilder + */ + open class func updateCarWithRequestBuilder(id: String, carUpdate: CarUpdate) -> RequestBuilder { + var localVariablePath = "/cars/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: carUpdate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/DriveLogAPI.swift b/sdk/swift/TimrApi/APIs/DriveLogAPI.swift new file mode 100644 index 0000000..402b7c3 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/DriveLogAPI.swift @@ -0,0 +1,336 @@ +// +// DriveLogAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class DriveLogAPI { + + /** + Create a Drive Log + + - parameter driveLogCreate: (body) Drive Log entity + - returns: DriveLog + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createDriveLog(driveLogCreate: DriveLogCreate) async throws -> DriveLog { + return try await createDriveLogWithRequestBuilder(driveLogCreate: driveLogCreate).execute().body + } + + /** + Create a Drive Log + - POST /drive-logs + - Creates a Drive Log from the data in the request body. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter driveLogCreate: (body) Drive Log entity + - returns: RequestBuilder + */ + open class func createDriveLogWithRequestBuilder(driveLogCreate: DriveLogCreate) -> RequestBuilder { + let localVariablePath = "/drive-logs" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: driveLogCreate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Delete a Drive Log + + - parameter id: (path) ID of the Drive Log. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteDriveLog(id: String) async throws { + return try await deleteDriveLogWithRequestBuilder(id: id).execute().body + } + + /** + Delete a Drive Log + - DELETE /drive-logs/{id} + - Deletes the Drive Log, including its Track. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Drive Log. + - returns: RequestBuilder + */ + open class func deleteDriveLogWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/drive-logs/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List deleted Drive Logs + + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: DeletedEntryPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchDeletedDriveLogs(lastModifiedAfter: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DeletedEntrySortColumn? = nil) async throws -> DeletedEntryPage { + return try await fetchDeletedDriveLogsWithRequestBuilder(lastModifiedAfter: lastModifiedAfter, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List deleted Drive Logs + - GET /drive-logs:deleted + - Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchDeletedDriveLogsWithRequestBuilder(lastModifiedAfter: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DeletedEntrySortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/drive-logs:deleted" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "last_modified_after": (wrappedValue: lastModifiedAfter?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Drive Logs + + - parameter startFrom: (query) Only return entries starting on or after this day. (optional) + - parameter startTo: (query) Only return entries starting on or before this day. (optional) + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter cars: (query) Only return entries recorded for these Cars. (optional) + - parameter driveLogCategories: (query) Only return entries in these Drive Log Categories. (optional) + - parameter statuses: (query) Only return entries in one of these statuses. (optional) + - parameter users: (query) Only return entries belonging to these users. (optional) + - parameter details: (query) Only return Drive Logs whose route, purpose or visited contains this text. (optional) + - parameter changed: (query) Only return entries that were changed by the user (true) or left unchanged (false). (optional) + - parameter hasTrack: (query) Only return Drive Logs that have a Track (true) or have none (false). (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: DriveLogsPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchDriveLogs(startFrom: Date? = nil, startTo: Date? = nil, lastModifiedAfter: Date? = nil, cars: [String]? = nil, driveLogCategories: [String]? = nil, statuses: [DriveLogStatus]? = nil, users: [String]? = nil, details: String? = nil, changed: Bool? = nil, hasTrack: Bool? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DriveLogsSortColumn? = nil) async throws -> DriveLogsPage { + return try await fetchDriveLogsWithRequestBuilder(startFrom: startFrom, startTo: startTo, lastModifiedAfter: lastModifiedAfter, cars: cars, driveLogCategories: driveLogCategories, statuses: statuses, users: users, details: details, changed: changed, hasTrack: hasTrack, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Drive Logs + - GET /drive-logs + - Lists the Drive Logs the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter startFrom: (query) Only return entries starting on or after this day. (optional) + - parameter startTo: (query) Only return entries starting on or before this day. (optional) + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter cars: (query) Only return entries recorded for these Cars. (optional) + - parameter driveLogCategories: (query) Only return entries in these Drive Log Categories. (optional) + - parameter statuses: (query) Only return entries in one of these statuses. (optional) + - parameter users: (query) Only return entries belonging to these users. (optional) + - parameter details: (query) Only return Drive Logs whose route, purpose or visited contains this text. (optional) + - parameter changed: (query) Only return entries that were changed by the user (true) or left unchanged (false). (optional) + - parameter hasTrack: (query) Only return Drive Logs that have a Track (true) or have none (false). (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchDriveLogsWithRequestBuilder(startFrom: Date? = nil, startTo: Date? = nil, lastModifiedAfter: Date? = nil, cars: [String]? = nil, driveLogCategories: [String]? = nil, statuses: [DriveLogStatus]? = nil, users: [String]? = nil, details: String? = nil, changed: Bool? = nil, hasTrack: Bool? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DriveLogsSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/drive-logs" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "start_from": (wrappedValue: startFrom?.encodeToJSON(), isExplode: true), + "start_to": (wrappedValue: startTo?.encodeToJSON(), isExplode: true), + "last_modified_after": (wrappedValue: lastModifiedAfter?.encodeToJSON(), isExplode: true), + "cars": (wrappedValue: cars?.encodeToJSON(), isExplode: true), + "drive_log_categories": (wrappedValue: driveLogCategories?.encodeToJSON(), isExplode: true), + "statuses": (wrappedValue: statuses?.encodeToJSON(), isExplode: true), + "users": (wrappedValue: users?.encodeToJSON(), isExplode: true), + "details": (wrappedValue: details?.encodeToJSON(), isExplode: true), + "changed": (wrappedValue: changed?.encodeToJSON(), isExplode: true), + "has_track": (wrappedValue: hasTrack?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Drive Log + + - parameter id: (path) ID of the Drive Log. + - returns: DriveLog + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getDriveLog(id: String) async throws -> DriveLog { + return try await getDriveLogWithRequestBuilder(id: id).execute().body + } + + /** + Get a Drive Log + - GET /drive-logs/{id} + - Returns a single Drive Log by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Drive Log. + - returns: RequestBuilder + */ + open class func getDriveLogWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/drive-logs/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Update a Drive Log + + - parameter id: (path) ID of the Drive Log. + - parameter driveLogUpdate: (body) Drive Log entity + - returns: DriveLog + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func updateDriveLog(id: String, driveLogUpdate: DriveLogUpdate) async throws -> DriveLog { + return try await updateDriveLogWithRequestBuilder(id: id, driveLogUpdate: driveLogUpdate).execute().body + } + + /** + Update a Drive Log + - PATCH /drive-logs/{id} + - Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Drive Log. + - parameter driveLogUpdate: (body) Drive Log entity + - returns: RequestBuilder + */ + open class func updateDriveLogWithRequestBuilder(id: String, driveLogUpdate: DriveLogUpdate) -> RequestBuilder { + var localVariablePath = "/drive-logs/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: driveLogUpdate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/DriveLogCategoryAPI.swift b/sdk/swift/TimrApi/APIs/DriveLogCategoryAPI.swift new file mode 100644 index 0000000..ad5857f --- /dev/null +++ b/sdk/swift/TimrApi/APIs/DriveLogCategoryAPI.swift @@ -0,0 +1,114 @@ +// +// DriveLogCategoryAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class DriveLogCategoryAPI { + + /** + List Drive Log Categories + + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: DriveLogCategoriesPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchDriveLogCategories(pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DriveLogCategoriesSortColumn? = nil) async throws -> DriveLogCategoriesPage { + return try await fetchDriveLogCategoriesWithRequestBuilder(pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Drive Log Categories + - GET /drive-log-categories + - Lists the Drive Log Categories the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchDriveLogCategoriesWithRequestBuilder(pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DriveLogCategoriesSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/drive-log-categories" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Drive Log Category + + - parameter id: (path) ID of the Drive Log Category. + - returns: DriveLogCategory + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getDriveLogCategory(id: String) async throws -> DriveLogCategory { + return try await getDriveLogCategoryWithRequestBuilder(id: id).execute().body + } + + /** + Get a Drive Log Category + - GET /drive-log-categories/{id} + - Returns a single Drive Log Category by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Drive Log Category. + - returns: RequestBuilder + */ + open class func getDriveLogCategoryWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/drive-log-categories/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/HolidayCalendarAPI.swift b/sdk/swift/TimrApi/APIs/HolidayCalendarAPI.swift new file mode 100644 index 0000000..e84046b --- /dev/null +++ b/sdk/swift/TimrApi/APIs/HolidayCalendarAPI.swift @@ -0,0 +1,174 @@ +// +// HolidayCalendarAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class HolidayCalendarAPI { + + /** + List Holiday Calendars + + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: HolidayCalendarsPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchHolidayCalendars(pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: HolidayCalendarsSortColumn? = nil) async throws -> HolidayCalendarsPage { + return try await fetchHolidayCalendarsWithRequestBuilder(pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Holiday Calendars + - GET /holiday-calendars + - Lists the Holiday Calendars the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchHolidayCalendarsWithRequestBuilder(pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: HolidayCalendarsSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/holiday-calendars" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Holidays + + - parameter id: (path) ID of the Holiday Calendar. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: HolidaysPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchHolidays(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: HolidaysSortColumn? = nil) async throws -> HolidaysPage { + return try await fetchHolidaysWithRequestBuilder(id: id, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Holidays + - GET /holiday-calendars/{id}/holidays + - Lists the Holidays in the Holiday Calendar. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter id: (path) ID of the Holiday Calendar. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchHolidaysWithRequestBuilder(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: HolidaysSortColumn? = nil) -> RequestBuilder { + var localVariablePath = "/holiday-calendars/{id}/holidays" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Holiday Calendar + + - parameter id: (path) ID of the Holiday Calendar. + - returns: HolidayCalendarPartial + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getHolidayCalendar(id: String) async throws -> HolidayCalendarPartial { + return try await getHolidayCalendarWithRequestBuilder(id: id).execute().body + } + + /** + Get a Holiday Calendar + - GET /holiday-calendars/{id} + - Returns a single Holiday Calendar by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Holiday Calendar. + - returns: RequestBuilder + */ + open class func getHolidayCalendarWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/holiday-calendars/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/ProjectTimeAPI.swift b/sdk/swift/TimrApi/APIs/ProjectTimeAPI.swift new file mode 100644 index 0000000..f61edf8 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/ProjectTimeAPI.swift @@ -0,0 +1,336 @@ +// +// ProjectTimeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class ProjectTimeAPI { + + /** + Create a Project Time + + - parameter projectTimeCreate: (body) Project Time entity + - returns: ProjectTime + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createProjectTime(projectTimeCreate: ProjectTimeCreate) async throws -> ProjectTime { + return try await createProjectTimeWithRequestBuilder(projectTimeCreate: projectTimeCreate).execute().body + } + + /** + Create a Project Time + - POST /project-times + - Creates a Project Time from the data in the request body. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter projectTimeCreate: (body) Project Time entity + - returns: RequestBuilder + */ + open class func createProjectTimeWithRequestBuilder(projectTimeCreate: ProjectTimeCreate) -> RequestBuilder { + let localVariablePath = "/project-times" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: projectTimeCreate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Delete a Project Time + + - parameter id: (path) ID of the Project Time. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteProjectTime(id: String) async throws { + return try await deleteProjectTimeWithRequestBuilder(id: id).execute().body + } + + /** + Delete a Project Time + - DELETE /project-times/{id} + - Deletes the Project Time. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Project Time. + - returns: RequestBuilder + */ + open class func deleteProjectTimeWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/project-times/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List deleted Project Times + + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: DeletedEntryWithMetadataPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchDeletedProjectTimes(lastModifiedAfter: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DeletedEntrySortColumn? = nil) async throws -> DeletedEntryWithMetadataPage { + return try await fetchDeletedProjectTimesWithRequestBuilder(lastModifiedAfter: lastModifiedAfter, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List deleted Project Times + - GET /project-times:deleted + - Lists Project Times that were deleted, so a client holding a local copy can reconcile. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchDeletedProjectTimesWithRequestBuilder(lastModifiedAfter: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DeletedEntrySortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/project-times:deleted" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "last_modified_after": (wrappedValue: lastModifiedAfter?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Project Times + + - parameter notes: (query) Only return entries whose notes contain this text. (optional) + - parameter startFrom: (query) Only return entries starting on or after this day. (optional) + - parameter startTo: (query) Only return entries starting on or before this day. (optional) + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter task: (query) Only return entries recorded on the Task with this ID. (optional) + - parameter traverseTaskTree: (query) Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + - parameter billable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter statuses: (query) Only return entries in one of these statuses. (optional) + - parameter users: (query) Only return entries belonging to these users. (optional) + - parameter changed: (query) Only return entries that were changed by the user (true) or left unchanged (false). (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: ProjectTimesPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchProjectTimes(notes: String? = nil, startFrom: Date? = nil, startTo: Date? = nil, lastModifiedAfter: Date? = nil, task: String? = nil, traverseTaskTree: Bool? = nil, billable: Bool? = nil, statuses: [ProjectTimeStatus]? = nil, users: [String]? = nil, changed: Bool? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: ProjectTimesSortColumn? = nil) async throws -> ProjectTimesPage { + return try await fetchProjectTimesWithRequestBuilder(notes: notes, startFrom: startFrom, startTo: startTo, lastModifiedAfter: lastModifiedAfter, task: task, traverseTaskTree: traverseTaskTree, billable: billable, statuses: statuses, users: users, changed: changed, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Project Times + - GET /project-times + - Lists the Project Times the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter notes: (query) Only return entries whose notes contain this text. (optional) + - parameter startFrom: (query) Only return entries starting on or after this day. (optional) + - parameter startTo: (query) Only return entries starting on or before this day. (optional) + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter task: (query) Only return entries recorded on the Task with this ID. (optional) + - parameter traverseTaskTree: (query) Include entries recorded on the whole subtree of the given Task (true) or only on the Task itself (false). (optional, default to true) + - parameter billable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter statuses: (query) Only return entries in one of these statuses. (optional) + - parameter users: (query) Only return entries belonging to these users. (optional) + - parameter changed: (query) Only return entries that were changed by the user (true) or left unchanged (false). (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchProjectTimesWithRequestBuilder(notes: String? = nil, startFrom: Date? = nil, startTo: Date? = nil, lastModifiedAfter: Date? = nil, task: String? = nil, traverseTaskTree: Bool? = nil, billable: Bool? = nil, statuses: [ProjectTimeStatus]? = nil, users: [String]? = nil, changed: Bool? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: ProjectTimesSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/project-times" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "notes": (wrappedValue: notes?.encodeToJSON(), isExplode: true), + "start_from": (wrappedValue: startFrom?.encodeToJSON(), isExplode: true), + "start_to": (wrappedValue: startTo?.encodeToJSON(), isExplode: true), + "last_modified_after": (wrappedValue: lastModifiedAfter?.encodeToJSON(), isExplode: true), + "task": (wrappedValue: task?.encodeToJSON(), isExplode: true), + "traverse_task_tree": (wrappedValue: traverseTaskTree?.encodeToJSON(), isExplode: true), + "billable": (wrappedValue: billable?.encodeToJSON(), isExplode: true), + "statuses": (wrappedValue: statuses?.encodeToJSON(), isExplode: true), + "users": (wrappedValue: users?.encodeToJSON(), isExplode: true), + "changed": (wrappedValue: changed?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Project Time + + - parameter id: (path) ID of the Project Time. + - returns: ProjectTime + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getProjectTime(id: String) async throws -> ProjectTime { + return try await getProjectTimeWithRequestBuilder(id: id).execute().body + } + + /** + Get a Project Time + - GET /project-times/{id} + - Returns a single Project Time by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Project Time. + - returns: RequestBuilder + */ + open class func getProjectTimeWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/project-times/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Update a Project Time + + - parameter id: (path) ID of the Project Time. + - parameter projectTimeUpdate: (body) Project Time entity + - returns: ProjectTime + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func updateProjectTime(id: String, projectTimeUpdate: ProjectTimeUpdate) async throws -> ProjectTime { + return try await updateProjectTimeWithRequestBuilder(id: id, projectTimeUpdate: projectTimeUpdate).execute().body + } + + /** + Update a Project Time + - PATCH /project-times/{id} + - Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Project Time. + - parameter projectTimeUpdate: (body) Project Time entity + - returns: RequestBuilder + */ + open class func updateProjectTimeWithRequestBuilder(id: String, projectTimeUpdate: ProjectTimeUpdate) -> RequestBuilder { + var localVariablePath = "/project-times/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: projectTimeUpdate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/TaskAPI.swift b/sdk/swift/TimrApi/APIs/TaskAPI.swift new file mode 100644 index 0000000..36c1ec1 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/TaskAPI.swift @@ -0,0 +1,299 @@ +// +// TaskAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class TaskAPI { + + /** + Create a Task + + - parameter taskCreate: (body) Project Time entity + - returns: Task + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createTask(taskCreate: TaskCreate) async throws -> Task { + return try await createTaskWithRequestBuilder(taskCreate: taskCreate).execute().body + } + + /** + Create a Task + - POST /tasks + - Creates a Task from the data in the request body. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskCreate: (body) Project Time entity + - returns: RequestBuilder + */ + open class func createTaskWithRequestBuilder(taskCreate: TaskCreate) -> RequestBuilder { + let localVariablePath = "/tasks" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: taskCreate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Tasks + + - parameter parentTaskId: (query) Only return Tasks whose parent is the Task with this ID. (optional) + - parameter traverseTaskTree: (query) Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + - parameter name: (query) Only return Users whose name contains this text. (optional) + - parameter bookable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter billable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter activeAt: (query) Only return Tasks that are active on this day. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: TasksPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchTasks(parentTaskId: String? = nil, traverseTaskTree: Bool? = nil, name: String? = nil, bookable: Bool? = nil, billable: Bool? = nil, activeAt: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TasksSortColumn? = nil) async throws -> TasksPage { + return try await fetchTasksWithRequestBuilder(parentTaskId: parentTaskId, traverseTaskTree: traverseTaskTree, name: name, bookable: bookable, billable: billable, activeAt: activeAt, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Tasks + - GET /tasks + - Lists the Tasks the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter parentTaskId: (query) Only return Tasks whose parent is the Task with this ID. (optional) + - parameter traverseTaskTree: (query) Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + - parameter name: (query) Only return Users whose name contains this text. (optional) + - parameter bookable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter billable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter activeAt: (query) Only return Tasks that are active on this day. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchTasksWithRequestBuilder(parentTaskId: String? = nil, traverseTaskTree: Bool? = nil, name: String? = nil, bookable: Bool? = nil, billable: Bool? = nil, activeAt: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TasksSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/tasks" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "parent_task_id": (wrappedValue: parentTaskId?.encodeToJSON(), isExplode: true), + "traverse_task_tree": (wrappedValue: traverseTaskTree?.encodeToJSON(), isExplode: true), + "name": (wrappedValue: name?.encodeToJSON(), isExplode: true), + "bookable": (wrappedValue: bookable?.encodeToJSON(), isExplode: true), + "billable": (wrappedValue: billable?.encodeToJSON(), isExplode: true), + "active_at": (wrappedValue: activeAt?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List a User's Tasks + + - parameter id: (path) ID of the User. + - parameter parentTaskId: (query) Only return Tasks whose parent is the Task with this ID. (optional) + - parameter traverseTaskTree: (query) Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + - parameter name: (query) Only return Users whose name contains this text. (optional) + - parameter bookable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter billable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter activeAt: (query) Only return Tasks that are active on this day. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: TasksReducedPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchUserTasks(id: String, parentTaskId: String? = nil, traverseTaskTree: Bool? = nil, name: String? = nil, bookable: Bool? = nil, billable: Bool? = nil, activeAt: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TasksSortColumn? = nil) async throws -> TasksReducedPage { + return try await fetchUserTasksWithRequestBuilder(id: id, parentTaskId: parentTaskId, traverseTaskTree: traverseTaskTree, name: name, bookable: bookable, billable: billable, activeAt: activeAt, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List a User's Tasks + - GET /users/{id}/tasks + - Lists the Tasks the User is assigned to and may record on. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter id: (path) ID of the User. + - parameter parentTaskId: (query) Only return Tasks whose parent is the Task with this ID. (optional) + - parameter traverseTaskTree: (query) Include Tasks from the whole subtree (true) or only direct children (false). (optional, default to true) + - parameter name: (query) Only return Users whose name contains this text. (optional) + - parameter bookable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter billable: (query) Only return entries that are billable (true) or not billable (false). (optional) + - parameter activeAt: (query) Only return Tasks that are active on this day. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchUserTasksWithRequestBuilder(id: String, parentTaskId: String? = nil, traverseTaskTree: Bool? = nil, name: String? = nil, bookable: Bool? = nil, billable: Bool? = nil, activeAt: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TasksSortColumn? = nil) -> RequestBuilder { + var localVariablePath = "/users/{id}/tasks" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "parent_task_id": (wrappedValue: parentTaskId?.encodeToJSON(), isExplode: true), + "traverse_task_tree": (wrappedValue: traverseTaskTree?.encodeToJSON(), isExplode: true), + "name": (wrappedValue: name?.encodeToJSON(), isExplode: true), + "bookable": (wrappedValue: bookable?.encodeToJSON(), isExplode: true), + "billable": (wrappedValue: billable?.encodeToJSON(), isExplode: true), + "active_at": (wrappedValue: activeAt?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Task + + - parameter id: (path) ID of the Task. + - returns: Task + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getTask(id: String) async throws -> Task { + return try await getTaskWithRequestBuilder(id: id).execute().body + } + + /** + Get a Task + - GET /tasks/{id} + - Returns a single Task by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Task. + - returns: RequestBuilder + */ + open class func getTaskWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/tasks/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Update a Task + + - parameter id: (path) ID of the Task. + - parameter taskUpdate: (body) Task entity + - returns: Task + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func updateTask(id: String, taskUpdate: TaskUpdate) async throws -> Task { + return try await updateTaskWithRequestBuilder(id: id, taskUpdate: taskUpdate).execute().body + } + + /** + Update a Task + - PATCH /tasks/{id} + - Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Task. + - parameter taskUpdate: (body) Task entity + - returns: RequestBuilder + */ + open class func updateTaskWithRequestBuilder(id: String, taskUpdate: TaskUpdate) -> RequestBuilder { + var localVariablePath = "/tasks/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: taskUpdate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/TaskToLeaderAssignmentAPI.swift b/sdk/swift/TimrApi/APIs/TaskToLeaderAssignmentAPI.swift new file mode 100644 index 0000000..70c6d64 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/TaskToLeaderAssignmentAPI.swift @@ -0,0 +1,224 @@ +// +// TaskToLeaderAssignmentAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class TaskToLeaderAssignmentAPI { + + /** + Create a Task to Leader Assignment + + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: TaskToLeaderAssignment + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createTaskToLeaderAssignment(taskId: String, userId: String) async throws -> TaskToLeaderAssignment { + return try await createTaskToLeaderAssignmentWithRequestBuilder(taskId: taskId, userId: userId).execute().body + } + + /** + Create a Task to Leader Assignment + - PUT /tasks/{task_id}/leaders/{user_id} + - Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func createTaskToLeaderAssignmentWithRequestBuilder(taskId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/leaders/{user_id}" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Delete a Task to Leader Assignment + + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteTaskToLeaderAssignment(taskId: String, userId: String) async throws { + return try await deleteTaskToLeaderAssignmentWithRequestBuilder(taskId: taskId, userId: userId).execute().body + } + + /** + Delete a Task to Leader Assignment + - DELETE /tasks/{task_id}/leaders/{user_id} + - Removes the User's leader assignment to the Task. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func deleteTaskToLeaderAssignmentWithRequestBuilder(taskId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/leaders/{user_id}" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Task to Leader Assignments + + - parameter taskId: (path) ID of the Task. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: TaskToLeaderAssignmentsPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchTaskToLeaderAssignments(taskId: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TaskToLeaderAssignmentsSortColumn? = nil) async throws -> TaskToLeaderAssignmentsPage { + return try await fetchTaskToLeaderAssignmentsWithRequestBuilder(taskId: taskId, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Task to Leader Assignments + - GET /tasks/{task_id}/leaders + - Lists the Users assigned to the Task as leaders. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter taskId: (path) ID of the Task. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchTaskToLeaderAssignmentsWithRequestBuilder(taskId: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TaskToLeaderAssignmentsSortColumn? = nil) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/leaders" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Task to Leader Assignment + + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: TaskToLeaderAssignment + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getTaskToLeaderAssignment(taskId: String, userId: String) async throws -> TaskToLeaderAssignment { + return try await getTaskToLeaderAssignmentWithRequestBuilder(taskId: taskId, userId: userId).execute().body + } + + /** + Get a Task to Leader Assignment + - GET /tasks/{task_id}/leaders/{user_id} + - Returns the leader assignment of a single User to the Task. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func getTaskToLeaderAssignmentWithRequestBuilder(taskId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/leaders/{user_id}" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/TaskToTeamAssignmentAPI.swift b/sdk/swift/TimrApi/APIs/TaskToTeamAssignmentAPI.swift new file mode 100644 index 0000000..e7df778 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/TaskToTeamAssignmentAPI.swift @@ -0,0 +1,224 @@ +// +// TaskToTeamAssignmentAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class TaskToTeamAssignmentAPI { + + /** + Create a Task to Team Assignment + + - parameter taskId: (path) ID of the Task. + - parameter teamId: (path) ID of the Team. + - returns: TaskToTeamAssignment + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createTaskToTeamAssignment(taskId: String, teamId: String) async throws -> TaskToTeamAssignment { + return try await createTaskToTeamAssignmentWithRequestBuilder(taskId: taskId, teamId: teamId).execute().body + } + + /** + Create a Task to Team Assignment + - PUT /tasks/{task_id}/teams/{team_id} + - Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskId: (path) ID of the Task. + - parameter teamId: (path) ID of the Team. + - returns: RequestBuilder + */ + open class func createTaskToTeamAssignmentWithRequestBuilder(taskId: String, teamId: String) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/teams/{team_id}" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let teamIdPreEscape = "\(APIHelper.mapValueToPathItem(teamId))" + let teamIdPostEscape = teamIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{team_id}", with: teamIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Delete a Task to Team Assignment + + - parameter taskId: (path) ID of the Task. + - parameter teamId: (path) ID of the Team. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteTaskToTeamAssignment(taskId: String, teamId: String) async throws { + return try await deleteTaskToTeamAssignmentWithRequestBuilder(taskId: taskId, teamId: teamId).execute().body + } + + /** + Delete a Task to Team Assignment + - DELETE /tasks/{task_id}/teams/{team_id} + - Removes the Team's assignment to the Task. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskId: (path) ID of the Task. + - parameter teamId: (path) ID of the Team. + - returns: RequestBuilder + */ + open class func deleteTaskToTeamAssignmentWithRequestBuilder(taskId: String, teamId: String) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/teams/{team_id}" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let teamIdPreEscape = "\(APIHelper.mapValueToPathItem(teamId))" + let teamIdPostEscape = teamIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{team_id}", with: teamIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Task to Team Assignments + + - parameter taskId: (path) ID of the Task. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: TaskToTeamAssignmentsPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchTaskToTeamAssignments(taskId: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TaskToTeamAssignmentsSortColumn? = nil) async throws -> TaskToTeamAssignmentsPage { + return try await fetchTaskToTeamAssignmentsWithRequestBuilder(taskId: taskId, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Task to Team Assignments + - GET /tasks/{task_id}/teams + - Lists the Teams assigned to the Task. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter taskId: (path) ID of the Task. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchTaskToTeamAssignmentsWithRequestBuilder(taskId: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TaskToTeamAssignmentsSortColumn? = nil) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/teams" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Task to Team Assignment + + - parameter taskId: (path) ID of the Task. + - parameter teamId: (path) ID of the Team. + - returns: TaskToTeamAssignment + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getTaskToTeamAssignment(taskId: String, teamId: String) async throws -> TaskToTeamAssignment { + return try await getTaskToTeamAssignmentWithRequestBuilder(taskId: taskId, teamId: teamId).execute().body + } + + /** + Get a Task to Team Assignment + - GET /tasks/{task_id}/teams/{team_id} + - Returns the assignment of a single Team to the Task. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskId: (path) ID of the Task. + - parameter teamId: (path) ID of the Team. + - returns: RequestBuilder + */ + open class func getTaskToTeamAssignmentWithRequestBuilder(taskId: String, teamId: String) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/teams/{team_id}" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let teamIdPreEscape = "\(APIHelper.mapValueToPathItem(teamId))" + let teamIdPostEscape = teamIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{team_id}", with: teamIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/TaskToUserAssignmentAPI.swift b/sdk/swift/TimrApi/APIs/TaskToUserAssignmentAPI.swift new file mode 100644 index 0000000..a9c184d --- /dev/null +++ b/sdk/swift/TimrApi/APIs/TaskToUserAssignmentAPI.swift @@ -0,0 +1,226 @@ +// +// TaskToUserAssignmentAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class TaskToUserAssignmentAPI { + + /** + Delete a Task to User Assignment + + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteTaskToUserAssignment(taskId: String, userId: String) async throws { + return try await deleteTaskToUserAssignmentWithRequestBuilder(taskId: taskId, userId: userId).execute().body + } + + /** + Delete a Task to User Assignment + - DELETE /tasks/{task_id}/users/{user_id} + - Removes the User's assignment to the Task. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func deleteTaskToUserAssignmentWithRequestBuilder(taskId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/users/{user_id}" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Task to User Assignments + + - parameter taskId: (path) ID of the Task. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: TaskToUserAssignmentsPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchTaskToUserAssignments(taskId: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TaskToUserAssignmentsSortColumn? = nil) async throws -> TaskToUserAssignmentsPage { + return try await fetchTaskToUserAssignmentsWithRequestBuilder(taskId: taskId, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Task to User Assignments + - GET /tasks/{task_id}/users + - Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter taskId: (path) ID of the Task. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchTaskToUserAssignmentsWithRequestBuilder(taskId: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TaskToUserAssignmentsSortColumn? = nil) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/users" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Task to User Assignment + + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: TaskToUserAssignment + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getTaskToUserAssignment(taskId: String, userId: String) async throws -> TaskToUserAssignment { + return try await getTaskToUserAssignmentWithRequestBuilder(taskId: taskId, userId: userId).execute().body + } + + /** + Get a Task to User Assignment + - GET /tasks/{task_id}/users/{user_id} + - Returns the assignment of a single User to the Task. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func getTaskToUserAssignmentWithRequestBuilder(taskId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/users/{user_id}" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Create or update a Task to User Assignment + + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - parameter taskToUserAssignmentUpsert: (body) Task to User Assignment entity + - returns: TaskToUserAssignment + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func upsertTaskToUserAssignment(taskId: String, userId: String, taskToUserAssignmentUpsert: TaskToUserAssignmentUpsert) async throws -> TaskToUserAssignment { + return try await upsertTaskToUserAssignmentWithRequestBuilder(taskId: taskId, userId: userId, taskToUserAssignmentUpsert: taskToUserAssignmentUpsert).execute().body + } + + /** + Create or update a Task to User Assignment + - PUT /tasks/{task_id}/users/{user_id} + - Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter taskId: (path) ID of the Task. + - parameter userId: (path) ID of the User. + - parameter taskToUserAssignmentUpsert: (body) Task to User Assignment entity + - returns: RequestBuilder + */ + open class func upsertTaskToUserAssignmentWithRequestBuilder(taskId: String, userId: String, taskToUserAssignmentUpsert: TaskToUserAssignmentUpsert) -> RequestBuilder { + var localVariablePath = "/tasks/{task_id}/users/{user_id}" + let taskIdPreEscape = "\(APIHelper.mapValueToPathItem(taskId))" + let taskIdPostEscape = taskIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{task_id}", with: taskIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: taskToUserAssignmentUpsert) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/TeamAPI.swift b/sdk/swift/TimrApi/APIs/TeamAPI.swift new file mode 100644 index 0000000..5332478 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/TeamAPI.swift @@ -0,0 +1,671 @@ +// +// TeamAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class TeamAPI { + + /** + Add a Team Leader + + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: UserPartial + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func addTeamLeader(teamId: String, userId: String) async throws -> UserPartial { + return try await addTeamLeaderWithRequestBuilder(teamId: teamId, userId: userId).execute().body + } + + /** + Add a Team Leader + - PUT /teams/{team_id}/leaders/{user_id} + - Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func addTeamLeaderWithRequestBuilder(teamId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/teams/{team_id}/leaders/{user_id}" + let teamIdPreEscape = "\(APIHelper.mapValueToPathItem(teamId))" + let teamIdPostEscape = teamIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{team_id}", with: teamIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Add a Team Member + + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: UserPartial + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func addTeamMember(teamId: String, userId: String) async throws -> UserPartial { + return try await addTeamMemberWithRequestBuilder(teamId: teamId, userId: userId).execute().body + } + + /** + Add a Team Member + - PUT /teams/{team_id}/members/{user_id} + - Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func addTeamMemberWithRequestBuilder(teamId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/teams/{team_id}/members/{user_id}" + let teamIdPreEscape = "\(APIHelper.mapValueToPathItem(teamId))" + let teamIdPostEscape = teamIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{team_id}", with: teamIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Create a Team + + - parameter teamCreate: (body) Team entity + - returns: Team + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createTeam(teamCreate: TeamCreate) async throws -> Team { + return try await createTeamWithRequestBuilder(teamCreate: teamCreate).execute().body + } + + /** + Create a Team + - POST /teams + - Creates a Team from the data in the request body. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter teamCreate: (body) Team entity + - returns: RequestBuilder + */ + open class func createTeamWithRequestBuilder(teamCreate: TeamCreate) -> RequestBuilder { + let localVariablePath = "/teams" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: teamCreate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Delete a Team + + - parameter id: (path) ID of the Team. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteTeam(id: String) async throws { + return try await deleteTeamWithRequestBuilder(id: id).execute().body + } + + /** + Delete a Team + - DELETE /teams/{id} + - Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Team. + - returns: RequestBuilder + */ + open class func deleteTeamWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/teams/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Team Leaders + + - parameter id: (path) ID of the Team. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: UsersPartialPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchTeamLeaders(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: UsersSortColumn? = nil) async throws -> UsersPartialPage { + return try await fetchTeamLeadersWithRequestBuilder(id: id, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Team Leaders + - GET /teams/{id}/leaders + - Lists the Users who lead the Team. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter id: (path) ID of the Team. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchTeamLeadersWithRequestBuilder(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: UsersSortColumn? = nil) -> RequestBuilder { + var localVariablePath = "/teams/{id}/leaders" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Team Members + + - parameter id: (path) ID of the Team. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: UsersPartialPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchTeamMembers(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: UsersSortColumn? = nil) async throws -> UsersPartialPage { + return try await fetchTeamMembersWithRequestBuilder(id: id, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Team Members + - GET /teams/{id}/members + - Lists the Users who are members of the Team. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter id: (path) ID of the Team. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchTeamMembersWithRequestBuilder(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: UsersSortColumn? = nil) -> RequestBuilder { + var localVariablePath = "/teams/{id}/members" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Teams + + - parameter name: (query) Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: TeamsPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchTeams(name: String? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TeamsSortColumn? = nil) async throws -> TeamsPage { + return try await fetchTeamsWithRequestBuilder(name: name, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Teams + - GET /teams + - Lists the Teams the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter name: (query) Only return Teams whose name matches this value in any segment of the breadcrumbs path. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchTeamsWithRequestBuilder(name: String? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TeamsSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/teams" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "name": (wrappedValue: name?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Team + + - parameter id: (path) ID of the Team. + - returns: Team + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getTeam(id: String) async throws -> Team { + return try await getTeamWithRequestBuilder(id: id).execute().body + } + + /** + Get a Team + - GET /teams/{id} + - Returns a single Team by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Team. + - returns: RequestBuilder + */ + open class func getTeamWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/teams/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Team Leader + + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: UserPartial + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getTeamLeader(teamId: String, userId: String) async throws -> UserPartial { + return try await getTeamLeaderWithRequestBuilder(teamId: teamId, userId: userId).execute().body + } + + /** + Get a Team Leader + - GET /teams/{team_id}/leaders/{user_id} + - Returns the leadership of a single User in the Team. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func getTeamLeaderWithRequestBuilder(teamId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/teams/{team_id}/leaders/{user_id}" + let teamIdPreEscape = "\(APIHelper.mapValueToPathItem(teamId))" + let teamIdPostEscape = teamIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{team_id}", with: teamIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Team Member + + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: UserPartial + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getTeamMember(teamId: String, userId: String) async throws -> UserPartial { + return try await getTeamMemberWithRequestBuilder(teamId: teamId, userId: userId).execute().body + } + + /** + Get a Team Member + - GET /teams/{team_id}/members/{user_id} + - Returns the membership of a single User in the Team. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func getTeamMemberWithRequestBuilder(teamId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/teams/{team_id}/members/{user_id}" + let teamIdPreEscape = "\(APIHelper.mapValueToPathItem(teamId))" + let teamIdPostEscape = teamIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{team_id}", with: teamIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Remove a Team Leader + + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func removeTeamLeader(teamId: String, userId: String) async throws { + return try await removeTeamLeaderWithRequestBuilder(teamId: teamId, userId: userId).execute().body + } + + /** + Remove a Team Leader + - DELETE /teams/{team_id}/leaders/{user_id} + - Removes the User's leadership of the Team. The User itself is not deleted. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func removeTeamLeaderWithRequestBuilder(teamId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/teams/{team_id}/leaders/{user_id}" + let teamIdPreEscape = "\(APIHelper.mapValueToPathItem(teamId))" + let teamIdPostEscape = teamIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{team_id}", with: teamIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Remove a Team Member + + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func removeTeamMember(teamId: String, userId: String) async throws { + return try await removeTeamMemberWithRequestBuilder(teamId: teamId, userId: userId).execute().body + } + + /** + Remove a Team Member + - DELETE /teams/{team_id}/members/{user_id} + - Removes the User's membership in the Team. The User itself is not deleted. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter teamId: (path) ID of the Team. + - parameter userId: (path) ID of the User. + - returns: RequestBuilder + */ + open class func removeTeamMemberWithRequestBuilder(teamId: String, userId: String) -> RequestBuilder { + var localVariablePath = "/teams/{team_id}/members/{user_id}" + let teamIdPreEscape = "\(APIHelper.mapValueToPathItem(teamId))" + let teamIdPostEscape = teamIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{team_id}", with: teamIdPostEscape, options: .literal, range: nil) + let userIdPreEscape = "\(APIHelper.mapValueToPathItem(userId))" + let userIdPostEscape = userIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{user_id}", with: userIdPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Update a Team + + - parameter id: (path) ID of the Team. + - parameter teamUpdate: (body) Team entity + - returns: Team + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func updateTeam(id: String, teamUpdate: TeamUpdate) async throws -> Team { + return try await updateTeamWithRequestBuilder(id: id, teamUpdate: teamUpdate).execute().body + } + + /** + Update a Team + - PATCH /teams/{id} + - Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Team. + - parameter teamUpdate: (body) Team entity + - returns: RequestBuilder + */ + open class func updateTeamWithRequestBuilder(id: String, teamUpdate: TeamUpdate) -> RequestBuilder { + var localVariablePath = "/teams/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: teamUpdate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/TimeAccountAPI.swift b/sdk/swift/TimrApi/APIs/TimeAccountAPI.swift new file mode 100644 index 0000000..870b0a5 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/TimeAccountAPI.swift @@ -0,0 +1,114 @@ +// +// TimeAccountAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class TimeAccountAPI { + + /** + Get a User's accounts + + - parameter id: (path) ID of the User. + - parameter date: (path) Day to return the balances for. + - returns: Accounts + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getUserAccounts(id: String, date: Date) async throws -> Accounts { + return try await getUserAccountsWithRequestBuilder(id: id, date: date).execute().body + } + + /** + Get a User's accounts + - GET /users/{id}/accounts/{date} + - Returns all of the User's account balances as of the given day, including overtime and surcharge accounts. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the User. + - parameter date: (path) Day to return the balances for. + - returns: RequestBuilder + */ + open class func getUserAccountsWithRequestBuilder(id: String, date: Date) -> RequestBuilder { + var localVariablePath = "/users/{id}/accounts/{date}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let datePreEscape = "\(APIHelper.mapValueToPathItem(date))" + let datePostEscape = datePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{date}", with: datePostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a User's working time accounts + + - parameter id: (path) ID of the User. + - parameter date: (path) Day to return the balances for. + - returns: Accounts + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getUserWorkingTimeAccounts(id: String, date: Date) async throws -> Accounts { + return try await getUserWorkingTimeAccountsWithRequestBuilder(id: id, date: date).execute().body + } + + /** + Get a User's working time accounts + - GET /users/{id}/working-time-accounts/{date} + - Returns the User's working time account balances as of the given day. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the User. + - parameter date: (path) Day to return the balances for. + - returns: RequestBuilder + */ + open class func getUserWorkingTimeAccountsWithRequestBuilder(id: String, date: Date) -> RequestBuilder { + var localVariablePath = "/users/{id}/working-time-accounts/{date}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let datePreEscape = "\(APIHelper.mapValueToPathItem(date))" + let datePostEscape = datePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{date}", with: datePostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/TrackAPI.swift b/sdk/swift/TimrApi/APIs/TrackAPI.swift new file mode 100644 index 0000000..1b98ca4 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/TrackAPI.swift @@ -0,0 +1,198 @@ +// +// TrackAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class TrackAPI { + + /** + Create a Drive Log's Track + + - parameter id: (path) drive log id + - parameter waypoint: (body) Working Time Date Span entity + - returns: [Waypoint] + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createTrack(id: String, waypoint: [Waypoint]) async throws -> [Waypoint] { + return try await createTrackWithRequestBuilder(id: id, waypoint: waypoint).execute().body + } + + /** + Create a Drive Log's Track + - POST /drive-logs/{id}/track + - Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) drive log id + - parameter waypoint: (body) Working Time Date Span entity + - returns: RequestBuilder<[Waypoint]> + */ + open class func createTrackWithRequestBuilder(id: String, waypoint: [Waypoint]) -> RequestBuilder<[Waypoint]> { + var localVariablePath = "/drive-logs/{id}/track" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: waypoint) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder<[Waypoint]>.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Delete a Drive Log's Track + + - parameter id: (path) drive log id + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteTrack(id: String) async throws { + return try await deleteTrackWithRequestBuilder(id: id).execute().body + } + + /** + Delete a Drive Log's Track + - DELETE /drive-logs/{id}/track + - Deletes the Drive Log's Track. The Drive Log itself is kept. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) drive log id + - returns: RequestBuilder + */ + open class func deleteTrackWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/drive-logs/{id}/track" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Drive Log's Track + + - parameter id: (path) drive log id + - returns: [Waypoint] + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getTrack(id: String) async throws -> [Waypoint] { + return try await getTrackWithRequestBuilder(id: id).execute().body + } + + /** + Get a Drive Log's Track + - GET /drive-logs/{id}/track + - Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) drive log id + - returns: RequestBuilder<[Waypoint]> + */ + open class func getTrackWithRequestBuilder(id: String) -> RequestBuilder<[Waypoint]> { + var localVariablePath = "/drive-logs/{id}/track" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder<[Waypoint]>.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Replace a Drive Log's Track + + - parameter id: (path) drive log id + - parameter waypoint: (body) working time date span entity + - returns: [Waypoint] + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func updateTrack(id: String, waypoint: [Waypoint]) async throws -> [Waypoint] { + return try await updateTrackWithRequestBuilder(id: id, waypoint: waypoint).execute().body + } + + /** + Replace a Drive Log's Track + - PUT /drive-logs/{id}/track + - Replaces the Drive Log's Track with the waypoints in the request body. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) drive log id + - parameter waypoint: (body) working time date span entity + - returns: RequestBuilder<[Waypoint]> + */ + open class func updateTrackWithRequestBuilder(id: String, waypoint: [Waypoint]) -> RequestBuilder<[Waypoint]> { + var localVariablePath = "/drive-logs/{id}/track" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: waypoint) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder<[Waypoint]>.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/UserAPI.swift b/sdk/swift/TimrApi/APIs/UserAPI.swift new file mode 100644 index 0000000..8c70bbc --- /dev/null +++ b/sdk/swift/TimrApi/APIs/UserAPI.swift @@ -0,0 +1,389 @@ +// +// UserAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class UserAPI { + + /** + Create a User + + - parameter userCreate: (body) User entity + - returns: User + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createUser(userCreate: UserCreate) async throws -> User { + return try await createUserWithRequestBuilder(userCreate: userCreate).execute().body + } + + /** + Create a User + - POST /users + - Creates a User from the data in the request body. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter userCreate: (body) User entity + - returns: RequestBuilder + */ + open class func createUserWithRequestBuilder(userCreate: UserCreate) -> RequestBuilder { + let localVariablePath = "/users" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: userCreate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List a User's Team leaderships + + - parameter id: (path) ID of the User. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: TeamsPartialPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchUserTeamLeaderships(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TeamsSortColumn? = nil) async throws -> TeamsPartialPage { + return try await fetchUserTeamLeadershipsWithRequestBuilder(id: id, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List a User's Team leaderships + - GET /users/{id}/team-leaderships + - Lists the Teams the User leads. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter id: (path) ID of the User. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchUserTeamLeadershipsWithRequestBuilder(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TeamsSortColumn? = nil) -> RequestBuilder { + var localVariablePath = "/users/{id}/team-leaderships" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List a User's Team memberships + + - parameter id: (path) ID of the User. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: TeamsPartialPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchUserTeamMemberships(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TeamsSortColumn? = nil) async throws -> TeamsPartialPage { + return try await fetchUserTeamMembershipsWithRequestBuilder(id: id, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List a User's Team memberships + - GET /users/{id}/team-memberships + - Lists the Teams the User is a member of. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter id: (path) ID of the User. + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchUserTeamMembershipsWithRequestBuilder(id: String, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: TeamsSortColumn? = nil) -> RequestBuilder { + var localVariablePath = "/users/{id}/team-memberships" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Users + + - parameter name: (query) Only return Users whose name contains this text. (optional) + - parameter entryDateFrom: (query) Only return Users whose entry date is on or after this day. (optional) + - parameter entryDateTo: (query) Only return Users whose entry date is on or before this day. (optional) + - parameter resignDateFrom: (query) Only return Users whose resignation date is on or after this day. (optional) + - parameter resignDateTo: (query) Only return Users whose resignation date is on or before this day. (optional) + - parameter resigned: (query) Only return Users who have resigned (true) or have not resigned (false). (optional) + - parameter employeeNumber: (query) Only return Users with this employee number. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: UsersPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchUsers(name: String? = nil, entryDateFrom: Date? = nil, entryDateTo: Date? = nil, resignDateFrom: Date? = nil, resignDateTo: Date? = nil, resigned: Bool? = nil, employeeNumber: String? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: UsersSortColumn? = nil) async throws -> UsersPage { + return try await fetchUsersWithRequestBuilder(name: name, entryDateFrom: entryDateFrom, entryDateTo: entryDateTo, resignDateFrom: resignDateFrom, resignDateTo: resignDateTo, resigned: resigned, employeeNumber: employeeNumber, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Users + - GET /users + - Lists the Users the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter name: (query) Only return Users whose name contains this text. (optional) + - parameter entryDateFrom: (query) Only return Users whose entry date is on or after this day. (optional) + - parameter entryDateTo: (query) Only return Users whose entry date is on or before this day. (optional) + - parameter resignDateFrom: (query) Only return Users whose resignation date is on or after this day. (optional) + - parameter resignDateTo: (query) Only return Users whose resignation date is on or before this day. (optional) + - parameter resigned: (query) Only return Users who have resigned (true) or have not resigned (false). (optional) + - parameter employeeNumber: (query) Only return Users with this employee number. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchUsersWithRequestBuilder(name: String? = nil, entryDateFrom: Date? = nil, entryDateTo: Date? = nil, resignDateFrom: Date? = nil, resignDateTo: Date? = nil, resigned: Bool? = nil, employeeNumber: String? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: UsersSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/users" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "name": (wrappedValue: name?.encodeToJSON(), isExplode: true), + "entry_date_from": (wrappedValue: entryDateFrom?.encodeToJSON(), isExplode: true), + "entry_date_to": (wrappedValue: entryDateTo?.encodeToJSON(), isExplode: true), + "resign_date_from": (wrappedValue: resignDateFrom?.encodeToJSON(), isExplode: true), + "resign_date_to": (wrappedValue: resignDateTo?.encodeToJSON(), isExplode: true), + "resigned": (wrappedValue: resigned?.encodeToJSON(), isExplode: true), + "employee_number": (wrappedValue: employeeNumber?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a User + + - parameter id: (path) ID of the User. + - returns: User + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getUser(id: String) async throws -> User { + return try await getUserWithRequestBuilder(id: id).execute().body + } + + /** + Get a User + - GET /users/{id} + - Returns a single User by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the User. + - returns: RequestBuilder + */ + open class func getUserWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/users/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a User's Work Schedule Model + + - parameter id: (path) ID of the User. + - returns: WorkScheduleModel + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getUserWorkScheduleModel(id: String) async throws -> WorkScheduleModel { + return try await getUserWorkScheduleModelWithRequestBuilder(id: id).execute().body + } + + /** + Get a User's Work Schedule Model + - GET /users/{id}/work-schedule-model + - Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the User. + - returns: RequestBuilder + */ + open class func getUserWorkScheduleModelWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/users/{id}/work-schedule-model" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Update a User + + - parameter id: (path) ID of the User. + - parameter userUpdate: (body) User entity + - returns: User + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func updateUser(id: String, userUpdate: UserUpdate) async throws -> User { + return try await updateUserWithRequestBuilder(id: id, userUpdate: userUpdate).execute().body + } + + /** + Update a User + - PATCH /users/{id} + - Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the User. + - parameter userUpdate: (body) User entity + - returns: RequestBuilder + */ + open class func updateUserWithRequestBuilder(id: String, userUpdate: UserUpdate) -> RequestBuilder { + var localVariablePath = "/users/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: userUpdate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/WorkScheduleModelAPI.swift b/sdk/swift/TimrApi/APIs/WorkScheduleModelAPI.swift new file mode 100644 index 0000000..28745fe --- /dev/null +++ b/sdk/swift/TimrApi/APIs/WorkScheduleModelAPI.swift @@ -0,0 +1,159 @@ +// +// WorkScheduleModelAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class WorkScheduleModelAPI { + + /** + Delete a Work Schedule Model + + - parameter id: (path) ID of the Work Schedule Model. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteWorkScheduleModel(id: String) async throws { + return try await deleteWorkScheduleModelWithRequestBuilder(id: id).execute().body + } + + /** + Delete a Work Schedule Model + - DELETE /work-schedule-models/{id} + - Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Work Schedule Model. + - returns: RequestBuilder + */ + open class func deleteWorkScheduleModelWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/work-schedule-models/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Work Schedule Models + + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: WorkScheduleModelsPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchWorkScheduleModels(pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: WorkScheduleModelSortColumn? = nil) async throws -> WorkScheduleModelsPage { + return try await fetchWorkScheduleModelsWithRequestBuilder(pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Work Schedule Models + - GET /work-schedule-models + - Lists the Work Schedule Models the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchWorkScheduleModelsWithRequestBuilder(pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: WorkScheduleModelSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/work-schedule-models" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Work Schedule Model + + - parameter id: (path) ID of the Work Schedule Model. + - returns: WorkScheduleModel + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getWorkScheduleModel(id: String) async throws -> WorkScheduleModel { + return try await getWorkScheduleModelWithRequestBuilder(id: id).execute().body + } + + /** + Get a Work Schedule Model + - GET /work-schedule-models/{id} + - Returns a single Work Schedule Model by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Work Schedule Model. + - returns: RequestBuilder + */ + open class func getWorkScheduleModelWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/work-schedule-models/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/WorkingTimeAPI.swift b/sdk/swift/TimrApi/APIs/WorkingTimeAPI.swift new file mode 100644 index 0000000..c2596c4 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/WorkingTimeAPI.swift @@ -0,0 +1,333 @@ +// +// WorkingTimeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class WorkingTimeAPI { + + /** + Create a Working Time + + - parameter workingTimeCreate: (body) Working Time entity + - returns: WorkingTime + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createWorkingTime(workingTimeCreate: WorkingTimeCreate) async throws -> WorkingTime { + return try await createWorkingTimeWithRequestBuilder(workingTimeCreate: workingTimeCreate).execute().body + } + + /** + Create a Working Time + - POST /working-times + - Creates a Working Time from the data in the request body. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter workingTimeCreate: (body) Working Time entity + - returns: RequestBuilder + */ + open class func createWorkingTimeWithRequestBuilder(workingTimeCreate: WorkingTimeCreate) -> RequestBuilder { + let localVariablePath = "/working-times" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: workingTimeCreate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Delete a Working Time + + - parameter id: (path) ID of the Working Time. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteWorkingTime(id: String) async throws { + return try await deleteWorkingTimeWithRequestBuilder(id: id).execute().body + } + + /** + Delete a Working Time + - DELETE /working-times/{id} + - Deletes the Working Time. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Working Time. + - returns: RequestBuilder + */ + open class func deleteWorkingTimeWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/working-times/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List deleted Working Times + + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: DeletedEntryWithMetadataPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchDeletedWorkingTimes(lastModifiedAfter: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DeletedEntrySortColumn? = nil) async throws -> DeletedEntryWithMetadataPage { + return try await fetchDeletedWorkingTimesWithRequestBuilder(lastModifiedAfter: lastModifiedAfter, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List deleted Working Times + - GET /working-times:deleted + - Lists Working Times that were deleted, so a client holding a local copy can reconcile. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchDeletedWorkingTimesWithRequestBuilder(lastModifiedAfter: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DeletedEntrySortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/working-times:deleted" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "last_modified_after": (wrappedValue: lastModifiedAfter?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Working Times + + - parameter notes: (query) Only return entries whose notes contain this text. (optional) + - parameter startFrom: (query) Only return entries starting on or after this day. (optional) + - parameter startTo: (query) Only return entries starting on or before this day. (optional) + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter workingTimeTypes: (query) Only return entries of these Working Time Types. (optional) + - parameter workingTimeTypeCategories: (query) Only return entries whose Working Time Type is in one of these categories. (optional) + - parameter statuses: (query) Only return entries in one of these statuses. (optional) + - parameter users: (query) Only return entries belonging to these users. (optional) + - parameter changed: (query) Only return entries that were changed by the user (true) or left unchanged (false). (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: WorkingTimesPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchWorkingTimes(notes: String? = nil, startFrom: Date? = nil, startTo: Date? = nil, lastModifiedAfter: Date? = nil, workingTimeTypes: [String]? = nil, workingTimeTypeCategories: [WorkingTimeTypeCategory]? = nil, statuses: [WorkingTimeStatus]? = nil, users: [String]? = nil, changed: Bool? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: WorkingTimesSortColumn? = nil) async throws -> WorkingTimesPage { + return try await fetchWorkingTimesWithRequestBuilder(notes: notes, startFrom: startFrom, startTo: startTo, lastModifiedAfter: lastModifiedAfter, workingTimeTypes: workingTimeTypes, workingTimeTypeCategories: workingTimeTypeCategories, statuses: statuses, users: users, changed: changed, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Working Times + - GET /working-times + - Lists the Working Times the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter notes: (query) Only return entries whose notes contain this text. (optional) + - parameter startFrom: (query) Only return entries starting on or after this day. (optional) + - parameter startTo: (query) Only return entries starting on or before this day. (optional) + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter workingTimeTypes: (query) Only return entries of these Working Time Types. (optional) + - parameter workingTimeTypeCategories: (query) Only return entries whose Working Time Type is in one of these categories. (optional) + - parameter statuses: (query) Only return entries in one of these statuses. (optional) + - parameter users: (query) Only return entries belonging to these users. (optional) + - parameter changed: (query) Only return entries that were changed by the user (true) or left unchanged (false). (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchWorkingTimesWithRequestBuilder(notes: String? = nil, startFrom: Date? = nil, startTo: Date? = nil, lastModifiedAfter: Date? = nil, workingTimeTypes: [String]? = nil, workingTimeTypeCategories: [WorkingTimeTypeCategory]? = nil, statuses: [WorkingTimeStatus]? = nil, users: [String]? = nil, changed: Bool? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: WorkingTimesSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/working-times" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "notes": (wrappedValue: notes?.encodeToJSON(), isExplode: true), + "start_from": (wrappedValue: startFrom?.encodeToJSON(), isExplode: true), + "start_to": (wrappedValue: startTo?.encodeToJSON(), isExplode: true), + "last_modified_after": (wrappedValue: lastModifiedAfter?.encodeToJSON(), isExplode: true), + "working_time_types": (wrappedValue: workingTimeTypes?.encodeToJSON(), isExplode: true), + "working_time_type_categories": (wrappedValue: workingTimeTypeCategories?.encodeToJSON(), isExplode: true), + "statuses": (wrappedValue: statuses?.encodeToJSON(), isExplode: true), + "users": (wrappedValue: users?.encodeToJSON(), isExplode: true), + "changed": (wrappedValue: changed?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Working Time + + - parameter id: (path) ID of the Working Time. + - returns: WorkingTime + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getWorkingTime(id: String) async throws -> WorkingTime { + return try await getWorkingTimeWithRequestBuilder(id: id).execute().body + } + + /** + Get a Working Time + - GET /working-times/{id} + - Returns a single Working Time by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Working Time. + - returns: RequestBuilder + */ + open class func getWorkingTimeWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/working-times/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Update a Working Time + + - parameter id: (path) ID of the Working Time. + - parameter workingTimeUpdate: (body) Working Time entity + - returns: WorkingTime + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func updateWorkingTime(id: String, workingTimeUpdate: WorkingTimeUpdate) async throws -> WorkingTime { + return try await updateWorkingTimeWithRequestBuilder(id: id, workingTimeUpdate: workingTimeUpdate).execute().body + } + + /** + Update a Working Time + - PATCH /working-times/{id} + - Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Working Time. + - parameter workingTimeUpdate: (body) Working Time entity + - returns: RequestBuilder + */ + open class func updateWorkingTimeWithRequestBuilder(id: String, workingTimeUpdate: WorkingTimeUpdate) -> RequestBuilder { + var localVariablePath = "/working-times/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: workingTimeUpdate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/WorkingTimeDateSpanAPI.swift b/sdk/swift/TimrApi/APIs/WorkingTimeDateSpanAPI.swift new file mode 100644 index 0000000..6ddcb01 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/WorkingTimeDateSpanAPI.swift @@ -0,0 +1,321 @@ +// +// WorkingTimeDateSpanAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class WorkingTimeDateSpanAPI { + + /** + Create a Working Time Date Span + + - parameter workingTimeDateSpanCreate: (body) Working Time Date Span entity + - returns: WorkingTimeDateSpan + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func createWorkingTimeDateSpan(workingTimeDateSpanCreate: WorkingTimeDateSpanCreate) async throws -> WorkingTimeDateSpan { + return try await createWorkingTimeDateSpanWithRequestBuilder(workingTimeDateSpanCreate: workingTimeDateSpanCreate).execute().body + } + + /** + Create a Working Time Date Span + - POST /working-time-date-spans + - Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter workingTimeDateSpanCreate: (body) Working Time Date Span entity + - returns: RequestBuilder + */ + open class func createWorkingTimeDateSpanWithRequestBuilder(workingTimeDateSpanCreate: WorkingTimeDateSpanCreate) -> RequestBuilder { + let localVariablePath = "/working-time-date-spans" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: workingTimeDateSpanCreate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Delete a Working Time Date Span + + - parameter id: (path) ID of the Working Time Date Span. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteWorkingTimeDateSpan(id: String) async throws { + return try await deleteWorkingTimeDateSpanWithRequestBuilder(id: id).execute().body + } + + /** + Delete a Working Time Date Span + - DELETE /working-time-date-spans/{id} + - Deletes the Working Time Date Span together with the Working Times it covers. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Working Time Date Span. + - returns: RequestBuilder + */ + open class func deleteWorkingTimeDateSpanWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/working-time-date-spans/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List deleted Working Time Date Spans + + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: DeletedEntryWithMetadataPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchDeletedWorkingTimeDateSpans(lastModifiedAfter: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DeletedEntrySortColumn? = nil) async throws -> DeletedEntryWithMetadataPage { + return try await fetchDeletedWorkingTimeDateSpansWithRequestBuilder(lastModifiedAfter: lastModifiedAfter, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List deleted Working Time Date Spans + - GET /working-time-date-spans:deleted + - Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchDeletedWorkingTimeDateSpansWithRequestBuilder(lastModifiedAfter: Date? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: DeletedEntrySortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/working-time-date-spans:deleted" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "last_modified_after": (wrappedValue: lastModifiedAfter?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Working Time Date Spans + + - parameter from: (query) Only return Working Time Date Spans that end on or after this day. (optional) + - parameter to: (query) Only return entries starting on or before this day. (optional) + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter workingTimeTypes: (query) Only return entries of these Working Time Types. (optional) + - parameter users: (query) Only return entries belonging to these users. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: WorkingTimeDateSpanPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchWorkingTimeDateSpans(from: Date? = nil, to: Date? = nil, lastModifiedAfter: Date? = nil, workingTimeTypes: [String]? = nil, users: [String]? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: WorkingTimeDateSpansSortColumn? = nil) async throws -> WorkingTimeDateSpanPage { + return try await fetchWorkingTimeDateSpansWithRequestBuilder(from: from, to: to, lastModifiedAfter: lastModifiedAfter, workingTimeTypes: workingTimeTypes, users: users, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Working Time Date Spans + - GET /working-time-date-spans + - Lists the Working Time Date Spans the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter from: (query) Only return Working Time Date Spans that end on or after this day. (optional) + - parameter to: (query) Only return entries starting on or before this day. (optional) + - parameter lastModifiedAfter: (query) Only return entries modified after this instant. (optional) + - parameter workingTimeTypes: (query) Only return entries of these Working Time Types. (optional) + - parameter users: (query) Only return entries belonging to these users. (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchWorkingTimeDateSpansWithRequestBuilder(from: Date? = nil, to: Date? = nil, lastModifiedAfter: Date? = nil, workingTimeTypes: [String]? = nil, users: [String]? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: WorkingTimeDateSpansSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/working-time-date-spans" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "from": (wrappedValue: from?.encodeToJSON(), isExplode: true), + "to": (wrappedValue: to?.encodeToJSON(), isExplode: true), + "last_modified_after": (wrappedValue: lastModifiedAfter?.encodeToJSON(), isExplode: true), + "working_time_types": (wrappedValue: workingTimeTypes?.encodeToJSON(), isExplode: true), + "users": (wrappedValue: users?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Working Time Date Span + + - parameter id: (path) ID of the Working Time Date Span. + - returns: WorkingTimeDateSpan + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getWorkingTimeDateSpan(id: String) async throws -> WorkingTimeDateSpan { + return try await getWorkingTimeDateSpanWithRequestBuilder(id: id).execute().body + } + + /** + Get a Working Time Date Span + - GET /working-time-date-spans/{id} + - Returns a single Working Time Date Span by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Working Time Date Span. + - returns: RequestBuilder + */ + open class func getWorkingTimeDateSpanWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/working-time-date-spans/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Update a Working Time Date Span + + - parameter id: (path) ID of the Working Time Date Span. + - parameter workingTimeDateSpanUpdate: (body) working time date span entity + - returns: WorkingTimeDateSpan? + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func updateWorkingTimeDateSpan(id: String, workingTimeDateSpanUpdate: WorkingTimeDateSpanUpdate) async throws -> WorkingTimeDateSpan? { + return try await updateWorkingTimeDateSpanWithRequestBuilder(id: id, workingTimeDateSpanUpdate: workingTimeDateSpanUpdate).execute().body + } + + /** + Update a Working Time Date Span + - PATCH /working-time-date-spans/{id} + - Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Working Time Date Span. + - parameter workingTimeDateSpanUpdate: (body) working time date span entity + - returns: RequestBuilder + */ + open class func updateWorkingTimeDateSpanWithRequestBuilder(id: String, workingTimeDateSpanUpdate: WorkingTimeDateSpanUpdate) -> RequestBuilder { + var localVariablePath = "/working-time-date-spans/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: workingTimeDateSpanUpdate) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/APIs/WorkingTimeTypeAPI.swift b/sdk/swift/TimrApi/APIs/WorkingTimeTypeAPI.swift new file mode 100644 index 0000000..2e4ed92 --- /dev/null +++ b/sdk/swift/TimrApi/APIs/WorkingTimeTypeAPI.swift @@ -0,0 +1,183 @@ +// +// WorkingTimeTypeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class WorkingTimeTypeAPI { + + /** + Delete a Working Time Type + + - parameter id: (path) ID of the Working Time Type. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteWorkingTimeType(id: String) async throws { + return try await deleteWorkingTimeTypeWithRequestBuilder(id: id).execute().body + } + + /** + Delete a Working Time Type + - DELETE /working-time-types/{id} + - Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Working Time Type. + - returns: RequestBuilder + */ + open class func deleteWorkingTimeTypeWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/working-time-types/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + List Working Time Types + + - parameter name: (query) Only return entries whose name contains this text. (optional) + - parameter shortName: (query) filter by short name (optional) + - parameter description: (query) filter by description (optional) + - parameter categories: (query) filter by WorkingTimeTypeCategory (optional) + - parameter subCategories: (query) filter by WorkingTimeTypeSubCategory (optional) + - parameter editUnits: (query) filter by WorkingTimeType's DurationUnit (optional) + - parameter archived: (query) Only return entries that are archived (true) or not archived (false). (optional) + - parameter recordingModes: (query) filter entries bAWS on their RecordingMode (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: WorkingTimeTypesPage + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func fetchWorkingTimeTypes(name: String? = nil, shortName: String? = nil, description: String? = nil, categories: [WorkingTimeTypeCategory]? = nil, subCategories: [WorkingTimeTypeSubCategory]? = nil, editUnits: [DurationUnit]? = nil, archived: Bool? = nil, recordingModes: [RecordingModeUser]? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: WorkingTimeTypesSortColumn? = nil) async throws -> WorkingTimeTypesPage { + return try await fetchWorkingTimeTypesWithRequestBuilder(name: name, shortName: shortName, description: description, categories: categories, subCategories: subCategories, editUnits: editUnits, archived: archived, recordingModes: recordingModes, pageToken: pageToken, limit: limit, sortDirection: sortDirection, sortBy: sortBy).execute().body + } + + /** + List Working Time Types + - GET /working-time-types + - Lists the Working Time Types the authenticated user or API token can access. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - responseHeaders: [Link(String)] + - parameter name: (query) Only return entries whose name contains this text. (optional) + - parameter shortName: (query) filter by short name (optional) + - parameter description: (query) filter by description (optional) + - parameter categories: (query) filter by WorkingTimeTypeCategory (optional) + - parameter subCategories: (query) filter by WorkingTimeTypeSubCategory (optional) + - parameter editUnits: (query) filter by WorkingTimeType's DurationUnit (optional) + - parameter archived: (query) Only return entries that are archived (true) or not archived (false). (optional) + - parameter recordingModes: (query) filter entries bAWS on their RecordingMode (optional) + - parameter pageToken: (query) Token identifying the page to return. Take it from the 'next_page_token' field of the previous response. (optional) + - parameter limit: (query) Maximum number of entries per page. Values above 500 are capped at 500. (optional, default to 20) + - parameter sortDirection: (query) Direction to sort the entries in. (optional) + - parameter sortBy: (query) Property to sort the entries by. (optional) + - returns: RequestBuilder + */ + open class func fetchWorkingTimeTypesWithRequestBuilder(name: String? = nil, shortName: String? = nil, description: String? = nil, categories: [WorkingTimeTypeCategory]? = nil, subCategories: [WorkingTimeTypeSubCategory]? = nil, editUnits: [DurationUnit]? = nil, archived: Bool? = nil, recordingModes: [RecordingModeUser]? = nil, pageToken: String? = nil, limit: Int? = nil, sortDirection: SortDirection? = nil, sortBy: WorkingTimeTypesSortColumn? = nil) -> RequestBuilder { + let localVariablePath = "/working-time-types" + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "name": (wrappedValue: name?.encodeToJSON(), isExplode: true), + "short_name": (wrappedValue: shortName?.encodeToJSON(), isExplode: true), + "description": (wrappedValue: description?.encodeToJSON(), isExplode: true), + "categories": (wrappedValue: categories?.encodeToJSON(), isExplode: true), + "sub_categories": (wrappedValue: subCategories?.encodeToJSON(), isExplode: true), + "edit_units": (wrappedValue: editUnits?.encodeToJSON(), isExplode: true), + "archived": (wrappedValue: archived?.encodeToJSON(), isExplode: true), + "recording_modes": (wrappedValue: recordingModes?.encodeToJSON(), isExplode: true), + "page_token": (wrappedValue: pageToken?.encodeToJSON(), isExplode: true), + "limit": (wrappedValue: limit?.encodeToJSON(), isExplode: true), + "sort_direction": (wrappedValue: sortDirection?.encodeToJSON(), isExplode: true), + "sort_by": (wrappedValue: sortBy?.encodeToJSON(), isExplode: true), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + + /** + Get a Working Time Type + + - parameter id: (path) ID of the Working Time Type. + - returns: WorkingTimeType + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func getWorkingTimeType(id: String) async throws -> WorkingTimeType { + return try await getWorkingTimeTypeWithRequestBuilder(id: id).execute().body + } + + /** + Get a Working Time Type + - GET /working-time-types/{id} + - Returns a single Working Time Type by its ID. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Working Time Type. + - returns: RequestBuilder + */ + open class func getWorkingTimeTypeWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/working-time-types/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } +} diff --git a/sdk/swift/TimrApi/AlamofireImplementations.swift b/sdk/swift/TimrApi/AlamofireImplementations.swift new file mode 100644 index 0000000..325a185 --- /dev/null +++ b/sdk/swift/TimrApi/AlamofireImplementations.swift @@ -0,0 +1,415 @@ +// AlamofireImplementations.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return AlamofireDecodableRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore = SynchronizedDictionary() + +open class AlamofireRequestBuilder: RequestBuilder { + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication) + } + + /** + May be overridden by a subclass if you want to control the session + configuration. + */ + open func createAlamofireSession(interceptor: RequestInterceptor? = nil) -> Alamofire.Session { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = buildHeaders() + return Alamofire.Session(configuration: configuration, + interceptor: interceptor) + } + + /** + May be overridden by a subclass if you want to custom request constructor. + */ + open func createURLRequest() -> URLRequest? { + let xMethod = Alamofire.HTTPMethod(rawValue: method) + + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + encoding = JSONDataEncoding() + + default: + fatalError("Unsupported HTTPMethod - \(xMethod.rawValue)") + } + + guard let originalRequest = try? URLRequest(url: URLString, method: xMethod, headers: HTTPHeaders(buildHeaders())) else { return nil } + return try? encoding.encode(originalRequest, with: parameters) + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: Session, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: HTTPHeaders(headers)) + } + + @discardableResult + override open func execute(_ apiResponseQueue: DispatchQueue = TimrAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> RequestTask { + let managerId = UUID().uuidString + // Create a new manager for each request to customize its request header + let manager = createAlamofireSession() + managerStore[managerId] = manager + + let xMethod = Alamofire.HTTPMethod(rawValue: method) + + let encoding: ParameterEncoding? + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType.hasPrefix("application/") && contentType.contains("json") { + encoding = JSONDataEncoding() + } else if contentType.hasPrefix("multipart/form-data") { + encoding = nil + + let upload = manager.upload(multipartFormData: { mpForm in + for (k, v) in self.parameters! { + for v in (v as? Array ?? [v]) { + switch v { + case let fileURL as URL: + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } else { + mpForm.append(fileURL, withName: k) + } + case let string as String: + mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) + case let number as NSNumber: + mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k) + case let data as Data: + mpForm.append(data, withName: k) + case let uuid as UUID: + mpForm.append(uuid.uuidString.data(using: String.Encoding.utf8)!, withName: k) + default: + fatalError("Unprocessable value \(v) with key \(k)") + } + } + } + }, to: URLString, method: xMethod, headers: nil) + .uploadProgress { progress in + if let onProgressReady = self.onProgressReady { + onProgressReady(progress) + } + } + + requestTask.set(request: upload) + + self.processRequest(request: upload, managerId, apiResponseQueue, completion) + } else if contentType.hasPrefix("application/x-www-form-urlencoded") { + encoding = URLEncoding(destination: .httpBody) + } else { + fatalError("Unsupported Media Type - \(contentType)") + } + + default: + fatalError("Unsupported HTTPMethod - \(xMethod.rawValue)") + } + + if let encoding = encoding { + let request = makeRequest(manager: manager, method: xMethod, encoding: encoding, headers: headers) + if let onProgressReady = self.onProgressReady { + onProgressReady(request.uploadProgress) + } + processRequest(request: request, managerId, apiResponseQueue, completion) + requestTask.set(request: request) + } + + return requestTask + } + + fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) { + if let credential = self.credential { + request.authenticate(with: credential) + } + + let cleanupRequest = { + managerStore[managerId] = nil + } + + let validatedRequest = request.validate(statusCode: Configuration.successfulStatusCodeRange) + + switch T.self { + case is Void.Type: + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { voidResponse in + cleanupRequest() + + switch voidResponse.result { + case .success: + completion(.success(Response(response: voidResponse.response!, body: () as! T, bodyData: voidResponse.data))) + case let .failure(error): + completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) + } + + }) + default: + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") + } + } + + open func buildHeaders() -> [String: String] { + var httpHeaders = Alamofire.HTTPHeaders.default.dictionary + for (key, value) in headers { + httpHeaders[key] = value + } + return httpHeaders + } + + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { + + guard let contentDisposition = contentDisposition else { + return nil + } + + let items = contentDisposition.components(separatedBy: ";") + + var filename: String? + + for contentItem in items { + + let filenameKey = "filename=" + guard let range = contentItem.range(of: filenameKey) else { + continue + } + + filename = contentItem + return filename? + .replacingCharacters(in: range, with: "") + .replacingOccurrences(of: "\"", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + return filename + + } + + fileprivate func getPath(from url: URL) throws -> String { + + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + throw DownloadException.requestMissingPath + } + + if path.hasPrefix("/") { + path.remove(at: path.startIndex) + } + + return path + + } + + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + return url + } + +} + +open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder { + + override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) { + if let credential = self.credential { + request.authenticate(with: credential) + } + + let cleanupRequest = { + managerStore[managerId] = nil + } + + let validatedRequest = request.validate(statusCode: Configuration.successfulStatusCodeRange) + + switch T.self { + case is String.Type: + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.stringResponseSerializer, + completionHandler: { stringResponse in + cleanupRequest() + + switch stringResponse.result { + case let .success(value): + completion(.success(Response(response: stringResponse.response!, body: value as! T, bodyData: stringResponse.data))) + case let .failure(error): + completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.response, error))) + } + + }) + case is URL.Type: + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { dataResponse in + cleanupRequest() + + do { + + guard case .success = dataResponse.result else { + throw DownloadException.responseFailed + } + + guard let data = dataResponse.data else { + throw DownloadException.responseDataMissing + } + + guard let request = request.request else { + throw DownloadException.requestMissing + } + + let fileManager = FileManager.default + let urlRequest = try request.asURLRequest() + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try self.getURL(from: urlRequest) + + var requestPath = try self.getPath(from: requestURL) + + if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.Timr.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: dataResponse.response!, body: filePath as! T, bodyData: data))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, error))) + } + return + }) + case is Void.Type: + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { voidResponse in + cleanupRequest() + + switch voidResponse.result { + case .success: + completion(.success(Response(response: voidResponse.response!, body: () as! T, bodyData: voidResponse.data))) + case let .failure(error): + completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) + } + + }) + case is Data.Type: + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { dataResponse in + cleanupRequest() + + switch dataResponse.result { + case .success: + completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as! T, bodyData: dataResponse.data))) + case let .failure(error): + completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) + } + + }) + default: + validatedRequest.response(queue: apiResponseQueue, + responseSerializer: Configuration.dataResponseSerializer, + completionHandler: { dataResponse in + cleanupRequest() + + if case let .failure(error) = dataResponse.result { + completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) + return + } + + guard let httpResponse = dataResponse.response else { + completion(.failure(ErrorResponse.error(-2, nil, dataResponse.response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard let data = dataResponse.data, !data.isEmpty else { + if T.self is ExpressibleByNilLiteral.Type { + completion(.success(Response(response: httpResponse, body: Optional.none as! T, bodyData: dataResponse.data))) + } else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, httpResponse, DecodableRequestBuilderError.emptyDataResponse))) + } + return + } + + let decodeResult = CodableHelper.decode(T.self, from: data) + + switch decodeResult { + case let .success(decodableObj): + completion(.success(Response(response: httpResponse, body: decodableObj, bodyData: data))) + case let .failure(error): + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, httpResponse, error))) + } + + }) + } + } + +} + +extension JSONDataEncoding: ParameterEncoding { + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + let urlRequest = try urlRequest.asURLRequest() + + // Alamofire 5.10 changed type of Parameters so that it is no longer equivalent to [String: Any] + // cast this type so that the call to encode is not recursive + return encode(urlRequest, with: parameters as [String: Any]?) + } +} diff --git a/sdk/swift/TimrApi/CodableHelper.swift b/sdk/swift/TimrApi/CodableHelper.swift new file mode 100644 index 0000000..09c82e5 --- /dev/null +++ b/sdk/swift/TimrApi/CodableHelper.swift @@ -0,0 +1,49 @@ +// +// CodableHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class CodableHelper { + private static var customDateFormatter: DateFormatter? + private static var defaultDateFormatter: DateFormatter = OpenISO8601DateFormatter() + + private static var customJSONDecoder: JSONDecoder? + private static var defaultJSONDecoder: JSONDecoder = { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .formatted(CodableHelper.dateFormatter) + return decoder + }() + + private static var customJSONEncoder: JSONEncoder? + private static var defaultJSONEncoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .formatted(CodableHelper.dateFormatter) + encoder.outputFormatting = .prettyPrinted + return encoder + }() + + public static var dateFormatter: DateFormatter { + get { return customDateFormatter ?? defaultDateFormatter } + set { customDateFormatter = newValue } + } + public static var jsonDecoder: JSONDecoder { + get { return customJSONDecoder ?? defaultJSONDecoder } + set { customJSONDecoder = newValue } + } + public static var jsonEncoder: JSONEncoder { + get { return customJSONEncoder ?? defaultJSONEncoder } + set { customJSONEncoder = newValue } + } + + open class func decode(_ type: T.Type, from data: Data) -> Swift.Result where T: Decodable { + return Swift.Result { try jsonDecoder.decode(type, from: data) } + } + + open class func encode(_ value: T) -> Swift.Result where T: Encodable { + return Swift.Result { try jsonEncoder.encode(value) } + } +} diff --git a/sdk/swift/TimrApi/Configuration.swift b/sdk/swift/TimrApi/Configuration.swift new file mode 100644 index 0000000..50c6473 --- /dev/null +++ b/sdk/swift/TimrApi/Configuration.swift @@ -0,0 +1,43 @@ +// Configuration.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif +import Alamofire + +open class Configuration { + + /// Configures the range of HTTP status codes that will result in a successful response + /// + /// If a HTTP status code is outside of this range the response will be interpreted as failed. + public static var successfulStatusCodeRange: Range = 200..<300 + /// ResponseSerializer that will be used by the generator for `Data` responses + /// + /// If unchanged, Alamofires default `DataResponseSerializer` will be used. + public static var dataResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(DataResponseSerializer()) + /// ResponseSerializer that will be used by the generator for `String` responses + /// + /// If unchanged, Alamofires default `StringResponseSerializer` will be used. + public static var stringResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(StringResponseSerializer()) +} + +/// Type-erased ResponseSerializer +/// +/// This is needed in order to use `ResponseSerializer` as a Type in `Configuration`. Obsolete with `any` keyword in Swift >= 5.7 +public struct AnyResponseSerializer: ResponseSerializer { + + let _serialize: (URLRequest?, HTTPURLResponse?, Data?, Error?) throws -> T + + public init(_ delegatee: V) where V.SerializedObject == T { + _serialize = delegatee.serialize + } + + public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T { + try _serialize(request, response, data, error) + } +} \ No newline at end of file diff --git a/sdk/swift/TimrApi/Extensions.swift b/sdk/swift/TimrApi/Extensions.swift new file mode 100644 index 0000000..2082fb0 --- /dev/null +++ b/sdk/swift/TimrApi/Extensions.swift @@ -0,0 +1,237 @@ +// Extensions.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension Bool: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension Decimal: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension String: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension URL: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension UUID: JSONEncodable { + func encodeToJSON() -> Any { self } +} + +extension RawRepresentable where RawValue: JSONEncodable { + func encodeToJSON() -> Any { return self.rawValue } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key] = encodeIfPossible(value) + } + return dictionary + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return CodableHelper.dateFormatter.string(from: self) + } +} + +extension JSONEncodable where Self: Encodable { + func encodeToJSON() -> Any { + guard let data = try? CodableHelper.jsonEncoder.encode(self) else { + fatalError("Could not encode to json: \(self)") + } + return data.encodeToJSON() + } +} + +extension String: CodingKey { + + public var stringValue: String { + return self + } + + public init?(stringValue: String) { + self.init(stringLiteral: stringValue) + } + + public var intValue: Int? { + return nil + } + + public init?(intValue: Int) { + return nil + } + +} + +extension KeyedEncodingContainerProtocol { + + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { + var arrayContainer = nestedUnkeyedContainer(forKey: key) + try arrayContainer.encode(contentsOf: values) + } + + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { + if let values = values { + try encodeArray(values, forKey: key) + } + } + + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { + for (key, value) in pairs { + try encode(value, forKey: key) + } + } + + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { + if let pairs = pairs { + try encodeMap(pairs) + } + } + + public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { + let decimalNumber = NSDecimalNumber(decimal: value) + let numberFormatter = NumberFormatter() + numberFormatter.numberStyle = .decimal + numberFormatter.locale = Locale(identifier: "en_US") + numberFormatter.usesGroupingSeparator = false + let formattedString = numberFormatter.string(from: decimalNumber) ?? "\(value)" + try encode(formattedString, forKey: key) + } + + public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { + if let value = value { + try encode(value, forKey: key) + } + } +} + +extension KeyedDecodingContainerProtocol { + + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { + var tmpArray = [T]() + + var nestedContainer = try nestedUnkeyedContainer(forKey: key) + while !nestedContainer.isAtEnd { + let arrayValue = try nestedContainer.decode(T.self) + tmpArray.append(arrayValue) + } + + return tmpArray + } + + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? + + if contains(key) { + tmpArray = try decodeArray(T.self, forKey: key) + } + + return tmpArray + } + + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] + + for key in allKeys { + if !excludedKeys.contains(key) { + let value = try decode(T.self, forKey: key) + map[key] = value + } + } + + return map + } + + public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal { + let stringValue = try decode(String.self, forKey: key) + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + + public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? { + guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { + return nil + } + guard let decimalValue = Decimal(string: stringValue) else { + let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value") + throw DecodingError.typeMismatch(type, context) + } + + return decimalValue + } + +} + +extension HTTPURLResponse { + var isStatusCodeSuccessful: Bool { + return Configuration.successfulStatusCodeRange.contains(statusCode) + } +} diff --git a/sdk/swift/TimrApi/JSONDataEncoding.swift b/sdk/swift/TimrApi/JSONDataEncoding.swift new file mode 100644 index 0000000..cb3121a --- /dev/null +++ b/sdk/swift/TimrApi/JSONDataEncoding.swift @@ -0,0 +1,56 @@ +// +// JSONDataEncoding.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +public struct JSONDataEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) -> URLRequest { + var urlRequest = urlRequest + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> [String: Any]? { + var returnedParams: [String: Any]? + if let jsonData = jsonData, !jsonData.isEmpty { + var params: [String: Any] = [:] + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/sdk/swift/TimrApi/JSONEncodingHelper.swift b/sdk/swift/TimrApi/JSONEncodingHelper.swift new file mode 100644 index 0000000..02f78ff --- /dev/null +++ b/sdk/swift/TimrApi/JSONEncodingHelper.swift @@ -0,0 +1,45 @@ +// +// JSONEncodingHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? { + var params: [String: Any]? + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj) + do { + let data = try encodeResult.get() + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + } + } + + return params + } + + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? { + var params: [String: Any]? + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + return nil + } + } + + return params + } + +} diff --git a/sdk/swift/TimrApi/Models.swift b/sdk/swift/TimrApi/Models.swift new file mode 100644 index 0000000..647a421 --- /dev/null +++ b/sdk/swift/TimrApi/Models.swift @@ -0,0 +1,130 @@ +// Models.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif +import Alamofire + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + +/// A flexible type that can be encoded (`.encodeNull` or `.encodeValue`) +/// or not encoded (`.encodeNothing`). Intended for request payloads. +public enum NullEncodable: Hashable { + case encodeNothing + case encodeNull + case encodeValue(Wrapped) +} + +extension NullEncodable: Codable where Wrapped: Codable { + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let value = try? container.decode(Wrapped.self) { + self = .encodeValue(value) + } else if container.decodeNil() { + self = .encodeNull + } else { + self = .encodeNothing + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .encodeNothing: return + case .encodeNull: try container.encodeNil() + case .encodeValue(let wrapped): try container.encode(wrapped) + } + } +} + +public enum ErrorResponse: Error { + case error(Int, Data?, URLResponse?, Error) +} + +public enum DownloadException: Error { + case responseDataMissing + case responseFailed + case requestMissing + case requestMissingPath + case requestMissingURL +} + +public enum DecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case unsuccessfulHTTPStatusCode + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T + public let bodyData: Data? + + public init(statusCode: Int, header: [String: String], body: T, bodyData: Data?) { + self.statusCode = statusCode + self.header = header + self.body = body + self.bodyData = bodyData + } + + public convenience init(response: HTTPURLResponse, body: T, bodyData: Data?) { + let rawHeader = response.allHeaderFields + var responseHeader = [String: String]() + for (key, value) in rawHeader { + if let key = key.base as? String, let value = value as? String { + responseHeader[key] = value + } + } + self.init(statusCode: response.statusCode, header: responseHeader, body: body, bodyData: bodyData) + } +} + +public final class RequestTask: @unchecked Sendable { + private let lock = NSRecursiveLock() + private var request: Request? + + internal func set(request: Request) { + lock.lock() + defer { lock.unlock() } + self.request = request + } + + public func cancel() { + lock.lock() + defer { lock.unlock() } + request?.cancel() + request = nil + } +} diff --git a/sdk/swift/TimrApi/Models/Accounts.swift b/sdk/swift/TimrApi/Models/Accounts.swift new file mode 100644 index 0000000..f5926c9 --- /dev/null +++ b/sdk/swift/TimrApi/Models/Accounts.swift @@ -0,0 +1,45 @@ +// +// Accounts.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Accounts: Codable, JSONEncodable, Hashable { + + /** date of last balance */ + public var lastBalanceDate: Date? + public var timeAccount: TimeAccount? + public var overtimeSurchargeAccounts: [OvertimeSurchargeAccounts]? + public var vacationAccount: VacationAccount? + + public init(lastBalanceDate: Date?, timeAccount: TimeAccount? = nil, overtimeSurchargeAccounts: [OvertimeSurchargeAccounts]? = nil, vacationAccount: VacationAccount? = nil) { + self.lastBalanceDate = lastBalanceDate + self.timeAccount = timeAccount + self.overtimeSurchargeAccounts = overtimeSurchargeAccounts + self.vacationAccount = vacationAccount + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case lastBalanceDate = "last_balance_date" + case timeAccount = "time_account" + case overtimeSurchargeAccounts = "overtime_surcharge_accounts" + case vacationAccount = "vacation_account" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(lastBalanceDate, forKey: .lastBalanceDate) + try container.encodeIfPresent(timeAccount, forKey: .timeAccount) + try container.encodeIfPresent(overtimeSurchargeAccounts, forKey: .overtimeSurchargeAccounts) + try container.encodeIfPresent(vacationAccount, forKey: .vacationAccount) + } +} + diff --git a/sdk/swift/TimrApi/Models/BreakTime.swift b/sdk/swift/TimrApi/Models/BreakTime.swift new file mode 100644 index 0000000..10d3112 --- /dev/null +++ b/sdk/swift/TimrApi/Models/BreakTime.swift @@ -0,0 +1,55 @@ +// +// BreakTime.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum BreakTime: Codable, JSONEncodable, Hashable { + case typeBreakTimeAutomatic(BreakTimeAutomatic) + case typeBreakTimeManual(BreakTimeManual) + case typeBreakTimeOngoing(BreakTimeOngoing) + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .typeBreakTimeAutomatic(let value): + try container.encode(value) + case .typeBreakTimeManual(let value): + try container.encode(value) + case .typeBreakTimeOngoing(let value): + try container.encode(value) + } + } + + private enum DiscriminatorCodingKey: String, CodingKey { + case type = "type" + } + + public init(from decoder: Decoder) throws { + let keyedContainer = try decoder.container(keyedBy: DiscriminatorCodingKey.self) + let discriminatorValue = try keyedContainer.decode(String.self, forKey: .type) + + switch discriminatorValue { + case "automatic": + self = .typeBreakTimeAutomatic(try BreakTimeAutomatic(from: decoder)) + case "manual": + self = .typeBreakTimeManual(try BreakTimeManual(from: decoder)) + case "ongoing": + self = .typeBreakTimeOngoing(try BreakTimeOngoing(from: decoder)) + default: + throw DecodingError.dataCorrupted( + DecodingError.Context( + codingPath: decoder.codingPath, + debugDescription: "Unknown discriminator value '\(discriminatorValue)' for BreakTime" + ) + ) + } + } +} + diff --git a/sdk/swift/TimrApi/Models/BreakTimeAutomatic.swift b/sdk/swift/TimrApi/Models/BreakTimeAutomatic.swift new file mode 100644 index 0000000..b755484 --- /dev/null +++ b/sdk/swift/TimrApi/Models/BreakTimeAutomatic.swift @@ -0,0 +1,47 @@ +// +// BreakTimeAutomatic.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct BreakTimeAutomatic: Codable, JSONEncodable, Hashable { + + public var type: BreakTimeType + /** Duration of break in minutes */ + public var durationMinutes: Int + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date? + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + + public init(type: BreakTimeType, durationMinutes: Int, start: Date?, end: Date?) { + self.type = type + self.durationMinutes = durationMinutes + self.start = start + self.end = end + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case type + case durationMinutes = "duration_minutes" + case start + case end + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(type, forKey: .type) + try container.encode(durationMinutes, forKey: .durationMinutes) + try container.encode(start, forKey: .start) + try container.encode(end, forKey: .end) + } +} + diff --git a/sdk/swift/TimrApi/Models/BreakTimeBase.swift b/sdk/swift/TimrApi/Models/BreakTimeBase.swift new file mode 100644 index 0000000..bc9ac0c --- /dev/null +++ b/sdk/swift/TimrApi/Models/BreakTimeBase.swift @@ -0,0 +1,33 @@ +// +// BreakTimeBase.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Members shared by every kind of break time, including the discriminator. */ +public struct BreakTimeBase: Codable, JSONEncodable, Hashable { + + public var type: BreakTimeType + + public init(type: BreakTimeType) { + self.type = type + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case type + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(type, forKey: .type) + } +} + diff --git a/sdk/swift/TimrApi/Models/BreakTimeManual.swift b/sdk/swift/TimrApi/Models/BreakTimeManual.swift new file mode 100644 index 0000000..04862f0 --- /dev/null +++ b/sdk/swift/TimrApi/Models/BreakTimeManual.swift @@ -0,0 +1,47 @@ +// +// BreakTimeManual.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct BreakTimeManual: Codable, JSONEncodable, Hashable { + + public var type: BreakTimeType + /** Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. */ + public var durationMinutes: Int + /** start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. */ + public var start: Date? + /** start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. */ + public var end: Date? + + public init(type: BreakTimeType, durationMinutes: Int, start: Date? = nil, end: Date? = nil) { + self.type = type + self.durationMinutes = durationMinutes + self.start = start + self.end = end + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case type + case durationMinutes = "duration_minutes" + case start + case end + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(type, forKey: .type) + try container.encode(durationMinutes, forKey: .durationMinutes) + try container.encodeIfPresent(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + } +} + diff --git a/sdk/swift/TimrApi/Models/BreakTimeOngoing.swift b/sdk/swift/TimrApi/Models/BreakTimeOngoing.swift new file mode 100644 index 0000000..0315178 --- /dev/null +++ b/sdk/swift/TimrApi/Models/BreakTimeOngoing.swift @@ -0,0 +1,37 @@ +// +// BreakTimeOngoing.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct BreakTimeOngoing: Codable, JSONEncodable, Hashable { + + public var type: BreakTimeType + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date + + public init(type: BreakTimeType, start: Date) { + self.type = type + self.start = start + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case type + case start + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(type, forKey: .type) + try container.encode(start, forKey: .start) + } +} + diff --git a/sdk/swift/TimrApi/Models/BreakTimeType.swift b/sdk/swift/TimrApi/Models/BreakTimeType.swift new file mode 100644 index 0000000..ad54628 --- /dev/null +++ b/sdk/swift/TimrApi/Models/BreakTimeType.swift @@ -0,0 +1,18 @@ +// +// BreakTimeType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Kind of break. `manual` was entered by the user, `automatic` was deducted by timr, `ongoing` is a break that has started and not yet ended. */ +public enum BreakTimeType: String, Codable, CaseIterable { + case manual = "manual" + case ongoing = "ongoing" + case automatic = "automatic" +} diff --git a/sdk/swift/TimrApi/Models/BreakTimeUpdate.swift b/sdk/swift/TimrApi/Models/BreakTimeUpdate.swift new file mode 100644 index 0000000..8d8f91e --- /dev/null +++ b/sdk/swift/TimrApi/Models/BreakTimeUpdate.swift @@ -0,0 +1,50 @@ +// +// BreakTimeUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum BreakTimeUpdate: Codable, JSONEncodable, Hashable { + case typeBreakTimeManual(BreakTimeManual) + case typeBreakTimeOngoing(BreakTimeOngoing) + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .typeBreakTimeManual(let value): + try container.encode(value) + case .typeBreakTimeOngoing(let value): + try container.encode(value) + } + } + + private enum DiscriminatorCodingKey: String, CodingKey { + case type = "type" + } + + public init(from decoder: Decoder) throws { + let keyedContainer = try decoder.container(keyedBy: DiscriminatorCodingKey.self) + let discriminatorValue = try keyedContainer.decode(String.self, forKey: .type) + + switch discriminatorValue { + case "manual": + self = .typeBreakTimeManual(try BreakTimeManual(from: decoder)) + case "ongoing": + self = .typeBreakTimeOngoing(try BreakTimeOngoing(from: decoder)) + default: + throw DecodingError.dataCorrupted( + DecodingError.Context( + codingPath: decoder.codingPath, + debugDescription: "Unknown discriminator value '\(discriminatorValue)' for BreakTimeUpdate" + ) + ) + } + } +} + diff --git a/sdk/swift/TimrApi/Models/BudgetPlanningType.swift b/sdk/swift/TimrApi/Models/BudgetPlanningType.swift new file mode 100644 index 0000000..ab5ed8a --- /dev/null +++ b/sdk/swift/TimrApi/Models/BudgetPlanningType.swift @@ -0,0 +1,19 @@ +// +// BudgetPlanningType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set for the remaining two types all budget properties are supported */ +public enum BudgetPlanningType: String, Codable, CaseIterable { + case _none = "none" + case taskHourlyRate = "task_hourly_rate" + case userHourlyRate = "user_hourly_rate" + case fixedPrice = "fixed_price" +} diff --git a/sdk/swift/TimrApi/Models/BudgetPlanningTypeRequest.swift b/sdk/swift/TimrApi/Models/BudgetPlanningTypeRequest.swift new file mode 100644 index 0000000..22a7756 --- /dev/null +++ b/sdk/swift/TimrApi/Models/BudgetPlanningTypeRequest.swift @@ -0,0 +1,20 @@ +// +// BudgetPlanningTypeRequest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** corresponding to the chosen planning type some properties cannot be set: * none: no further budget properties can be set * user_hourly_rate: budget_hourly_rate cannot be set * inherited: budget settings are inherited from the parent task for the remaining two types all budget properties are supported */ +public enum BudgetPlanningTypeRequest: String, Codable, CaseIterable { + case _none = "none" + case taskHourlyRate = "task_hourly_rate" + case userHourlyRate = "user_hourly_rate" + case fixedPrice = "fixed_price" + case inherited = "inherited" +} diff --git a/sdk/swift/TimrApi/Models/Car.swift b/sdk/swift/TimrApi/Models/Car.swift new file mode 100644 index 0000000..dbe35c8 --- /dev/null +++ b/sdk/swift/TimrApi/Models/Car.swift @@ -0,0 +1,58 @@ +// +// Car.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** A vehicle identified by `name` and license `plate`. `usable` says whether it can currently be selected. */ +public struct Car: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + public var plate: String + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var usable: Bool + public var metadata: [String: AnyCodable]? + + public init(id: String, name: String, plate: String, externalId: String?, usable: Bool, metadata: [String: AnyCodable]? = nil) { + self.id = id + self.name = name + self.plate = plate + self.externalId = externalId + self.usable = usable + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case plate + case externalId = "external_id" + case usable + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(plate, forKey: .plate) + try container.encode(externalId, forKey: .externalId) + try container.encode(usable, forKey: .usable) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension Car: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/CarCreate.swift b/sdk/swift/TimrApi/Models/CarCreate.swift new file mode 100644 index 0000000..345972f --- /dev/null +++ b/sdk/swift/TimrApi/Models/CarCreate.swift @@ -0,0 +1,51 @@ +// +// CarCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CarCreate: Codable, JSONEncodable, Hashable { + + public static let nameRule = StringRule(minLength: 1, maxLength: 191, pattern: nil) + public static let plateRule = StringRule(minLength: 1, maxLength: 191, pattern: nil) + public var name: String + public var plate: String + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var usable: Bool? + public var metadata: [String: AnyCodable]? + + public init(name: String, plate: String, externalId: String? = nil, usable: Bool? = nil, metadata: [String: AnyCodable]? = nil) { + self.name = name + self.plate = plate + self.externalId = externalId + self.usable = usable + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case plate + case externalId = "external_id" + case usable + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encode(plate, forKey: .plate) + try container.encodeIfPresent(externalId, forKey: .externalId) + try container.encodeIfPresent(usable, forKey: .usable) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + diff --git a/sdk/swift/TimrApi/Models/CarPartial.swift b/sdk/swift/TimrApi/Models/CarPartial.swift new file mode 100644 index 0000000..184e5b1 --- /dev/null +++ b/sdk/swift/TimrApi/Models/CarPartial.swift @@ -0,0 +1,49 @@ +// +// CarPartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CarPartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + public var plate: String + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + + public init(id: String, name: String, plate: String, externalId: String?) { + self.id = id + self.name = name + self.plate = plate + self.externalId = externalId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case plate + case externalId = "external_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(plate, forKey: .plate) + try container.encode(externalId, forKey: .externalId) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension CarPartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/CarUpdate.swift b/sdk/swift/TimrApi/Models/CarUpdate.swift new file mode 100644 index 0000000..95b956d --- /dev/null +++ b/sdk/swift/TimrApi/Models/CarUpdate.swift @@ -0,0 +1,51 @@ +// +// CarUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CarUpdate: Codable, JSONEncodable, Hashable { + + public static let nameRule = StringRule(minLength: 1, maxLength: 191, pattern: nil) + public static let plateRule = StringRule(minLength: 1, maxLength: 191, pattern: nil) + public var name: String? + public var plate: String? + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var usable: Bool? + public var metadata: [String: AnyCodable]? + + public init(name: String? = nil, plate: String? = nil, externalId: String? = nil, usable: Bool? = nil, metadata: [String: AnyCodable]? = nil) { + self.name = name + self.plate = plate + self.externalId = externalId + self.usable = usable + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case plate + case externalId = "external_id" + case usable + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(plate, forKey: .plate) + try container.encodeIfPresent(externalId, forKey: .externalId) + try container.encodeIfPresent(usable, forKey: .usable) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + diff --git a/sdk/swift/TimrApi/Models/CarsPage.swift b/sdk/swift/TimrApi/Models/CarsPage.swift new file mode 100644 index 0000000..ee7cb9a --- /dev/null +++ b/sdk/swift/TimrApi/Models/CarsPage.swift @@ -0,0 +1,37 @@ +// +// CarsPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CarsPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [Car] + + public init(nextPageToken: String?, data: [Car]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/CarsSortColumn.swift b/sdk/swift/TimrApi/Models/CarsSortColumn.swift new file mode 100644 index 0000000..1f139f8 --- /dev/null +++ b/sdk/swift/TimrApi/Models/CarsSortColumn.swift @@ -0,0 +1,16 @@ +// +// CarsSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Cars. */ +public enum CarsSortColumn: String, Codable, CaseIterable { + case name = "name" +} diff --git a/sdk/swift/TimrApi/Models/DailyWorkSchedule.swift b/sdk/swift/TimrApi/Models/DailyWorkSchedule.swift new file mode 100644 index 0000000..ac6fda4 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DailyWorkSchedule.swift @@ -0,0 +1,38 @@ +// +// DailyWorkSchedule.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DailyWorkSchedule: Codable, JSONEncodable, Hashable { + + /** value in minutes */ + public var targetDurationMinutes: Int64 + /** this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set */ + public var normalWorkingTimes: [NormalWorkingTimes]? + + public init(targetDurationMinutes: Int64, normalWorkingTimes: [NormalWorkingTimes]? = nil) { + self.targetDurationMinutes = targetDurationMinutes + self.normalWorkingTimes = normalWorkingTimes + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case targetDurationMinutes = "target_duration_minutes" + case normalWorkingTimes = "normal_working_times" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(targetDurationMinutes, forKey: .targetDurationMinutes) + try container.encodeIfPresent(normalWorkingTimes, forKey: .normalWorkingTimes) + } +} + diff --git a/sdk/swift/TimrApi/Models/DeletedEntryPage.swift b/sdk/swift/TimrApi/Models/DeletedEntryPage.swift new file mode 100644 index 0000000..b2863ee --- /dev/null +++ b/sdk/swift/TimrApi/Models/DeletedEntryPage.swift @@ -0,0 +1,37 @@ +// +// DeletedEntryPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DeletedEntryPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [DeletedEntryPartial] + + public init(nextPageToken: String?, data: [DeletedEntryPartial]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/DeletedEntryPartial.swift b/sdk/swift/TimrApi/Models/DeletedEntryPartial.swift new file mode 100644 index 0000000..0cd3157 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DeletedEntryPartial.swift @@ -0,0 +1,46 @@ +// +// DeletedEntryPartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DeletedEntryPartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + /** Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + public var lastModified: Date + /** Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + public var lastModifiedBy: UserPartial? + + public init(id: String, lastModified: Date, lastModifiedBy: UserPartial?) { + self.id = id + self.lastModified = lastModified + self.lastModifiedBy = lastModifiedBy + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case lastModified = "last_modified" + case lastModifiedBy = "last_modified_by" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(lastModified, forKey: .lastModified) + try container.encode(lastModifiedBy, forKey: .lastModifiedBy) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension DeletedEntryPartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/DeletedEntrySortColumn.swift b/sdk/swift/TimrApi/Models/DeletedEntrySortColumn.swift new file mode 100644 index 0000000..f770654 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DeletedEntrySortColumn.swift @@ -0,0 +1,16 @@ +// +// DeletedEntrySortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for deleted entries. */ +public enum DeletedEntrySortColumn: String, Codable, CaseIterable { + case lastModified = "last_modified" +} diff --git a/sdk/swift/TimrApi/Models/DeletedEntryWithMetadata.swift b/sdk/swift/TimrApi/Models/DeletedEntryWithMetadata.swift new file mode 100644 index 0000000..0dabcb8 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DeletedEntryWithMetadata.swift @@ -0,0 +1,50 @@ +// +// DeletedEntryWithMetadata.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DeletedEntryWithMetadata: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + /** Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + public var lastModified: Date + /** Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + public var lastModifiedBy: UserPartial? + public var metadata: [String: AnyCodable]? + + public init(id: String, lastModified: Date, lastModifiedBy: UserPartial?, metadata: [String: AnyCodable]? = nil) { + self.id = id + self.lastModified = lastModified + self.lastModifiedBy = lastModifiedBy + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case lastModified = "last_modified" + case lastModifiedBy = "last_modified_by" + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(lastModified, forKey: .lastModified) + try container.encode(lastModifiedBy, forKey: .lastModifiedBy) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension DeletedEntryWithMetadata: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/DeletedEntryWithMetadataPage.swift b/sdk/swift/TimrApi/Models/DeletedEntryWithMetadataPage.swift new file mode 100644 index 0000000..e4388c5 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DeletedEntryWithMetadataPage.swift @@ -0,0 +1,37 @@ +// +// DeletedEntryWithMetadataPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DeletedEntryWithMetadataPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [DeletedEntryWithMetadata] + + public init(nextPageToken: String?, data: [DeletedEntryWithMetadata]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/DriveLog.swift b/sdk/swift/TimrApi/Models/DriveLog.swift new file mode 100644 index 0000000..18fbac0 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLog.swift @@ -0,0 +1,138 @@ +// +// DriveLog.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** One trip in a `car`: `start` and `end`, `start_mileage` and `end_mileage` with the resulting `distance`, the `purpose`, the places `visited`, and its `drive_log_category`. May include a recorded GPS `route`. */ +public struct DriveLog: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var duration: Duration? + public var changed: Bool + public var startMileage: Int64 + public var endMileage: Int64? + /** Driven distance in kilometers */ + public var distance: Int64? + public var route: String? + public var purpose: String? + public var visited: String? + public var user: UserPartial + public var car: CarPartial + public var driveLogCategory: DriveLogCategoryPartial + public var startVenue: VenuePartial? + public var endVenue: VenuePartial? + public var hasTrack: Bool + public var startLocation: Location? + public var endLocation: Location? + public var startPlatform: Platform? + public var endPlatform: Platform? + /** Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + public var lastModified: Date + /** Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + public var lastModifiedBy: UserPartial? + public var status: DriveLogStatus + public var metadata: [String: AnyCodable]? + + public init(id: String, start: Date, end: Date?, duration: Duration?, changed: Bool, startMileage: Int64, endMileage: Int64?, distance: Int64?, route: String?, purpose: String?, visited: String?, user: UserPartial, car: CarPartial, driveLogCategory: DriveLogCategoryPartial, startVenue: VenuePartial?, endVenue: VenuePartial?, hasTrack: Bool, startLocation: Location?, endLocation: Location?, startPlatform: Platform?, endPlatform: Platform?, lastModified: Date, lastModifiedBy: UserPartial?, status: DriveLogStatus, metadata: [String: AnyCodable]? = nil) { + self.id = id + self.start = start + self.end = end + self.duration = duration + self.changed = changed + self.startMileage = startMileage + self.endMileage = endMileage + self.distance = distance + self.route = route + self.purpose = purpose + self.visited = visited + self.user = user + self.car = car + self.driveLogCategory = driveLogCategory + self.startVenue = startVenue + self.endVenue = endVenue + self.hasTrack = hasTrack + self.startLocation = startLocation + self.endLocation = endLocation + self.startPlatform = startPlatform + self.endPlatform = endPlatform + self.lastModified = lastModified + self.lastModifiedBy = lastModifiedBy + self.status = status + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case start + case end + case duration + case changed + case startMileage = "start_mileage" + case endMileage = "end_mileage" + case distance + case route + case purpose + case visited + case user + case car + case driveLogCategory = "drive_log_category" + case startVenue = "start_venue" + case endVenue = "end_venue" + case hasTrack = "has_track" + case startLocation = "start_location" + case endLocation = "end_location" + case startPlatform = "start_platform" + case endPlatform = "end_platform" + case lastModified = "last_modified" + case lastModifiedBy = "last_modified_by" + case status + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(start, forKey: .start) + try container.encode(end, forKey: .end) + try container.encode(duration, forKey: .duration) + try container.encode(changed, forKey: .changed) + try container.encode(startMileage, forKey: .startMileage) + try container.encode(endMileage, forKey: .endMileage) + try container.encode(distance, forKey: .distance) + try container.encode(route, forKey: .route) + try container.encode(purpose, forKey: .purpose) + try container.encode(visited, forKey: .visited) + try container.encode(user, forKey: .user) + try container.encode(car, forKey: .car) + try container.encode(driveLogCategory, forKey: .driveLogCategory) + try container.encode(startVenue, forKey: .startVenue) + try container.encode(endVenue, forKey: .endVenue) + try container.encode(hasTrack, forKey: .hasTrack) + try container.encode(startLocation, forKey: .startLocation) + try container.encode(endLocation, forKey: .endLocation) + try container.encode(startPlatform, forKey: .startPlatform) + try container.encode(endPlatform, forKey: .endPlatform) + try container.encode(lastModified, forKey: .lastModified) + try container.encode(lastModifiedBy, forKey: .lastModifiedBy) + try container.encode(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension DriveLog: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/DriveLogCategoriesPage.swift b/sdk/swift/TimrApi/Models/DriveLogCategoriesPage.swift new file mode 100644 index 0000000..21ebe00 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogCategoriesPage.swift @@ -0,0 +1,37 @@ +// +// DriveLogCategoriesPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DriveLogCategoriesPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [DriveLogCategory] + + public init(nextPageToken: String?, data: [DriveLogCategory]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/DriveLogCategoriesSortColumn.swift b/sdk/swift/TimrApi/Models/DriveLogCategoriesSortColumn.swift new file mode 100644 index 0000000..20070bd --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogCategoriesSortColumn.swift @@ -0,0 +1,16 @@ +// +// DriveLogCategoriesSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Drive Log Categories. */ +public enum DriveLogCategoriesSortColumn: String, Codable, CaseIterable { + case name = "name" +} diff --git a/sdk/swift/TimrApi/Models/DriveLogCategory.swift b/sdk/swift/TimrApi/Models/DriveLogCategory.swift new file mode 100644 index 0000000..f896935 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogCategory.swift @@ -0,0 +1,59 @@ +// +// DriveLogCategory.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** A drive log category with a `name` and a display `color`; `business` marks it as business travel. */ +public struct DriveLogCategory: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + public var business: Bool + public var color: String + /** Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + public var lastModified: Date + /** Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + public var lastModifiedBy: UserPartial? + + public init(id: String, name: String, business: Bool, color: String, lastModified: Date, lastModifiedBy: UserPartial?) { + self.id = id + self.name = name + self.business = business + self.color = color + self.lastModified = lastModified + self.lastModifiedBy = lastModifiedBy + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case business + case color + case lastModified = "last_modified" + case lastModifiedBy = "last_modified_by" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(business, forKey: .business) + try container.encode(color, forKey: .color) + try container.encode(lastModified, forKey: .lastModified) + try container.encode(lastModifiedBy, forKey: .lastModifiedBy) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension DriveLogCategory: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/DriveLogCategoryPartial.swift b/sdk/swift/TimrApi/Models/DriveLogCategoryPartial.swift new file mode 100644 index 0000000..984f532 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogCategoryPartial.swift @@ -0,0 +1,48 @@ +// +// DriveLogCategoryPartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DriveLogCategoryPartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + public var business: Bool + public var color: String + + public init(id: String, name: String, business: Bool, color: String) { + self.id = id + self.name = name + self.business = business + self.color = color + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case business + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(business, forKey: .business) + try container.encode(color, forKey: .color) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension DriveLogCategoryPartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/DriveLogCreate.swift b/sdk/swift/TimrApi/Models/DriveLogCreate.swift new file mode 100644 index 0000000..83e01b2 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogCreate.swift @@ -0,0 +1,90 @@ +// +// DriveLogCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DriveLogCreate: Codable, JSONEncodable, Hashable { + + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var changed: Bool + public var startMileage: Int64 + public var endMileage: Int64? + public var route: String? + public var purpose: String? + public var visited: String? + public var driveLogCategoryId: String + public var status: DriveLogStatus + public var metadata: [String: AnyCodable]? + public var userId: String + public var carId: String + public var startLocation: LocationCreate? + public var endLocation: LocationCreate? + + public init(start: Date, end: Date? = nil, changed: Bool, startMileage: Int64, endMileage: Int64? = nil, route: String? = nil, purpose: String? = nil, visited: String? = nil, driveLogCategoryId: String, status: DriveLogStatus, metadata: [String: AnyCodable]? = nil, userId: String, carId: String, startLocation: LocationCreate? = nil, endLocation: LocationCreate? = nil) { + self.start = start + self.end = end + self.changed = changed + self.startMileage = startMileage + self.endMileage = endMileage + self.route = route + self.purpose = purpose + self.visited = visited + self.driveLogCategoryId = driveLogCategoryId + self.status = status + self.metadata = metadata + self.userId = userId + self.carId = carId + self.startLocation = startLocation + self.endLocation = endLocation + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + case changed + case startMileage = "start_mileage" + case endMileage = "end_mileage" + case route + case purpose + case visited + case driveLogCategoryId = "drive_log_category_id" + case status + case metadata + case userId = "user_id" + case carId = "car_id" + case startLocation = "start_location" + case endLocation = "end_location" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + try container.encode(changed, forKey: .changed) + try container.encode(startMileage, forKey: .startMileage) + try container.encodeIfPresent(endMileage, forKey: .endMileage) + try container.encodeIfPresent(route, forKey: .route) + try container.encodeIfPresent(purpose, forKey: .purpose) + try container.encodeIfPresent(visited, forKey: .visited) + try container.encode(driveLogCategoryId, forKey: .driveLogCategoryId) + try container.encode(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encode(userId, forKey: .userId) + try container.encode(carId, forKey: .carId) + try container.encodeIfPresent(startLocation, forKey: .startLocation) + try container.encodeIfPresent(endLocation, forKey: .endLocation) + } +} + diff --git a/sdk/swift/TimrApi/Models/DriveLogStatus.swift b/sdk/swift/TimrApi/Models/DriveLogStatus.swift new file mode 100644 index 0000000..f7b0a9d --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogStatus.swift @@ -0,0 +1,22 @@ +// +// DriveLogStatus.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Processing state of a Drive Log. `running` means the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. */ +public enum DriveLogStatus: String, Codable, CaseIterable { + case changeable = "changeable" + case locked = "locked" + case approved = "approved" + case cleared = "cleared" + case closed = "closed" + case archived = "archived" + case running = "running" +} diff --git a/sdk/swift/TimrApi/Models/DriveLogUpdate.swift b/sdk/swift/TimrApi/Models/DriveLogUpdate.swift new file mode 100644 index 0000000..117b5c3 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogUpdate.swift @@ -0,0 +1,82 @@ +// +// DriveLogUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DriveLogUpdate: Codable, JSONEncodable, Hashable { + + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date? + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var changed: Bool? + public var startMileage: Int64? + public var endMileage: Int64? + public var route: String? + public var purpose: String? + public var visited: String? + public var driveLogCategoryId: String? + public var status: DriveLogStatus? + public var metadata: [String: AnyCodable]? + public var startLocation: LocationUpdate? + public var endLocation: LocationUpdate? + + public init(start: Date? = nil, end: Date? = nil, changed: Bool? = nil, startMileage: Int64? = nil, endMileage: Int64? = nil, route: String? = nil, purpose: String? = nil, visited: String? = nil, driveLogCategoryId: String? = nil, status: DriveLogStatus? = nil, metadata: [String: AnyCodable]? = nil, startLocation: LocationUpdate? = nil, endLocation: LocationUpdate? = nil) { + self.start = start + self.end = end + self.changed = changed + self.startMileage = startMileage + self.endMileage = endMileage + self.route = route + self.purpose = purpose + self.visited = visited + self.driveLogCategoryId = driveLogCategoryId + self.status = status + self.metadata = metadata + self.startLocation = startLocation + self.endLocation = endLocation + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + case changed + case startMileage = "start_mileage" + case endMileage = "end_mileage" + case route + case purpose + case visited + case driveLogCategoryId = "drive_log_category_id" + case status + case metadata + case startLocation = "start_location" + case endLocation = "end_location" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + try container.encodeIfPresent(changed, forKey: .changed) + try container.encodeIfPresent(startMileage, forKey: .startMileage) + try container.encodeIfPresent(endMileage, forKey: .endMileage) + try container.encodeIfPresent(route, forKey: .route) + try container.encodeIfPresent(purpose, forKey: .purpose) + try container.encodeIfPresent(visited, forKey: .visited) + try container.encodeIfPresent(driveLogCategoryId, forKey: .driveLogCategoryId) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(startLocation, forKey: .startLocation) + try container.encodeIfPresent(endLocation, forKey: .endLocation) + } +} + diff --git a/sdk/swift/TimrApi/Models/DriveLogUpsert.swift b/sdk/swift/TimrApi/Models/DriveLogUpsert.swift new file mode 100644 index 0000000..d27de94 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogUpsert.swift @@ -0,0 +1,74 @@ +// +// DriveLogUpsert.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DriveLogUpsert: Codable, JSONEncodable, Hashable { + + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date? + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var changed: Bool? + public var startMileage: Int64? + public var endMileage: Int64? + public var route: String? + public var purpose: String? + public var visited: String? + public var driveLogCategoryId: String? + public var status: DriveLogStatus? + public var metadata: [String: AnyCodable]? + + public init(start: Date? = nil, end: Date? = nil, changed: Bool? = nil, startMileage: Int64? = nil, endMileage: Int64? = nil, route: String? = nil, purpose: String? = nil, visited: String? = nil, driveLogCategoryId: String? = nil, status: DriveLogStatus? = nil, metadata: [String: AnyCodable]? = nil) { + self.start = start + self.end = end + self.changed = changed + self.startMileage = startMileage + self.endMileage = endMileage + self.route = route + self.purpose = purpose + self.visited = visited + self.driveLogCategoryId = driveLogCategoryId + self.status = status + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + case changed + case startMileage = "start_mileage" + case endMileage = "end_mileage" + case route + case purpose + case visited + case driveLogCategoryId = "drive_log_category_id" + case status + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + try container.encodeIfPresent(changed, forKey: .changed) + try container.encodeIfPresent(startMileage, forKey: .startMileage) + try container.encodeIfPresent(endMileage, forKey: .endMileage) + try container.encodeIfPresent(route, forKey: .route) + try container.encodeIfPresent(purpose, forKey: .purpose) + try container.encodeIfPresent(visited, forKey: .visited) + try container.encodeIfPresent(driveLogCategoryId, forKey: .driveLogCategoryId) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + diff --git a/sdk/swift/TimrApi/Models/DriveLogsPage.swift b/sdk/swift/TimrApi/Models/DriveLogsPage.swift new file mode 100644 index 0000000..4376832 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogsPage.swift @@ -0,0 +1,37 @@ +// +// DriveLogsPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DriveLogsPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [DriveLog] + + public init(nextPageToken: String?, data: [DriveLog]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/DriveLogsSortColumn.swift b/sdk/swift/TimrApi/Models/DriveLogsSortColumn.swift new file mode 100644 index 0000000..9b58fe4 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DriveLogsSortColumn.swift @@ -0,0 +1,17 @@ +// +// DriveLogsSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Drive Logs. */ +public enum DriveLogsSortColumn: String, Codable, CaseIterable { + case start = "start" + case lastModified = "last_modified" +} diff --git a/sdk/swift/TimrApi/Models/Duration.swift b/sdk/swift/TimrApi/Models/Duration.swift new file mode 100644 index 0000000..eb322a6 --- /dev/null +++ b/sdk/swift/TimrApi/Models/Duration.swift @@ -0,0 +1,42 @@ +// +// Duration.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Duration: Codable, JSONEncodable, Hashable { + + public var type: DurationType + /** Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User */ + public var minutes: Int64 + /** Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User */ + public var minutesRounded: Int64 + + public init(type: DurationType, minutes: Int64, minutesRounded: Int64) { + self.type = type + self.minutes = minutes + self.minutesRounded = minutesRounded + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case type + case minutes + case minutesRounded = "minutes_rounded" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(type, forKey: .type) + try container.encode(minutes, forKey: .minutes) + try container.encode(minutesRounded, forKey: .minutesRounded) + } +} + diff --git a/sdk/swift/TimrApi/Models/DurationType.swift b/sdk/swift/TimrApi/Models/DurationType.swift new file mode 100644 index 0000000..805a0f8 --- /dev/null +++ b/sdk/swift/TimrApi/Models/DurationType.swift @@ -0,0 +1,18 @@ +// +// DurationType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** How the duration of a single recording is expressed. Not to be confused with `DurationUnit`, which states the unit a Working Time Type is recorded in. */ +public enum DurationType: String, Codable, CaseIterable { + case minutes = "minutes" + case fullDay = "full_day" + case halfDay = "half_day" +} diff --git a/sdk/swift/TimrApi/Models/DurationUnit.swift b/sdk/swift/TimrApi/Models/DurationUnit.swift new file mode 100644 index 0000000..163ab4b --- /dev/null +++ b/sdk/swift/TimrApi/Models/DurationUnit.swift @@ -0,0 +1,18 @@ +// +// DurationUnit.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Unit a Working Time Type is recorded in. Not to be confused with `DurationType`, which states how an individual recording's duration is expressed. */ +public enum DurationUnit: String, Codable, CaseIterable { + case minutes = "minutes" + case halfDays = "half_days" + case days = "days" +} diff --git a/sdk/swift/TimrApi/Models/ErrorEntry.swift b/sdk/swift/TimrApi/Models/ErrorEntry.swift new file mode 100644 index 0000000..ab667c7 --- /dev/null +++ b/sdk/swift/TimrApi/Models/ErrorEntry.swift @@ -0,0 +1,41 @@ +// +// ErrorEntry.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Field-level or sub-error entry, shaped like a sub-ProblemDetail. The `type` URI identifies the specific constraint or sub-error category (e.g. `validation/not-null` for a Bean Validation `@NotNull`, `validation/paused-working-time` for a TIMR custom validator code, `validation/type-mismatch` for a value that does not fit its target type, `validation/unknown-property` for a property the resource does not declare, `reference-not-found/user` for a `MappingException`). `field` is the JSONPath of the offending property in the request body, rooted at `$` — array elements included. An error about a query parameter names it plainly instead, without the `$.` prefix. */ +public struct ErrorEntry: Codable, JSONEncodable, Hashable { + + public var type: String + public var field: String? + public var detail: String + + public init(type: String, field: String? = nil, detail: String) { + self.type = type + self.field = field + self.detail = detail + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case type + case field + case detail + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(type, forKey: .type) + try container.encodeIfPresent(field, forKey: .field) + try container.encode(detail, forKey: .detail) + } +} + diff --git a/sdk/swift/TimrApi/Models/FlexTimeIndicator.swift b/sdk/swift/TimrApi/Models/FlexTimeIndicator.swift new file mode 100644 index 0000000..b781416 --- /dev/null +++ b/sdk/swift/TimrApi/Models/FlexTimeIndicator.swift @@ -0,0 +1,18 @@ +// +// FlexTimeIndicator.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Traffic-light rating of the flex time balance. The thresholds are an account setting and are not part of this contract. */ +public enum FlexTimeIndicator: String, Codable, CaseIterable { + case green = "green" + case yellow = "yellow" + case red = "red" +} diff --git a/sdk/swift/TimrApi/Models/Holiday.swift b/sdk/swift/TimrApi/Models/Holiday.swift new file mode 100644 index 0000000..141b8c4 --- /dev/null +++ b/sdk/swift/TimrApi/Models/Holiday.swift @@ -0,0 +1,41 @@ +// +// Holiday.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Holiday: Codable, JSONEncodable, Hashable { + + /** RFC 3339 date (ISO-8601) */ + public var date: Date + public var description: String + public var halfDay: Bool + + public init(date: Date, description: String, halfDay: Bool) { + self.date = date + self.description = description + self.halfDay = halfDay + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case date + case description + case halfDay = "half_day" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(date, forKey: .date) + try container.encode(description, forKey: .description) + try container.encode(halfDay, forKey: .halfDay) + } +} + diff --git a/sdk/swift/TimrApi/Models/HolidayCalendarPartial.swift b/sdk/swift/TimrApi/Models/HolidayCalendarPartial.swift new file mode 100644 index 0000000..043ca36 --- /dev/null +++ b/sdk/swift/TimrApi/Models/HolidayCalendarPartial.swift @@ -0,0 +1,41 @@ +// +// HolidayCalendarPartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** A holiday calendar. Its holidays are either generated automatically or maintained manually. */ +public struct HolidayCalendarPartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var description: String + + public init(id: String, description: String) { + self.id = id + self.description = description + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case description + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(description, forKey: .description) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension HolidayCalendarPartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/HolidayCalendarsPage.swift b/sdk/swift/TimrApi/Models/HolidayCalendarsPage.swift new file mode 100644 index 0000000..e2a70b4 --- /dev/null +++ b/sdk/swift/TimrApi/Models/HolidayCalendarsPage.swift @@ -0,0 +1,37 @@ +// +// HolidayCalendarsPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct HolidayCalendarsPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [HolidayCalendarPartial] + + public init(nextPageToken: String?, data: [HolidayCalendarPartial]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/HolidayCalendarsSortColumn.swift b/sdk/swift/TimrApi/Models/HolidayCalendarsSortColumn.swift new file mode 100644 index 0000000..56aaa4c --- /dev/null +++ b/sdk/swift/TimrApi/Models/HolidayCalendarsSortColumn.swift @@ -0,0 +1,16 @@ +// +// HolidayCalendarsSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Holiday Calendars. */ +public enum HolidayCalendarsSortColumn: String, Codable, CaseIterable { + case description = "description" +} diff --git a/sdk/swift/TimrApi/Models/HolidaysPage.swift b/sdk/swift/TimrApi/Models/HolidaysPage.swift new file mode 100644 index 0000000..1738b06 --- /dev/null +++ b/sdk/swift/TimrApi/Models/HolidaysPage.swift @@ -0,0 +1,37 @@ +// +// HolidaysPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct HolidaysPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [Holiday] + + public init(nextPageToken: String?, data: [Holiday]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/HolidaysSortColumn.swift b/sdk/swift/TimrApi/Models/HolidaysSortColumn.swift new file mode 100644 index 0000000..8448eae --- /dev/null +++ b/sdk/swift/TimrApi/Models/HolidaysSortColumn.swift @@ -0,0 +1,16 @@ +// +// HolidaysSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Holidays. */ +public enum HolidaysSortColumn: String, Codable, CaseIterable { + case date = "date" +} diff --git a/sdk/swift/TimrApi/Models/Location.swift b/sdk/swift/TimrApi/Models/Location.swift new file mode 100644 index 0000000..1f1df21 --- /dev/null +++ b/sdk/swift/TimrApi/Models/Location.swift @@ -0,0 +1,52 @@ +// +// Location.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Location: Codable, JSONEncodable, Hashable { + + /** Latitude in decimal degrees. */ + public var lat: Float? + /** Longitude in decimal degrees. */ + public var lon: Float? + /** RFC 3339 date-time (ISO-8601) */ + public var timestamp: Date? + public var formattedAddress: String? + /** Horizontal GPS accuracy in meters. */ + public var accuracy: Float? + + public init(lat: Float?, lon: Float?, timestamp: Date? = nil, formattedAddress: String? = nil, accuracy: Float?) { + self.lat = lat + self.lon = lon + self.timestamp = timestamp + self.formattedAddress = formattedAddress + self.accuracy = accuracy + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case lat + case lon + case timestamp + case formattedAddress = "formatted_address" + case accuracy + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(lat, forKey: .lat) + try container.encode(lon, forKey: .lon) + try container.encodeIfPresent(timestamp, forKey: .timestamp) + try container.encodeIfPresent(formattedAddress, forKey: .formattedAddress) + try container.encode(accuracy, forKey: .accuracy) + } +} + diff --git a/sdk/swift/TimrApi/Models/LocationCreate.swift b/sdk/swift/TimrApi/Models/LocationCreate.swift new file mode 100644 index 0000000..961298a --- /dev/null +++ b/sdk/swift/TimrApi/Models/LocationCreate.swift @@ -0,0 +1,52 @@ +// +// LocationCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct LocationCreate: Codable, JSONEncodable, Hashable { + + /** Latitude in decimal degrees. */ + public var lat: Float + /** Longitude in decimal degrees. */ + public var lon: Float + /** RFC 3339 date-time (ISO-8601) */ + public var timestamp: Date? + public var formattedAddress: String? + /** Horizontal GPS accuracy in meters. */ + public var accuracy: Float? + + public init(lat: Float, lon: Float, timestamp: Date? = nil, formattedAddress: String? = nil, accuracy: Float? = nil) { + self.lat = lat + self.lon = lon + self.timestamp = timestamp + self.formattedAddress = formattedAddress + self.accuracy = accuracy + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case lat + case lon + case timestamp + case formattedAddress = "formatted_address" + case accuracy + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(lat, forKey: .lat) + try container.encode(lon, forKey: .lon) + try container.encodeIfPresent(timestamp, forKey: .timestamp) + try container.encodeIfPresent(formattedAddress, forKey: .formattedAddress) + try container.encodeIfPresent(accuracy, forKey: .accuracy) + } +} + diff --git a/sdk/swift/TimrApi/Models/LocationUpdate.swift b/sdk/swift/TimrApi/Models/LocationUpdate.swift new file mode 100644 index 0000000..34281ec --- /dev/null +++ b/sdk/swift/TimrApi/Models/LocationUpdate.swift @@ -0,0 +1,52 @@ +// +// LocationUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct LocationUpdate: Codable, JSONEncodable, Hashable { + + /** Latitude in decimal degrees. */ + public var lat: Float? + /** Longitude in decimal degrees. */ + public var lon: Float? + /** RFC 3339 date-time (ISO-8601) */ + public var timestamp: Date? + public var formattedAddress: String? + /** Horizontal GPS accuracy in meters. */ + public var accuracy: Float? + + public init(lat: Float? = nil, lon: Float? = nil, timestamp: Date? = nil, formattedAddress: String? = nil, accuracy: Float? = nil) { + self.lat = lat + self.lon = lon + self.timestamp = timestamp + self.formattedAddress = formattedAddress + self.accuracy = accuracy + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case lat + case lon + case timestamp + case formattedAddress = "formatted_address" + case accuracy + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(lat, forKey: .lat) + try container.encodeIfPresent(lon, forKey: .lon) + try container.encodeIfPresent(timestamp, forKey: .timestamp) + try container.encodeIfPresent(formattedAddress, forKey: .formattedAddress) + try container.encodeIfPresent(accuracy, forKey: .accuracy) + } +} + diff --git a/sdk/swift/TimrApi/Models/ModelError.swift b/sdk/swift/TimrApi/Models/ModelError.swift new file mode 100644 index 0000000..300b240 --- /dev/null +++ b/sdk/swift/TimrApi/Models/ModelError.swift @@ -0,0 +1,61 @@ +// +// ModelError.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** TIMR error response body, extending the Problem Details base with `timestamp`, `trace_id` and per-field `errors[]` for validation, binding, constraint, request-body deserialization, and reference-not-found errors. The semantic identifier is encoded in the `type` URI (e.g. `https://errors.timr.com/conflict/resource-outdated`). Slugs in the `type` URI are lowercase kebab-case: a top-level category (`validation`, `reference-not-found`, `conflict`, `forbidden`, `internal`) optionally followed by a specific sub-slug (`conflict/resource-outdated`, `validation/end-time-required`, `reference-not-found/user`). */ +public struct ModelError: Codable, JSONEncodable, Hashable { + + public var type: String + public var title: String + public var status: Int + public var detail: String? + public var instance: String? + public var timestamp: Date + public var traceId: String? + public var errors: [ErrorEntry]? + + public init(type: String, title: String, status: Int, detail: String? = nil, instance: String? = nil, timestamp: Date, traceId: String? = nil, errors: [ErrorEntry]? = nil) { + self.type = type + self.title = title + self.status = status + self.detail = detail + self.instance = instance + self.timestamp = timestamp + self.traceId = traceId + self.errors = errors + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case type + case title + case status + case detail + case instance + case timestamp + case traceId = "trace_id" + case errors + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(type, forKey: .type) + try container.encode(title, forKey: .title) + try container.encode(status, forKey: .status) + try container.encodeIfPresent(detail, forKey: .detail) + try container.encodeIfPresent(instance, forKey: .instance) + try container.encode(timestamp, forKey: .timestamp) + try container.encodeIfPresent(traceId, forKey: .traceId) + try container.encodeIfPresent(errors, forKey: .errors) + } +} + diff --git a/sdk/swift/TimrApi/Models/NormalWorkingTimes.swift b/sdk/swift/TimrApi/Models/NormalWorkingTimes.swift new file mode 100644 index 0000000..fcdcc0f --- /dev/null +++ b/sdk/swift/TimrApi/Models/NormalWorkingTimes.swift @@ -0,0 +1,36 @@ +// +// NormalWorkingTimes.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct NormalWorkingTimes: Codable, JSONEncodable, Hashable { + + public var start: String? + public var end: String? + + public init(start: String? = nil, end: String? = nil) { + self.start = start + self.end = end + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + } +} + diff --git a/sdk/swift/TimrApi/Models/OvertimeSurchargeAccount.swift b/sdk/swift/TimrApi/Models/OvertimeSurchargeAccount.swift new file mode 100644 index 0000000..c84405b --- /dev/null +++ b/sdk/swift/TimrApi/Models/OvertimeSurchargeAccount.swift @@ -0,0 +1,40 @@ +// +// OvertimeSurchargeAccount.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct OvertimeSurchargeAccount: Codable, JSONEncodable, Hashable { + + public var balanceLastPeriodMinutes: Int? + public var newMinutes: Int? + public var balanceTotalMinutes: Int? + + public init(balanceLastPeriodMinutes: Int?, newMinutes: Int?, balanceTotalMinutes: Int?) { + self.balanceLastPeriodMinutes = balanceLastPeriodMinutes + self.newMinutes = newMinutes + self.balanceTotalMinutes = balanceTotalMinutes + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case balanceLastPeriodMinutes = "balance_last_period_minutes" + case newMinutes = "new_minutes" + case balanceTotalMinutes = "balance_total_minutes" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(balanceLastPeriodMinutes, forKey: .balanceLastPeriodMinutes) + try container.encode(newMinutes, forKey: .newMinutes) + try container.encode(balanceTotalMinutes, forKey: .balanceTotalMinutes) + } +} + diff --git a/sdk/swift/TimrApi/Models/OvertimeSurchargeAccounts.swift b/sdk/swift/TimrApi/Models/OvertimeSurchargeAccounts.swift new file mode 100644 index 0000000..e3a44fa --- /dev/null +++ b/sdk/swift/TimrApi/Models/OvertimeSurchargeAccounts.swift @@ -0,0 +1,44 @@ +// +// OvertimeSurchargeAccounts.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct OvertimeSurchargeAccounts: Codable, JSONEncodable, Hashable { + + public var rule: OvertimeSurchargeRule + public var percentage: Double? + public var overtime: OvertimeSurchargeAccount + public var surcharge: OvertimeSurchargeAccount + + public init(rule: OvertimeSurchargeRule, percentage: Double?, overtime: OvertimeSurchargeAccount, surcharge: OvertimeSurchargeAccount) { + self.rule = rule + self.percentage = percentage + self.overtime = overtime + self.surcharge = surcharge + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case rule + case percentage + case overtime + case surcharge + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(rule, forKey: .rule) + try container.encode(percentage, forKey: .percentage) + try container.encode(overtime, forKey: .overtime) + try container.encode(surcharge, forKey: .surcharge) + } +} + diff --git a/sdk/swift/TimrApi/Models/OvertimeSurchargeRule.swift b/sdk/swift/TimrApi/Models/OvertimeSurchargeRule.swift new file mode 100644 index 0000000..4230181 --- /dev/null +++ b/sdk/swift/TimrApi/Models/OvertimeSurchargeRule.swift @@ -0,0 +1,44 @@ +// +// OvertimeSurchargeRule.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct OvertimeSurchargeRule: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: UUID + public var name: String + public var shortName: String + + public init(id: UUID, name: String, shortName: String) { + self.id = id + self.name = name + self.shortName = shortName + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case shortName = "short_name" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(shortName, forKey: .shortName) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension OvertimeSurchargeRule: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/PagingInformation.swift b/sdk/swift/TimrApi/Models/PagingInformation.swift new file mode 100644 index 0000000..37c80ce --- /dev/null +++ b/sdk/swift/TimrApi/Models/PagingInformation.swift @@ -0,0 +1,33 @@ +// +// PagingInformation.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct PagingInformation: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + + public init(nextPageToken: String?) { + self.nextPageToken = nextPageToken + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + } +} + diff --git a/sdk/swift/TimrApi/Models/Platform.swift b/sdk/swift/TimrApi/Models/Platform.swift new file mode 100644 index 0000000..8bcf47f --- /dev/null +++ b/sdk/swift/TimrApi/Models/Platform.swift @@ -0,0 +1,21 @@ +// +// Platform.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Platform the entry was recorded on. */ +public enum Platform: String, Codable, CaseIterable { + case timrWeb = "timr_web" + case timrMobile = "timr_mobile" + case tourMobile = "tour_mobile" + case timrTerminal = "timr_terminal" + case syncApi = "sync_api" + case timrApi = "timr_api" +} diff --git a/sdk/swift/TimrApi/Models/ProblemDetail.swift b/sdk/swift/TimrApi/Models/ProblemDetail.swift new file mode 100644 index 0000000..6a11be9 --- /dev/null +++ b/sdk/swift/TimrApi/Models/ProblemDetail.swift @@ -0,0 +1,49 @@ +// +// ProblemDetail.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** RFC 9457 Problem Details base members (`type`, `title`, `status`, `detail`, `instance`) — the common shape of all error response bodies. */ +public struct ProblemDetail: Codable, JSONEncodable, Hashable { + + public var type: String + public var title: String + public var status: Int + public var detail: String? + public var instance: String? + + public init(type: String, title: String, status: Int, detail: String? = nil, instance: String? = nil) { + self.type = type + self.title = title + self.status = status + self.detail = detail + self.instance = instance + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case type + case title + case status + case detail + case instance + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(type, forKey: .type) + try container.encode(title, forKey: .title) + try container.encode(status, forKey: .status) + try container.encodeIfPresent(detail, forKey: .detail) + try container.encodeIfPresent(instance, forKey: .instance) + } +} + diff --git a/sdk/swift/TimrApi/Models/ProjectTime.swift b/sdk/swift/TimrApi/Models/ProjectTime.swift new file mode 100644 index 0000000..a8acef9 --- /dev/null +++ b/sdk/swift/TimrApi/Models/ProjectTime.swift @@ -0,0 +1,114 @@ +// +// ProjectTime.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** One booking on a `task`, from `start` to `end`, optionally `billable`, with `break_times`, notes and locations. */ +public struct ProjectTime: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + /** Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties */ + public var breakTimeTotalMinutes: Int + public var breakTimes: [BreakTime] + public var duration: Duration? + public var changed: Bool + public var notes: String? + public var user: UserPartial + public var task: TaskPartial + public var billable: Bool + public var startLocation: Location? + public var endLocation: Location? + public var startPlatform: Platform? + public var endPlatform: Platform? + /** Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + public var lastModified: Date + /** Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + public var lastModifiedBy: UserPartial? + public var status: ProjectTimeStatus + public var metadata: [String: AnyCodable]? + + public init(id: String, start: Date, end: Date?, breakTimeTotalMinutes: Int, breakTimes: [BreakTime], duration: Duration?, changed: Bool, notes: String?, user: UserPartial, task: TaskPartial, billable: Bool, startLocation: Location?, endLocation: Location?, startPlatform: Platform?, endPlatform: Platform?, lastModified: Date, lastModifiedBy: UserPartial?, status: ProjectTimeStatus, metadata: [String: AnyCodable]? = nil) { + self.id = id + self.start = start + self.end = end + self.breakTimeTotalMinutes = breakTimeTotalMinutes + self.breakTimes = breakTimes + self.duration = duration + self.changed = changed + self.notes = notes + self.user = user + self.task = task + self.billable = billable + self.startLocation = startLocation + self.endLocation = endLocation + self.startPlatform = startPlatform + self.endPlatform = endPlatform + self.lastModified = lastModified + self.lastModifiedBy = lastModifiedBy + self.status = status + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case start + case end + case breakTimeTotalMinutes = "break_time_total_minutes" + case breakTimes = "break_times" + case duration + case changed + case notes + case user + case task + case billable + case startLocation = "start_location" + case endLocation = "end_location" + case startPlatform = "start_platform" + case endPlatform = "end_platform" + case lastModified = "last_modified" + case lastModifiedBy = "last_modified_by" + case status + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(start, forKey: .start) + try container.encode(end, forKey: .end) + try container.encode(breakTimeTotalMinutes, forKey: .breakTimeTotalMinutes) + try container.encode(breakTimes, forKey: .breakTimes) + try container.encode(duration, forKey: .duration) + try container.encode(changed, forKey: .changed) + try container.encode(notes, forKey: .notes) + try container.encode(user, forKey: .user) + try container.encode(task, forKey: .task) + try container.encode(billable, forKey: .billable) + try container.encode(startLocation, forKey: .startLocation) + try container.encode(endLocation, forKey: .endLocation) + try container.encode(startPlatform, forKey: .startPlatform) + try container.encode(endPlatform, forKey: .endPlatform) + try container.encode(lastModified, forKey: .lastModified) + try container.encode(lastModifiedBy, forKey: .lastModifiedBy) + try container.encode(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension ProjectTime: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/ProjectTimeCreate.swift b/sdk/swift/TimrApi/Models/ProjectTimeCreate.swift new file mode 100644 index 0000000..9af7376 --- /dev/null +++ b/sdk/swift/TimrApi/Models/ProjectTimeCreate.swift @@ -0,0 +1,78 @@ +// +// ProjectTimeCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ProjectTimeCreate: Codable, JSONEncodable, Hashable { + + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var breakTimes: [BreakTimeUpdate]? + public var changed: Bool + public var notes: String? + public var taskId: String + public var billable: Bool? + public var status: ProjectTimeStatus + public var metadata: [String: AnyCodable]? + public var userId: String + public var startLocation: LocationCreate? + public var endLocation: LocationCreate? + + public init(start: Date, end: Date? = nil, breakTimes: [BreakTimeUpdate]? = nil, changed: Bool, notes: String? = nil, taskId: String, billable: Bool? = nil, status: ProjectTimeStatus, metadata: [String: AnyCodable]? = nil, userId: String, startLocation: LocationCreate? = nil, endLocation: LocationCreate? = nil) { + self.start = start + self.end = end + self.breakTimes = breakTimes + self.changed = changed + self.notes = notes + self.taskId = taskId + self.billable = billable + self.status = status + self.metadata = metadata + self.userId = userId + self.startLocation = startLocation + self.endLocation = endLocation + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + case breakTimes = "break_times" + case changed + case notes + case taskId = "task_id" + case billable + case status + case metadata + case userId = "user_id" + case startLocation = "start_location" + case endLocation = "end_location" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + try container.encodeIfPresent(breakTimes, forKey: .breakTimes) + try container.encode(changed, forKey: .changed) + try container.encodeIfPresent(notes, forKey: .notes) + try container.encode(taskId, forKey: .taskId) + try container.encodeIfPresent(billable, forKey: .billable) + try container.encode(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encode(userId, forKey: .userId) + try container.encodeIfPresent(startLocation, forKey: .startLocation) + try container.encodeIfPresent(endLocation, forKey: .endLocation) + } +} + diff --git a/sdk/swift/TimrApi/Models/ProjectTimeStatus.swift b/sdk/swift/TimrApi/Models/ProjectTimeStatus.swift new file mode 100644 index 0000000..d4a27fe --- /dev/null +++ b/sdk/swift/TimrApi/Models/ProjectTimeStatus.swift @@ -0,0 +1,23 @@ +// +// ProjectTimeStatus.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Processing state of a Project Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. */ +public enum ProjectTimeStatus: String, Codable, CaseIterable { + case running = "running" + case paused = "paused" + case changeable = "changeable" + case locked = "locked" + case approved = "approved" + case cleared = "cleared" + case closed = "closed" + case archived = "archived" +} diff --git a/sdk/swift/TimrApi/Models/ProjectTimeUpdate.swift b/sdk/swift/TimrApi/Models/ProjectTimeUpdate.swift new file mode 100644 index 0000000..302f768 --- /dev/null +++ b/sdk/swift/TimrApi/Models/ProjectTimeUpdate.swift @@ -0,0 +1,74 @@ +// +// ProjectTimeUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ProjectTimeUpdate: Codable, JSONEncodable, Hashable { + + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date? + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var breakTimes: [BreakTimeUpdate]? + public var changed: Bool? + public var notes: String? + public var taskId: String? + public var billable: Bool? + public var status: ProjectTimeStatus? + public var metadata: [String: AnyCodable]? + public var startLocation: LocationUpdate? + public var endLocation: LocationUpdate? + + public init(start: Date? = nil, end: Date? = nil, breakTimes: [BreakTimeUpdate]? = nil, changed: Bool? = nil, notes: String? = nil, taskId: String? = nil, billable: Bool? = nil, status: ProjectTimeStatus? = nil, metadata: [String: AnyCodable]? = nil, startLocation: LocationUpdate? = nil, endLocation: LocationUpdate? = nil) { + self.start = start + self.end = end + self.breakTimes = breakTimes + self.changed = changed + self.notes = notes + self.taskId = taskId + self.billable = billable + self.status = status + self.metadata = metadata + self.startLocation = startLocation + self.endLocation = endLocation + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + case breakTimes = "break_times" + case changed + case notes + case taskId = "task_id" + case billable + case status + case metadata + case startLocation = "start_location" + case endLocation = "end_location" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + try container.encodeIfPresent(breakTimes, forKey: .breakTimes) + try container.encodeIfPresent(changed, forKey: .changed) + try container.encodeIfPresent(notes, forKey: .notes) + try container.encodeIfPresent(taskId, forKey: .taskId) + try container.encodeIfPresent(billable, forKey: .billable) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(startLocation, forKey: .startLocation) + try container.encodeIfPresent(endLocation, forKey: .endLocation) + } +} + diff --git a/sdk/swift/TimrApi/Models/ProjectTimeUpsert.swift b/sdk/swift/TimrApi/Models/ProjectTimeUpsert.swift new file mode 100644 index 0000000..883b2be --- /dev/null +++ b/sdk/swift/TimrApi/Models/ProjectTimeUpsert.swift @@ -0,0 +1,66 @@ +// +// ProjectTimeUpsert.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ProjectTimeUpsert: Codable, JSONEncodable, Hashable { + + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date? + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var breakTimes: [BreakTimeUpdate]? + public var changed: Bool? + public var notes: String? + public var taskId: String? + public var billable: Bool? + public var status: ProjectTimeStatus? + public var metadata: [String: AnyCodable]? + + public init(start: Date? = nil, end: Date? = nil, breakTimes: [BreakTimeUpdate]? = nil, changed: Bool? = nil, notes: String? = nil, taskId: String? = nil, billable: Bool? = nil, status: ProjectTimeStatus? = nil, metadata: [String: AnyCodable]? = nil) { + self.start = start + self.end = end + self.breakTimes = breakTimes + self.changed = changed + self.notes = notes + self.taskId = taskId + self.billable = billable + self.status = status + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + case breakTimes = "break_times" + case changed + case notes + case taskId = "task_id" + case billable + case status + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + try container.encodeIfPresent(breakTimes, forKey: .breakTimes) + try container.encodeIfPresent(changed, forKey: .changed) + try container.encodeIfPresent(notes, forKey: .notes) + try container.encodeIfPresent(taskId, forKey: .taskId) + try container.encodeIfPresent(billable, forKey: .billable) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + diff --git a/sdk/swift/TimrApi/Models/ProjectTimesPage.swift b/sdk/swift/TimrApi/Models/ProjectTimesPage.swift new file mode 100644 index 0000000..6d6d875 --- /dev/null +++ b/sdk/swift/TimrApi/Models/ProjectTimesPage.swift @@ -0,0 +1,37 @@ +// +// ProjectTimesPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ProjectTimesPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [ProjectTime] + + public init(nextPageToken: String?, data: [ProjectTime]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/ProjectTimesSortColumn.swift b/sdk/swift/TimrApi/Models/ProjectTimesSortColumn.swift new file mode 100644 index 0000000..853b5a8 --- /dev/null +++ b/sdk/swift/TimrApi/Models/ProjectTimesSortColumn.swift @@ -0,0 +1,17 @@ +// +// ProjectTimesSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Project Times. */ +public enum ProjectTimesSortColumn: String, Codable, CaseIterable { + case start = "start" + case lastModified = "last_modified" +} diff --git a/sdk/swift/TimrApi/Models/RecordingLockType.swift b/sdk/swift/TimrApi/Models/RecordingLockType.swift new file mode 100644 index 0000000..fd782da --- /dev/null +++ b/sdk/swift/TimrApi/Models/RecordingLockType.swift @@ -0,0 +1,19 @@ +// +// RecordingLockType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Whether the assigned User may record on the Task, and where the lock comes from. `recordable` allows recording; `locked_automatically` follows the Task's lock date; `locked_manually` and `unlocked_manually` are explicit overrides for this assignment. */ +public enum RecordingLockType: String, Codable, CaseIterable { + case recordable = "recordable" + case lockedAutomatically = "locked_automatically" + case lockedManually = "locked_manually" + case unlockedManually = "unlocked_manually" +} diff --git a/sdk/swift/TimrApi/Models/RecordingModeUser.swift b/sdk/swift/TimrApi/Models/RecordingModeUser.swift new file mode 100644 index 0000000..2026416 --- /dev/null +++ b/sdk/swift/TimrApi/Models/RecordingModeUser.swift @@ -0,0 +1,18 @@ +// +// RecordingModeUser.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Whether a User may record this Working Time Type themselves. Only meaningful for day-based types. */ +public enum RecordingModeUser: String, Codable, CaseIterable { + case notAllowed = "not_allowed" + case allowed = "allowed" + case byRequest = "by_request" +} diff --git a/sdk/swift/TimrApi/Models/SortDirection.swift b/sdk/swift/TimrApi/Models/SortDirection.swift new file mode 100644 index 0000000..a9219fb --- /dev/null +++ b/sdk/swift/TimrApi/Models/SortDirection.swift @@ -0,0 +1,17 @@ +// +// SortDirection.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort direction — `asc` for ascending, `dsc` for descending. */ +public enum SortDirection: String, Codable, CaseIterable { + case asc = "asc" + case dsc = "dsc" +} diff --git a/sdk/swift/TimrApi/Models/Task.swift b/sdk/swift/TimrApi/Models/Task.swift new file mode 100644 index 0000000..15e2e4b --- /dev/null +++ b/sdk/swift/TimrApi/Models/Task.swift @@ -0,0 +1,162 @@ +// +// Task.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** A task, placed in the tree by `parent_task`, with the full path from the root in `breadcrumbs`. `bookable` and `billable` control recording and invoicing; `lock_date`, time windows and location constrain what may be recorded. */ +public struct Task: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + /** Full path of the entry within its hierarchy, including its own name. */ + public var breadcrumbs: String + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var parentTask: TaskPartial? + public var description: String? + public var descriptionExternal: String? + public var bookable: Bool + public var billable: Bool + public var projectTimeNotesRequired: Bool + /** RFC 3339 date (ISO-8601) */ + public var startDate: Date? + /** RFC 3339 date (ISO-8601) */ + public var endDate: Date? + /** RFC 3339 date (ISO-8601) */ + public var lockDate: Date? + /** time of day (ISO-8601) */ + public var earliestStartTime: String? + /** time of day (ISO-8601) */ + public var latestEndTime: String? + /** RFC 3339 date (ISO-8601) */ + public var activeFrom: Date? + /** RFC 3339 date (ISO-8601) */ + public var activeTo: Date? + public var budgetInherited: Bool? + public var budgetPlanningType: BudgetPlanningType? + public var budgetHoursPlanned: Double? + public var budgetHourlyRate: Double? + public var budgetPlanned: Double? + public var budgetIncludeNonBillableProjectTimes: Bool? + public var locationInherited: Bool? + public var location: TaskLocation? + public var locationRestrictionRadiusMeters: Int? + public var customField1: String? + public var customField2: String? + public var customField3: String? + public var metadata: [String: AnyCodable]? + + public init(id: String, name: String, breadcrumbs: String, externalId: String?, parentTask: TaskPartial?, description: String?, descriptionExternal: String?, bookable: Bool, billable: Bool, projectTimeNotesRequired: Bool, startDate: Date?, endDate: Date?, lockDate: Date? = nil, earliestStartTime: String? = nil, latestEndTime: String? = nil, activeFrom: Date?, activeTo: Date?, budgetInherited: Bool? = nil, budgetPlanningType: BudgetPlanningType? = nil, budgetHoursPlanned: Double? = nil, budgetHourlyRate: Double? = nil, budgetPlanned: Double? = nil, budgetIncludeNonBillableProjectTimes: Bool? = nil, locationInherited: Bool? = nil, location: TaskLocation? = nil, locationRestrictionRadiusMeters: Int? = nil, customField1: String?, customField2: String?, customField3: String?, metadata: [String: AnyCodable]? = nil) { + self.id = id + self.name = name + self.breadcrumbs = breadcrumbs + self.externalId = externalId + self.parentTask = parentTask + self.description = description + self.descriptionExternal = descriptionExternal + self.bookable = bookable + self.billable = billable + self.projectTimeNotesRequired = projectTimeNotesRequired + self.startDate = startDate + self.endDate = endDate + self.lockDate = lockDate + self.earliestStartTime = earliestStartTime + self.latestEndTime = latestEndTime + self.activeFrom = activeFrom + self.activeTo = activeTo + self.budgetInherited = budgetInherited + self.budgetPlanningType = budgetPlanningType + self.budgetHoursPlanned = budgetHoursPlanned + self.budgetHourlyRate = budgetHourlyRate + self.budgetPlanned = budgetPlanned + self.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes + self.locationInherited = locationInherited + self.location = location + self.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters + self.customField1 = customField1 + self.customField2 = customField2 + self.customField3 = customField3 + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case breadcrumbs + case externalId = "external_id" + case parentTask = "parent_task" + case description + case descriptionExternal = "description_external" + case bookable + case billable + case projectTimeNotesRequired = "project_time_notes_required" + case startDate = "start_date" + case endDate = "end_date" + case lockDate = "lock_date" + case earliestStartTime = "earliest_start_time" + case latestEndTime = "latest_end_time" + case activeFrom = "active_from" + case activeTo = "active_to" + case budgetInherited = "budget_inherited" + case budgetPlanningType = "budget_planning_type" + case budgetHoursPlanned = "budget_hours_planned" + case budgetHourlyRate = "budget_hourly_rate" + case budgetPlanned = "budget_planned" + case budgetIncludeNonBillableProjectTimes = "budget_include_non_billable_project_times" + case locationInherited = "location_inherited" + case location + case locationRestrictionRadiusMeters = "location_restriction_radius_meters" + case customField1 = "custom_field_1" + case customField2 = "custom_field_2" + case customField3 = "custom_field_3" + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(breadcrumbs, forKey: .breadcrumbs) + try container.encode(externalId, forKey: .externalId) + try container.encode(parentTask, forKey: .parentTask) + try container.encode(description, forKey: .description) + try container.encode(descriptionExternal, forKey: .descriptionExternal) + try container.encode(bookable, forKey: .bookable) + try container.encode(billable, forKey: .billable) + try container.encode(projectTimeNotesRequired, forKey: .projectTimeNotesRequired) + try container.encode(startDate, forKey: .startDate) + try container.encode(endDate, forKey: .endDate) + try container.encodeIfPresent(lockDate, forKey: .lockDate) + try container.encodeIfPresent(earliestStartTime, forKey: .earliestStartTime) + try container.encodeIfPresent(latestEndTime, forKey: .latestEndTime) + try container.encode(activeFrom, forKey: .activeFrom) + try container.encode(activeTo, forKey: .activeTo) + try container.encodeIfPresent(budgetInherited, forKey: .budgetInherited) + try container.encodeIfPresent(budgetPlanningType, forKey: .budgetPlanningType) + try container.encodeIfPresent(budgetHoursPlanned, forKey: .budgetHoursPlanned) + try container.encodeIfPresent(budgetHourlyRate, forKey: .budgetHourlyRate) + try container.encodeIfPresent(budgetPlanned, forKey: .budgetPlanned) + try container.encodeIfPresent(budgetIncludeNonBillableProjectTimes, forKey: .budgetIncludeNonBillableProjectTimes) + try container.encodeIfPresent(locationInherited, forKey: .locationInherited) + try container.encodeIfPresent(location, forKey: .location) + try container.encodeIfPresent(locationRestrictionRadiusMeters, forKey: .locationRestrictionRadiusMeters) + try container.encode(customField1, forKey: .customField1) + try container.encode(customField2, forKey: .customField2) + try container.encode(customField3, forKey: .customField3) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension Task: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/TaskBase.swift b/sdk/swift/TimrApi/Models/TaskBase.swift new file mode 100644 index 0000000..671aac2 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskBase.swift @@ -0,0 +1,147 @@ +// +// TaskBase.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskBase: Codable, JSONEncodable, Hashable { + + public var name: String? + /** returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. */ + public var parentTaskId: String? + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var description: String? + public var descriptionExternal: String? + /** when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. */ + public var bookable: Bool? + public var billable: Bool? + /** depending on this property project times booked on this task have to include notes or not */ + public var projectTimeNotesRequired: Bool? + /** the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + public var startDate: Date? + /** the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + public var endDate: Date? + /** with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later */ + public var lockDate: Date? + /** set this property to limit the task so that it cannot be booked before this time */ + public var earliestStartTime: String? + /** set this property to limit the task so that it cannot be booked after this time */ + public var latestEndTime: String? + /** when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. */ + public var budgetPlanningType: BudgetPlanningTypeRequest? + /** how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + public var budgetHoursPlanned: Double? + /** depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value */ + public var budgetHourlyRate: Double? + /** the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + public var budgetPlanned: Double? + /** set this property to true, if you want to include not billable hours for all project times booked on this task */ + public var budgetIncludeNonBillableProjectTimes: Bool? + /** set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent */ + public var locationInherited: Bool? + public var location: TaskLocation? + /** set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius */ + public var locationRestrictionRadiusMeters: Int? + /** you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + public var customField1: String? + /** you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + public var customField2: String? + /** you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + public var customField3: String? + public var metadata: [String: AnyCodable]? + + public init(name: String? = nil, parentTaskId: String? = nil, externalId: String? = nil, description: String? = nil, descriptionExternal: String? = nil, bookable: Bool? = nil, billable: Bool? = nil, projectTimeNotesRequired: Bool? = nil, startDate: Date? = nil, endDate: Date? = nil, lockDate: Date? = nil, earliestStartTime: String? = nil, latestEndTime: String? = nil, budgetPlanningType: BudgetPlanningTypeRequest? = nil, budgetHoursPlanned: Double? = nil, budgetHourlyRate: Double? = nil, budgetPlanned: Double? = nil, budgetIncludeNonBillableProjectTimes: Bool? = nil, locationInherited: Bool? = nil, location: TaskLocation? = nil, locationRestrictionRadiusMeters: Int? = nil, customField1: String? = nil, customField2: String? = nil, customField3: String? = nil, metadata: [String: AnyCodable]? = nil) { + self.name = name + self.parentTaskId = parentTaskId + self.externalId = externalId + self.description = description + self.descriptionExternal = descriptionExternal + self.bookable = bookable + self.billable = billable + self.projectTimeNotesRequired = projectTimeNotesRequired + self.startDate = startDate + self.endDate = endDate + self.lockDate = lockDate + self.earliestStartTime = earliestStartTime + self.latestEndTime = latestEndTime + self.budgetPlanningType = budgetPlanningType + self.budgetHoursPlanned = budgetHoursPlanned + self.budgetHourlyRate = budgetHourlyRate + self.budgetPlanned = budgetPlanned + self.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes + self.locationInherited = locationInherited + self.location = location + self.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters + self.customField1 = customField1 + self.customField2 = customField2 + self.customField3 = customField3 + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case parentTaskId = "parent_task_id" + case externalId = "external_id" + case description + case descriptionExternal = "description_external" + case bookable + case billable + case projectTimeNotesRequired = "project_time_notes_required" + case startDate = "start_date" + case endDate = "end_date" + case lockDate = "lock_date" + case earliestStartTime = "earliest_start_time" + case latestEndTime = "latest_end_time" + case budgetPlanningType = "budget_planning_type" + case budgetHoursPlanned = "budget_hours_planned" + case budgetHourlyRate = "budget_hourly_rate" + case budgetPlanned = "budget_planned" + case budgetIncludeNonBillableProjectTimes = "budget_include_non_billable_project_times" + case locationInherited = "location_inherited" + case location + case locationRestrictionRadiusMeters = "location_restriction_radius_meters" + case customField1 = "custom_field_1" + case customField2 = "custom_field_2" + case customField3 = "custom_field_3" + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(parentTaskId, forKey: .parentTaskId) + try container.encodeIfPresent(externalId, forKey: .externalId) + try container.encodeIfPresent(description, forKey: .description) + try container.encodeIfPresent(descriptionExternal, forKey: .descriptionExternal) + try container.encodeIfPresent(bookable, forKey: .bookable) + try container.encodeIfPresent(billable, forKey: .billable) + try container.encodeIfPresent(projectTimeNotesRequired, forKey: .projectTimeNotesRequired) + try container.encodeIfPresent(startDate, forKey: .startDate) + try container.encodeIfPresent(endDate, forKey: .endDate) + try container.encodeIfPresent(lockDate, forKey: .lockDate) + try container.encodeIfPresent(earliestStartTime, forKey: .earliestStartTime) + try container.encodeIfPresent(latestEndTime, forKey: .latestEndTime) + try container.encodeIfPresent(budgetPlanningType, forKey: .budgetPlanningType) + try container.encodeIfPresent(budgetHoursPlanned, forKey: .budgetHoursPlanned) + try container.encodeIfPresent(budgetHourlyRate, forKey: .budgetHourlyRate) + try container.encodeIfPresent(budgetPlanned, forKey: .budgetPlanned) + try container.encodeIfPresent(budgetIncludeNonBillableProjectTimes, forKey: .budgetIncludeNonBillableProjectTimes) + try container.encodeIfPresent(locationInherited, forKey: .locationInherited) + try container.encodeIfPresent(location, forKey: .location) + try container.encodeIfPresent(locationRestrictionRadiusMeters, forKey: .locationRestrictionRadiusMeters) + try container.encodeIfPresent(customField1, forKey: .customField1) + try container.encodeIfPresent(customField2, forKey: .customField2) + try container.encodeIfPresent(customField3, forKey: .customField3) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskCreate.swift b/sdk/swift/TimrApi/Models/TaskCreate.swift new file mode 100644 index 0000000..f494b81 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskCreate.swift @@ -0,0 +1,147 @@ +// +// TaskCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskCreate: Codable, JSONEncodable, Hashable { + + public var name: String + /** returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. */ + public var parentTaskId: String? + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var description: String? + public var descriptionExternal: String? + /** when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. */ + public var bookable: Bool + public var billable: Bool + /** depending on this property project times booked on this task have to include notes or not */ + public var projectTimeNotesRequired: Bool? + /** the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + public var startDate: Date? + /** the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + public var endDate: Date? + /** with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later */ + public var lockDate: Date? + /** set this property to limit the task so that it cannot be booked before this time */ + public var earliestStartTime: String? + /** set this property to limit the task so that it cannot be booked after this time */ + public var latestEndTime: String? + /** when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. */ + public var budgetPlanningType: BudgetPlanningTypeRequest? + /** how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + public var budgetHoursPlanned: Double? + /** depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value */ + public var budgetHourlyRate: Double? + /** the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + public var budgetPlanned: Double? + /** set this property to true, if you want to include not billable hours for all project times booked on this task */ + public var budgetIncludeNonBillableProjectTimes: Bool? + /** set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent */ + public var locationInherited: Bool? + public var location: TaskLocation? + /** set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius */ + public var locationRestrictionRadiusMeters: Int? + /** you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + public var customField1: String? + /** you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + public var customField2: String? + /** you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + public var customField3: String? + public var metadata: [String: AnyCodable]? + + public init(name: String, parentTaskId: String? = nil, externalId: String? = nil, description: String? = nil, descriptionExternal: String? = nil, bookable: Bool, billable: Bool, projectTimeNotesRequired: Bool? = nil, startDate: Date? = nil, endDate: Date? = nil, lockDate: Date? = nil, earliestStartTime: String? = nil, latestEndTime: String? = nil, budgetPlanningType: BudgetPlanningTypeRequest? = nil, budgetHoursPlanned: Double? = nil, budgetHourlyRate: Double? = nil, budgetPlanned: Double? = nil, budgetIncludeNonBillableProjectTimes: Bool? = nil, locationInherited: Bool? = nil, location: TaskLocation? = nil, locationRestrictionRadiusMeters: Int? = nil, customField1: String? = nil, customField2: String? = nil, customField3: String? = nil, metadata: [String: AnyCodable]? = nil) { + self.name = name + self.parentTaskId = parentTaskId + self.externalId = externalId + self.description = description + self.descriptionExternal = descriptionExternal + self.bookable = bookable + self.billable = billable + self.projectTimeNotesRequired = projectTimeNotesRequired + self.startDate = startDate + self.endDate = endDate + self.lockDate = lockDate + self.earliestStartTime = earliestStartTime + self.latestEndTime = latestEndTime + self.budgetPlanningType = budgetPlanningType + self.budgetHoursPlanned = budgetHoursPlanned + self.budgetHourlyRate = budgetHourlyRate + self.budgetPlanned = budgetPlanned + self.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes + self.locationInherited = locationInherited + self.location = location + self.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters + self.customField1 = customField1 + self.customField2 = customField2 + self.customField3 = customField3 + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case parentTaskId = "parent_task_id" + case externalId = "external_id" + case description + case descriptionExternal = "description_external" + case bookable + case billable + case projectTimeNotesRequired = "project_time_notes_required" + case startDate = "start_date" + case endDate = "end_date" + case lockDate = "lock_date" + case earliestStartTime = "earliest_start_time" + case latestEndTime = "latest_end_time" + case budgetPlanningType = "budget_planning_type" + case budgetHoursPlanned = "budget_hours_planned" + case budgetHourlyRate = "budget_hourly_rate" + case budgetPlanned = "budget_planned" + case budgetIncludeNonBillableProjectTimes = "budget_include_non_billable_project_times" + case locationInherited = "location_inherited" + case location + case locationRestrictionRadiusMeters = "location_restriction_radius_meters" + case customField1 = "custom_field_1" + case customField2 = "custom_field_2" + case customField3 = "custom_field_3" + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(parentTaskId, forKey: .parentTaskId) + try container.encodeIfPresent(externalId, forKey: .externalId) + try container.encodeIfPresent(description, forKey: .description) + try container.encodeIfPresent(descriptionExternal, forKey: .descriptionExternal) + try container.encode(bookable, forKey: .bookable) + try container.encode(billable, forKey: .billable) + try container.encodeIfPresent(projectTimeNotesRequired, forKey: .projectTimeNotesRequired) + try container.encodeIfPresent(startDate, forKey: .startDate) + try container.encodeIfPresent(endDate, forKey: .endDate) + try container.encodeIfPresent(lockDate, forKey: .lockDate) + try container.encodeIfPresent(earliestStartTime, forKey: .earliestStartTime) + try container.encodeIfPresent(latestEndTime, forKey: .latestEndTime) + try container.encodeIfPresent(budgetPlanningType, forKey: .budgetPlanningType) + try container.encodeIfPresent(budgetHoursPlanned, forKey: .budgetHoursPlanned) + try container.encodeIfPresent(budgetHourlyRate, forKey: .budgetHourlyRate) + try container.encodeIfPresent(budgetPlanned, forKey: .budgetPlanned) + try container.encodeIfPresent(budgetIncludeNonBillableProjectTimes, forKey: .budgetIncludeNonBillableProjectTimes) + try container.encodeIfPresent(locationInherited, forKey: .locationInherited) + try container.encodeIfPresent(location, forKey: .location) + try container.encodeIfPresent(locationRestrictionRadiusMeters, forKey: .locationRestrictionRadiusMeters) + try container.encodeIfPresent(customField1, forKey: .customField1) + try container.encodeIfPresent(customField2, forKey: .customField2) + try container.encodeIfPresent(customField3, forKey: .customField3) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskLocation.swift b/sdk/swift/TimrApi/Models/TaskLocation.swift new file mode 100644 index 0000000..d4611f0 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskLocation.swift @@ -0,0 +1,60 @@ +// +// TaskLocation.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** You can define the location of a task by setting this property. If the task has a parent task, the location is inherited if nothing else is explicitly defined. If you set this property to null, the location will be deleted. */ +public struct TaskLocation: Codable, JSONEncodable, Hashable { + + /** Latitude in decimal degrees. */ + public var lat: Float? + /** Longitude in decimal degrees. */ + public var lon: Float? + public var address: String? + public var city: String? + public var zipCode: String? + public var state: String? + /** the country's international country code */ + public var country: String? + + public init(lat: Float?, lon: Float?, address: String?, city: String?, zipCode: String?, state: String?, country: String?) { + self.lat = lat + self.lon = lon + self.address = address + self.city = city + self.zipCode = zipCode + self.state = state + self.country = country + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case lat + case lon + case address + case city + case zipCode = "zip_code" + case state + case country + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(lat, forKey: .lat) + try container.encode(lon, forKey: .lon) + try container.encode(address, forKey: .address) + try container.encode(city, forKey: .city) + try container.encode(zipCode, forKey: .zipCode) + try container.encode(state, forKey: .state) + try container.encode(country, forKey: .country) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskPartial.swift b/sdk/swift/TimrApi/Models/TaskPartial.swift new file mode 100644 index 0000000..8b1da65 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskPartial.swift @@ -0,0 +1,50 @@ +// +// TaskPartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskPartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + /** Full path of the entry within its hierarchy, including its own name. */ + public var breadcrumbs: String + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + + public init(id: String, name: String, breadcrumbs: String, externalId: String?) { + self.id = id + self.name = name + self.breadcrumbs = breadcrumbs + self.externalId = externalId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case breadcrumbs + case externalId = "external_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(breadcrumbs, forKey: .breadcrumbs) + try container.encode(externalId, forKey: .externalId) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension TaskPartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/TaskReduced.swift b/sdk/swift/TimrApi/Models/TaskReduced.swift new file mode 100644 index 0000000..e30615e --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskReduced.swift @@ -0,0 +1,123 @@ +// +// TaskReduced.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskReduced: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + /** Full path of the entry within its hierarchy, including its own name. */ + public var breadcrumbs: String + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var parentTask: TaskPartial? + public var description: String? + public var bookable: Bool + public var billable: Bool + public var projectTimeNotesRequired: Bool + /** RFC 3339 date (ISO-8601) */ + public var lockDate: Date? + /** time of day (ISO-8601) */ + public var earliestStartTime: String? + /** time of day (ISO-8601) */ + public var latestEndTime: String? + /** RFC 3339 date (ISO-8601) */ + public var activeFrom: Date? + /** RFC 3339 date (ISO-8601) */ + public var activeTo: Date? + public var budgetPlanningType: BudgetPlanningType? + public var locationInherited: Bool? + public var location: TaskLocation? + public var locationRestrictionRadiusMeters: Int? + public var customField1: String? + public var customField2: String? + public var customField3: String? + + public init(id: String, name: String, breadcrumbs: String, externalId: String?, parentTask: TaskPartial?, description: String?, bookable: Bool, billable: Bool, projectTimeNotesRequired: Bool, lockDate: Date? = nil, earliestStartTime: String? = nil, latestEndTime: String? = nil, activeFrom: Date?, activeTo: Date?, budgetPlanningType: BudgetPlanningType? = nil, locationInherited: Bool? = nil, location: TaskLocation? = nil, locationRestrictionRadiusMeters: Int? = nil, customField1: String?, customField2: String?, customField3: String?) { + self.id = id + self.name = name + self.breadcrumbs = breadcrumbs + self.externalId = externalId + self.parentTask = parentTask + self.description = description + self.bookable = bookable + self.billable = billable + self.projectTimeNotesRequired = projectTimeNotesRequired + self.lockDate = lockDate + self.earliestStartTime = earliestStartTime + self.latestEndTime = latestEndTime + self.activeFrom = activeFrom + self.activeTo = activeTo + self.budgetPlanningType = budgetPlanningType + self.locationInherited = locationInherited + self.location = location + self.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters + self.customField1 = customField1 + self.customField2 = customField2 + self.customField3 = customField3 + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case breadcrumbs + case externalId = "external_id" + case parentTask = "parent_task" + case description + case bookable + case billable + case projectTimeNotesRequired = "project_time_notes_required" + case lockDate = "lock_date" + case earliestStartTime = "earliest_start_time" + case latestEndTime = "latest_end_time" + case activeFrom = "active_from" + case activeTo = "active_to" + case budgetPlanningType = "budget_planning_type" + case locationInherited = "location_inherited" + case location + case locationRestrictionRadiusMeters = "location_restriction_radius_meters" + case customField1 = "custom_field_1" + case customField2 = "custom_field_2" + case customField3 = "custom_field_3" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(breadcrumbs, forKey: .breadcrumbs) + try container.encode(externalId, forKey: .externalId) + try container.encode(parentTask, forKey: .parentTask) + try container.encode(description, forKey: .description) + try container.encode(bookable, forKey: .bookable) + try container.encode(billable, forKey: .billable) + try container.encode(projectTimeNotesRequired, forKey: .projectTimeNotesRequired) + try container.encodeIfPresent(lockDate, forKey: .lockDate) + try container.encodeIfPresent(earliestStartTime, forKey: .earliestStartTime) + try container.encodeIfPresent(latestEndTime, forKey: .latestEndTime) + try container.encode(activeFrom, forKey: .activeFrom) + try container.encode(activeTo, forKey: .activeTo) + try container.encodeIfPresent(budgetPlanningType, forKey: .budgetPlanningType) + try container.encodeIfPresent(locationInherited, forKey: .locationInherited) + try container.encodeIfPresent(location, forKey: .location) + try container.encodeIfPresent(locationRestrictionRadiusMeters, forKey: .locationRestrictionRadiusMeters) + try container.encode(customField1, forKey: .customField1) + try container.encode(customField2, forKey: .customField2) + try container.encode(customField3, forKey: .customField3) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension TaskReduced: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/TaskToLeaderAssignment.swift b/sdk/swift/TimrApi/Models/TaskToLeaderAssignment.swift new file mode 100644 index 0000000..efce41b --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToLeaderAssignment.swift @@ -0,0 +1,36 @@ +// +// TaskToLeaderAssignment.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskToLeaderAssignment: Codable, JSONEncodable, Hashable { + + public var user: UserPartial + public var automaticallyAssigned: Bool + + public init(user: UserPartial, automaticallyAssigned: Bool) { + self.user = user + self.automaticallyAssigned = automaticallyAssigned + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case user + case automaticallyAssigned = "automatically_assigned" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(user, forKey: .user) + try container.encode(automaticallyAssigned, forKey: .automaticallyAssigned) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskToLeaderAssignmentsPage.swift b/sdk/swift/TimrApi/Models/TaskToLeaderAssignmentsPage.swift new file mode 100644 index 0000000..9ebc3b7 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToLeaderAssignmentsPage.swift @@ -0,0 +1,37 @@ +// +// TaskToLeaderAssignmentsPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskToLeaderAssignmentsPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [TaskToLeaderAssignment] + + public init(nextPageToken: String?, data: [TaskToLeaderAssignment]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskToLeaderAssignmentsSortColumn.swift b/sdk/swift/TimrApi/Models/TaskToLeaderAssignmentsSortColumn.swift new file mode 100644 index 0000000..7763dc0 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToLeaderAssignmentsSortColumn.swift @@ -0,0 +1,16 @@ +// +// TaskToLeaderAssignmentsSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Task to Leader Assignments. `user_name` orders by the assigned User's last name, then first name. */ +public enum TaskToLeaderAssignmentsSortColumn: String, Codable, CaseIterable { + case userName = "user_name" +} diff --git a/sdk/swift/TimrApi/Models/TaskToTeamAssignment.swift b/sdk/swift/TimrApi/Models/TaskToTeamAssignment.swift new file mode 100644 index 0000000..e54f7b4 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToTeamAssignment.swift @@ -0,0 +1,36 @@ +// +// TaskToTeamAssignment.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskToTeamAssignment: Codable, JSONEncodable, Hashable { + + public var team: TeamPartial + public var automaticallyAssigned: Bool + + public init(team: TeamPartial, automaticallyAssigned: Bool) { + self.team = team + self.automaticallyAssigned = automaticallyAssigned + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case team + case automaticallyAssigned = "automatically_assigned" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(team, forKey: .team) + try container.encode(automaticallyAssigned, forKey: .automaticallyAssigned) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskToTeamAssignmentsPage.swift b/sdk/swift/TimrApi/Models/TaskToTeamAssignmentsPage.swift new file mode 100644 index 0000000..7be3165 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToTeamAssignmentsPage.swift @@ -0,0 +1,37 @@ +// +// TaskToTeamAssignmentsPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskToTeamAssignmentsPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [TaskToTeamAssignment] + + public init(nextPageToken: String?, data: [TaskToTeamAssignment]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskToTeamAssignmentsSortColumn.swift b/sdk/swift/TimrApi/Models/TaskToTeamAssignmentsSortColumn.swift new file mode 100644 index 0000000..c2da4c8 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToTeamAssignmentsSortColumn.swift @@ -0,0 +1,16 @@ +// +// TaskToTeamAssignmentsSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Task to Team Assignments. `team_name` orders by the assigned Team's name. */ +public enum TaskToTeamAssignmentsSortColumn: String, Codable, CaseIterable { + case teamName = "team_name" +} diff --git a/sdk/swift/TimrApi/Models/TaskToUserAssignment.swift b/sdk/swift/TimrApi/Models/TaskToUserAssignment.swift new file mode 100644 index 0000000..0c45052 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToUserAssignment.swift @@ -0,0 +1,44 @@ +// +// TaskToUserAssignment.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskToUserAssignment: Codable, JSONEncodable, Hashable { + + public var user: UserPartial + public var hoursPlanned: Double? + public var recordingLock: RecordingLockType + public var automaticallyAssigned: Bool + + public init(user: UserPartial, hoursPlanned: Double? = nil, recordingLock: RecordingLockType, automaticallyAssigned: Bool) { + self.user = user + self.hoursPlanned = hoursPlanned + self.recordingLock = recordingLock + self.automaticallyAssigned = automaticallyAssigned + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case user + case hoursPlanned = "hours_planned" + case recordingLock = "recording_lock" + case automaticallyAssigned = "automatically_assigned" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(user, forKey: .user) + try container.encodeIfPresent(hoursPlanned, forKey: .hoursPlanned) + try container.encode(recordingLock, forKey: .recordingLock) + try container.encode(automaticallyAssigned, forKey: .automaticallyAssigned) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskToUserAssignmentUpsert.swift b/sdk/swift/TimrApi/Models/TaskToUserAssignmentUpsert.swift new file mode 100644 index 0000000..101c40d --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToUserAssignmentUpsert.swift @@ -0,0 +1,36 @@ +// +// TaskToUserAssignmentUpsert.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskToUserAssignmentUpsert: Codable, JSONEncodable, Hashable { + + public var hoursPlanned: Double? + public var recordingLock: RecordingLockType? + + public init(hoursPlanned: Double? = nil, recordingLock: RecordingLockType? = nil) { + self.hoursPlanned = hoursPlanned + self.recordingLock = recordingLock + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case hoursPlanned = "hours_planned" + case recordingLock = "recording_lock" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(hoursPlanned, forKey: .hoursPlanned) + try container.encodeIfPresent(recordingLock, forKey: .recordingLock) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskToUserAssignmentsPage.swift b/sdk/swift/TimrApi/Models/TaskToUserAssignmentsPage.swift new file mode 100644 index 0000000..43f61b0 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToUserAssignmentsPage.swift @@ -0,0 +1,37 @@ +// +// TaskToUserAssignmentsPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskToUserAssignmentsPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [TaskToUserAssignment] + + public init(nextPageToken: String?, data: [TaskToUserAssignment]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/TaskToUserAssignmentsSortColumn.swift b/sdk/swift/TimrApi/Models/TaskToUserAssignmentsSortColumn.swift new file mode 100644 index 0000000..eb72a2c --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskToUserAssignmentsSortColumn.swift @@ -0,0 +1,16 @@ +// +// TaskToUserAssignmentsSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Task to User Assignments. `user_name` orders by the assigned User's last name, then first name. */ +public enum TaskToUserAssignmentsSortColumn: String, Codable, CaseIterable { + case userName = "user_name" +} diff --git a/sdk/swift/TimrApi/Models/TaskUpdate.swift b/sdk/swift/TimrApi/Models/TaskUpdate.swift new file mode 100644 index 0000000..24adff7 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TaskUpdate.swift @@ -0,0 +1,152 @@ +// +// TaskUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TaskUpdate: Codable, JSONEncodable, Hashable { + + public var name: String? + /** returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. */ + public var parentTaskId: String? + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var description: String? + public var descriptionExternal: String? + /** when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. */ + public var bookable: Bool? + public var billable: Bool? + /** depending on this property project times booked on this task have to include notes or not */ + public var projectTimeNotesRequired: Bool? + /** the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + public var startDate: Date? + /** the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. */ + public var endDate: Date? + /** with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that * existing entries cannot be changed or deleted * no entries can be added later */ + public var lockDate: Date? + /** set this property to limit the task so that it cannot be booked before this time */ + public var earliestStartTime: String? + /** set this property to limit the task so that it cannot be booked after this time */ + public var latestEndTime: String? + /** when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. */ + public var budgetPlanningType: BudgetPlanningTypeRequest? + /** how many hours were planned in the calculation set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + public var budgetHoursPlanned: Double? + /** depending on its budget_planning_type this property may or may not be set: * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** * **user_hourly_rate: this property cannot be set** * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value */ + public var budgetHourlyRate: Double? + /** the price at which the task was sold set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: * task_hourly_rate: out of budget_hourly_rate and budget_planned * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned * fixed_price: out of budget_hourly_rate and budget_planned */ + public var budgetPlanned: Double? + /** set this property to true, if you want to include not billable hours for all project times booked on this task */ + public var budgetIncludeNonBillableProjectTimes: Bool? + /** set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent */ + public var locationInherited: Bool? + public var location: TaskLocation? + /** set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius */ + public var locationRestrictionRadiusMeters: Int? + /** you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + public var customField1: String? + /** you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + public var customField2: String? + /** you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. */ + public var customField3: String? + public var metadata: [String: AnyCodable]? + /** this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. */ + public var budgetUpdateProjectTimes: Bool? + + public init(name: String? = nil, parentTaskId: String? = nil, externalId: String? = nil, description: String? = nil, descriptionExternal: String? = nil, bookable: Bool? = nil, billable: Bool? = nil, projectTimeNotesRequired: Bool? = nil, startDate: Date? = nil, endDate: Date? = nil, lockDate: Date? = nil, earliestStartTime: String? = nil, latestEndTime: String? = nil, budgetPlanningType: BudgetPlanningTypeRequest? = nil, budgetHoursPlanned: Double? = nil, budgetHourlyRate: Double? = nil, budgetPlanned: Double? = nil, budgetIncludeNonBillableProjectTimes: Bool? = nil, locationInherited: Bool? = nil, location: TaskLocation? = nil, locationRestrictionRadiusMeters: Int? = nil, customField1: String? = nil, customField2: String? = nil, customField3: String? = nil, metadata: [String: AnyCodable]? = nil, budgetUpdateProjectTimes: Bool? = nil) { + self.name = name + self.parentTaskId = parentTaskId + self.externalId = externalId + self.description = description + self.descriptionExternal = descriptionExternal + self.bookable = bookable + self.billable = billable + self.projectTimeNotesRequired = projectTimeNotesRequired + self.startDate = startDate + self.endDate = endDate + self.lockDate = lockDate + self.earliestStartTime = earliestStartTime + self.latestEndTime = latestEndTime + self.budgetPlanningType = budgetPlanningType + self.budgetHoursPlanned = budgetHoursPlanned + self.budgetHourlyRate = budgetHourlyRate + self.budgetPlanned = budgetPlanned + self.budgetIncludeNonBillableProjectTimes = budgetIncludeNonBillableProjectTimes + self.locationInherited = locationInherited + self.location = location + self.locationRestrictionRadiusMeters = locationRestrictionRadiusMeters + self.customField1 = customField1 + self.customField2 = customField2 + self.customField3 = customField3 + self.metadata = metadata + self.budgetUpdateProjectTimes = budgetUpdateProjectTimes + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case parentTaskId = "parent_task_id" + case externalId = "external_id" + case description + case descriptionExternal = "description_external" + case bookable + case billable + case projectTimeNotesRequired = "project_time_notes_required" + case startDate = "start_date" + case endDate = "end_date" + case lockDate = "lock_date" + case earliestStartTime = "earliest_start_time" + case latestEndTime = "latest_end_time" + case budgetPlanningType = "budget_planning_type" + case budgetHoursPlanned = "budget_hours_planned" + case budgetHourlyRate = "budget_hourly_rate" + case budgetPlanned = "budget_planned" + case budgetIncludeNonBillableProjectTimes = "budget_include_non_billable_project_times" + case locationInherited = "location_inherited" + case location + case locationRestrictionRadiusMeters = "location_restriction_radius_meters" + case customField1 = "custom_field_1" + case customField2 = "custom_field_2" + case customField3 = "custom_field_3" + case metadata + case budgetUpdateProjectTimes = "budget_update_project_times" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(parentTaskId, forKey: .parentTaskId) + try container.encodeIfPresent(externalId, forKey: .externalId) + try container.encodeIfPresent(description, forKey: .description) + try container.encodeIfPresent(descriptionExternal, forKey: .descriptionExternal) + try container.encodeIfPresent(bookable, forKey: .bookable) + try container.encodeIfPresent(billable, forKey: .billable) + try container.encodeIfPresent(projectTimeNotesRequired, forKey: .projectTimeNotesRequired) + try container.encodeIfPresent(startDate, forKey: .startDate) + try container.encodeIfPresent(endDate, forKey: .endDate) + try container.encodeIfPresent(lockDate, forKey: .lockDate) + try container.encodeIfPresent(earliestStartTime, forKey: .earliestStartTime) + try container.encodeIfPresent(latestEndTime, forKey: .latestEndTime) + try container.encodeIfPresent(budgetPlanningType, forKey: .budgetPlanningType) + try container.encodeIfPresent(budgetHoursPlanned, forKey: .budgetHoursPlanned) + try container.encodeIfPresent(budgetHourlyRate, forKey: .budgetHourlyRate) + try container.encodeIfPresent(budgetPlanned, forKey: .budgetPlanned) + try container.encodeIfPresent(budgetIncludeNonBillableProjectTimes, forKey: .budgetIncludeNonBillableProjectTimes) + try container.encodeIfPresent(locationInherited, forKey: .locationInherited) + try container.encodeIfPresent(location, forKey: .location) + try container.encodeIfPresent(locationRestrictionRadiusMeters, forKey: .locationRestrictionRadiusMeters) + try container.encodeIfPresent(customField1, forKey: .customField1) + try container.encodeIfPresent(customField2, forKey: .customField2) + try container.encodeIfPresent(customField3, forKey: .customField3) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(budgetUpdateProjectTimes, forKey: .budgetUpdateProjectTimes) + } +} + diff --git a/sdk/swift/TimrApi/Models/TasksPage.swift b/sdk/swift/TimrApi/Models/TasksPage.swift new file mode 100644 index 0000000..7a0092f --- /dev/null +++ b/sdk/swift/TimrApi/Models/TasksPage.swift @@ -0,0 +1,37 @@ +// +// TasksPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TasksPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [Task] + + public init(nextPageToken: String?, data: [Task]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/TasksReducedPage.swift b/sdk/swift/TimrApi/Models/TasksReducedPage.swift new file mode 100644 index 0000000..693ac54 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TasksReducedPage.swift @@ -0,0 +1,37 @@ +// +// TasksReducedPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TasksReducedPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [TaskReduced] + + public init(nextPageToken: String?, data: [TaskReduced]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/TasksSortColumn.swift b/sdk/swift/TimrApi/Models/TasksSortColumn.swift new file mode 100644 index 0000000..d7c386b --- /dev/null +++ b/sdk/swift/TimrApi/Models/TasksSortColumn.swift @@ -0,0 +1,17 @@ +// +// TasksSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Tasks. `breadcrumbs` orders by the Task's full path, `name` by its own name only. */ +public enum TasksSortColumn: String, Codable, CaseIterable { + case breadcrumbs = "breadcrumbs" + case name = "name" +} diff --git a/sdk/swift/TimrApi/Models/Team.swift b/sdk/swift/TimrApi/Models/Team.swift new file mode 100644 index 0000000..7b78b87 --- /dev/null +++ b/sdk/swift/TimrApi/Models/Team.swift @@ -0,0 +1,59 @@ +// +// Team.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** A team, placed in the hierarchy by `parent_team`, with the full path from the root in `breadcrumbs`. */ +public struct Team: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + /** Full path of the entry within its hierarchy, including its own name. */ + public var breadcrumbs: String + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var description: String? + public var parentTeam: TeamPartial? + + public init(id: String, name: String, breadcrumbs: String, externalId: String?, description: String?, parentTeam: TeamPartial?) { + self.id = id + self.name = name + self.breadcrumbs = breadcrumbs + self.externalId = externalId + self.description = description + self.parentTeam = parentTeam + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case breadcrumbs + case externalId = "external_id" + case description + case parentTeam = "parent_team" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(breadcrumbs, forKey: .breadcrumbs) + try container.encode(externalId, forKey: .externalId) + try container.encode(description, forKey: .description) + try container.encode(parentTeam, forKey: .parentTeam) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension Team: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/TeamCreate.swift b/sdk/swift/TimrApi/Models/TeamCreate.swift new file mode 100644 index 0000000..3660396 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TeamCreate.swift @@ -0,0 +1,45 @@ +// +// TeamCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TeamCreate: Codable, JSONEncodable, Hashable { + + public var name: String + public var description: String? + public var parentTeamId: String? + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + + public init(name: String, description: String? = nil, parentTeamId: String? = nil, externalId: String? = nil) { + self.name = name + self.description = description + self.parentTeamId = parentTeamId + self.externalId = externalId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case description + case parentTeamId = "parent_team_id" + case externalId = "external_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(description, forKey: .description) + try container.encodeIfPresent(parentTeamId, forKey: .parentTeamId) + try container.encodeIfPresent(externalId, forKey: .externalId) + } +} + diff --git a/sdk/swift/TimrApi/Models/TeamPartial.swift b/sdk/swift/TimrApi/Models/TeamPartial.swift new file mode 100644 index 0000000..2360b3b --- /dev/null +++ b/sdk/swift/TimrApi/Models/TeamPartial.swift @@ -0,0 +1,50 @@ +// +// TeamPartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TeamPartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + /** Full path of the entry within its hierarchy, including its own name. */ + public var breadcrumbs: String + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + + public init(id: String, name: String, breadcrumbs: String, externalId: String?) { + self.id = id + self.name = name + self.breadcrumbs = breadcrumbs + self.externalId = externalId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case breadcrumbs + case externalId = "external_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(breadcrumbs, forKey: .breadcrumbs) + try container.encode(externalId, forKey: .externalId) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension TeamPartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/TeamUpdate.swift b/sdk/swift/TimrApi/Models/TeamUpdate.swift new file mode 100644 index 0000000..6801bc4 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TeamUpdate.swift @@ -0,0 +1,45 @@ +// +// TeamUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TeamUpdate: Codable, JSONEncodable, Hashable { + + public var name: String? + public var description: String? + public var parentTeamId: String? + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + + public init(name: String? = nil, description: String? = nil, parentTeamId: String? = nil, externalId: String? = nil) { + self.name = name + self.description = description + self.parentTeamId = parentTeamId + self.externalId = externalId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case description + case parentTeamId = "parent_team_id" + case externalId = "external_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(description, forKey: .description) + try container.encodeIfPresent(parentTeamId, forKey: .parentTeamId) + try container.encodeIfPresent(externalId, forKey: .externalId) + } +} + diff --git a/sdk/swift/TimrApi/Models/TeamsPage.swift b/sdk/swift/TimrApi/Models/TeamsPage.swift new file mode 100644 index 0000000..9f3ef81 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TeamsPage.swift @@ -0,0 +1,37 @@ +// +// TeamsPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TeamsPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [Team] + + public init(nextPageToken: String?, data: [Team]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/TeamsPartialPage.swift b/sdk/swift/TimrApi/Models/TeamsPartialPage.swift new file mode 100644 index 0000000..acecbd3 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TeamsPartialPage.swift @@ -0,0 +1,37 @@ +// +// TeamsPartialPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TeamsPartialPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [TeamPartial] + + public init(nextPageToken: String?, data: [TeamPartial]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/TeamsSortColumn.swift b/sdk/swift/TimrApi/Models/TeamsSortColumn.swift new file mode 100644 index 0000000..4fc79f7 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TeamsSortColumn.swift @@ -0,0 +1,17 @@ +// +// TeamsSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Teams. `breadcrumbs` orders by the Team's full path, `name` by its own name only. */ +public enum TeamsSortColumn: String, Codable, CaseIterable { + case breadcrumbs = "breadcrumbs" + case name = "name" +} diff --git a/sdk/swift/TimrApi/Models/TimeAccount.swift b/sdk/swift/TimrApi/Models/TimeAccount.swift new file mode 100644 index 0000000..b6de291 --- /dev/null +++ b/sdk/swift/TimrApi/Models/TimeAccount.swift @@ -0,0 +1,66 @@ +// +// TimeAccount.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TimeAccount: Codable, JSONEncodable, Hashable { + + public var balanceLastPeriodMinutes: Int? + /** sum of durations in current period */ + public var durationActualMinutes: Int? + /** target duration in current period */ + public var durationTargetMinutes: Int? + /** difference between target duration and actual duration */ + public var balanceCurrentPeriodMinutes: Int? + /** total duration until balancing date */ + public var balanceTotalMinutes: Int? + /** complete days worked from home in current period */ + public var workFromHomeDaysFull: Int? + /** partial days worked from home in current period */ + public var workFromHomeDaysPartial: Int? + public var flexTimeIndicator: FlexTimeIndicator? + + public init(balanceLastPeriodMinutes: Int?, durationActualMinutes: Int?, durationTargetMinutes: Int?, balanceCurrentPeriodMinutes: Int?, balanceTotalMinutes: Int?, workFromHomeDaysFull: Int?, workFromHomeDaysPartial: Int?, flexTimeIndicator: FlexTimeIndicator? = nil) { + self.balanceLastPeriodMinutes = balanceLastPeriodMinutes + self.durationActualMinutes = durationActualMinutes + self.durationTargetMinutes = durationTargetMinutes + self.balanceCurrentPeriodMinutes = balanceCurrentPeriodMinutes + self.balanceTotalMinutes = balanceTotalMinutes + self.workFromHomeDaysFull = workFromHomeDaysFull + self.workFromHomeDaysPartial = workFromHomeDaysPartial + self.flexTimeIndicator = flexTimeIndicator + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case balanceLastPeriodMinutes = "balance_last_period_minutes" + case durationActualMinutes = "duration_actual_minutes" + case durationTargetMinutes = "duration_target_minutes" + case balanceCurrentPeriodMinutes = "balance_current_period_minutes" + case balanceTotalMinutes = "balance_total_minutes" + case workFromHomeDaysFull = "work_from_home_days_full" + case workFromHomeDaysPartial = "work_from_home_days_partial" + case flexTimeIndicator = "flex_time_indicator" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(balanceLastPeriodMinutes, forKey: .balanceLastPeriodMinutes) + try container.encode(durationActualMinutes, forKey: .durationActualMinutes) + try container.encode(durationTargetMinutes, forKey: .durationTargetMinutes) + try container.encode(balanceCurrentPeriodMinutes, forKey: .balanceCurrentPeriodMinutes) + try container.encode(balanceTotalMinutes, forKey: .balanceTotalMinutes) + try container.encode(workFromHomeDaysFull, forKey: .workFromHomeDaysFull) + try container.encode(workFromHomeDaysPartial, forKey: .workFromHomeDaysPartial) + try container.encodeIfPresent(flexTimeIndicator, forKey: .flexTimeIndicator) + } +} + diff --git a/sdk/swift/TimrApi/Models/User.swift b/sdk/swift/TimrApi/Models/User.swift new file mode 100644 index 0000000..973be10 --- /dev/null +++ b/sdk/swift/TimrApi/Models/User.swift @@ -0,0 +1,97 @@ +// +// User.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** A user's identity (`firstname`, `lastname`, `email`), employment dates (`entry_date`, `resign_date`), and the assigned `work_schedule_model` and `holiday_calendar`. */ +public struct User: Codable, JSONEncodable, Hashable { + + public static let emailRule = StringRule(minLength: 1, maxLength: nil, pattern: nil) + public static let loginRule = StringRule(minLength: nil, maxLength: nil, pattern: "/^[A-Za-z0-9!#$%&'*+\/=@\\.?^_`{|}~-]*$/") + public static let vacationYearStartRule = StringRule(minLength: nil, maxLength: nil, pattern: "/^--(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$/") + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var firstname: String? + public var lastname: String? + public var fullname: String? + /** Email address must be either valid or null. */ + public var email: String? + public var employeeNumber: String? + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var login: String? + /** RFC 3339 date (ISO-8601) */ + public var entryDate: Date? + /** RFC 3339 date (ISO-8601) */ + public var resignDate: Date? + public var workScheduleModel: WorkScheduleModelPartial? + public var holidayCalendar: HolidayCalendarPartial? + /** recurring month and day on which the user's vacation year starts */ + public var vacationYearStart: String? + public var metadata: [String: AnyCodable]? + + public init(id: String, firstname: String?, lastname: String?, fullname: String?, email: String?, employeeNumber: String?, externalId: String?, login: String? = nil, entryDate: Date? = nil, resignDate: Date? = nil, workScheduleModel: WorkScheduleModelPartial? = nil, holidayCalendar: HolidayCalendarPartial? = nil, vacationYearStart: String? = nil, metadata: [String: AnyCodable]? = nil) { + self.id = id + self.firstname = firstname + self.lastname = lastname + self.fullname = fullname + self.email = email + self.employeeNumber = employeeNumber + self.externalId = externalId + self.login = login + self.entryDate = entryDate + self.resignDate = resignDate + self.workScheduleModel = workScheduleModel + self.holidayCalendar = holidayCalendar + self.vacationYearStart = vacationYearStart + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case firstname + case lastname + case fullname + case email + case employeeNumber = "employee_number" + case externalId = "external_id" + case login + case entryDate = "entry_date" + case resignDate = "resign_date" + case workScheduleModel = "work_schedule_model" + case holidayCalendar = "holiday_calendar" + case vacationYearStart = "vacation_year_start" + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(firstname, forKey: .firstname) + try container.encode(lastname, forKey: .lastname) + try container.encode(fullname, forKey: .fullname) + try container.encode(email, forKey: .email) + try container.encode(employeeNumber, forKey: .employeeNumber) + try container.encode(externalId, forKey: .externalId) + try container.encodeIfPresent(login, forKey: .login) + try container.encodeIfPresent(entryDate, forKey: .entryDate) + try container.encodeIfPresent(resignDate, forKey: .resignDate) + try container.encodeIfPresent(workScheduleModel, forKey: .workScheduleModel) + try container.encodeIfPresent(holidayCalendar, forKey: .holidayCalendar) + try container.encodeIfPresent(vacationYearStart, forKey: .vacationYearStart) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension User: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/UserCreate.swift b/sdk/swift/TimrApi/Models/UserCreate.swift new file mode 100644 index 0000000..37cea5a --- /dev/null +++ b/sdk/swift/TimrApi/Models/UserCreate.swift @@ -0,0 +1,76 @@ +// +// UserCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct UserCreate: Codable, JSONEncodable, Hashable { + + public static let loginRule = StringRule(minLength: 1, maxLength: nil, pattern: "/^[A-Za-z0-9!#$%&'*+\/=@\\.?^_`{|}~-]*$/") + public static let emailRule = StringRule(minLength: 1, maxLength: nil, pattern: nil) + public var login: String + public var firstname: String? + public var lastname: String? + public var email: String? + /** RFC 3339 date (ISO-8601) */ + public var entryDate: Date? + /** RFC 3339 date (ISO-8601) */ + public var resignDate: Date? + public var employeeNumber: String? + public var externalId: String? + public var metadata: [String: AnyCodable]? + public var authProvider: String? + public var authIdentifier: String? + + public init(login: String, firstname: String? = nil, lastname: String? = nil, email: String? = nil, entryDate: Date? = nil, resignDate: Date? = nil, employeeNumber: String? = nil, externalId: String? = nil, metadata: [String: AnyCodable]? = nil, authProvider: String? = nil, authIdentifier: String? = nil) { + self.login = login + self.firstname = firstname + self.lastname = lastname + self.email = email + self.entryDate = entryDate + self.resignDate = resignDate + self.employeeNumber = employeeNumber + self.externalId = externalId + self.metadata = metadata + self.authProvider = authProvider + self.authIdentifier = authIdentifier + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case login + case firstname + case lastname + case email + case entryDate = "entry_date" + case resignDate = "resign_date" + case employeeNumber = "employee_number" + case externalId = "external_id" + case metadata + case authProvider = "auth_provider" + case authIdentifier = "auth_identifier" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(login, forKey: .login) + try container.encodeIfPresent(firstname, forKey: .firstname) + try container.encodeIfPresent(lastname, forKey: .lastname) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(entryDate, forKey: .entryDate) + try container.encodeIfPresent(resignDate, forKey: .resignDate) + try container.encodeIfPresent(employeeNumber, forKey: .employeeNumber) + try container.encodeIfPresent(externalId, forKey: .externalId) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(authProvider, forKey: .authProvider) + try container.encodeIfPresent(authIdentifier, forKey: .authIdentifier) + } +} + diff --git a/sdk/swift/TimrApi/Models/UserPartial.swift b/sdk/swift/TimrApi/Models/UserPartial.swift new file mode 100644 index 0000000..cc3f9c1 --- /dev/null +++ b/sdk/swift/TimrApi/Models/UserPartial.swift @@ -0,0 +1,63 @@ +// +// UserPartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct UserPartial: Codable, JSONEncodable, Hashable { + + public static let emailRule = StringRule(minLength: 1, maxLength: nil, pattern: nil) + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var firstname: String? + public var lastname: String? + public var fullname: String? + /** Email address must be either valid or null. */ + public var email: String? + public var employeeNumber: String? + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + + public init(id: String, firstname: String?, lastname: String?, fullname: String?, email: String?, employeeNumber: String?, externalId: String?) { + self.id = id + self.firstname = firstname + self.lastname = lastname + self.fullname = fullname + self.email = email + self.employeeNumber = employeeNumber + self.externalId = externalId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case firstname + case lastname + case fullname + case email + case employeeNumber = "employee_number" + case externalId = "external_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(firstname, forKey: .firstname) + try container.encode(lastname, forKey: .lastname) + try container.encode(fullname, forKey: .fullname) + try container.encode(email, forKey: .email) + try container.encode(employeeNumber, forKey: .employeeNumber) + try container.encode(externalId, forKey: .externalId) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension UserPartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/UserUpdate.swift b/sdk/swift/TimrApi/Models/UserUpdate.swift new file mode 100644 index 0000000..f41f549 --- /dev/null +++ b/sdk/swift/TimrApi/Models/UserUpdate.swift @@ -0,0 +1,68 @@ +// +// UserUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct UserUpdate: Codable, JSONEncodable, Hashable { + + public static let loginRule = StringRule(minLength: 1, maxLength: nil, pattern: "/^[A-Za-z0-9!#$%&'*+\/=@\\.?^_`{|}~-]*$/") + public static let emailRule = StringRule(minLength: 1, maxLength: nil, pattern: nil) + public var login: String? + public var firstname: String? + public var lastname: String? + public var email: String? + /** RFC 3339 date (ISO-8601) */ + public var entryDate: Date? + /** RFC 3339 date (ISO-8601) */ + public var resignDate: Date? + public var employeeNumber: String? + public var externalId: String? + public var metadata: [String: AnyCodable]? + + public init(login: String? = nil, firstname: String? = nil, lastname: String? = nil, email: String? = nil, entryDate: Date? = nil, resignDate: Date? = nil, employeeNumber: String? = nil, externalId: String? = nil, metadata: [String: AnyCodable]? = nil) { + self.login = login + self.firstname = firstname + self.lastname = lastname + self.email = email + self.entryDate = entryDate + self.resignDate = resignDate + self.employeeNumber = employeeNumber + self.externalId = externalId + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case login + case firstname + case lastname + case email + case entryDate = "entry_date" + case resignDate = "resign_date" + case employeeNumber = "employee_number" + case externalId = "external_id" + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(login, forKey: .login) + try container.encodeIfPresent(firstname, forKey: .firstname) + try container.encodeIfPresent(lastname, forKey: .lastname) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(entryDate, forKey: .entryDate) + try container.encodeIfPresent(resignDate, forKey: .resignDate) + try container.encodeIfPresent(employeeNumber, forKey: .employeeNumber) + try container.encodeIfPresent(externalId, forKey: .externalId) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + diff --git a/sdk/swift/TimrApi/Models/UsersPage.swift b/sdk/swift/TimrApi/Models/UsersPage.swift new file mode 100644 index 0000000..4c495f5 --- /dev/null +++ b/sdk/swift/TimrApi/Models/UsersPage.swift @@ -0,0 +1,37 @@ +// +// UsersPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct UsersPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [User] + + public init(nextPageToken: String?, data: [User]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/UsersPartialPage.swift b/sdk/swift/TimrApi/Models/UsersPartialPage.swift new file mode 100644 index 0000000..3a23490 --- /dev/null +++ b/sdk/swift/TimrApi/Models/UsersPartialPage.swift @@ -0,0 +1,37 @@ +// +// UsersPartialPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct UsersPartialPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [UserPartial] + + public init(nextPageToken: String?, data: [UserPartial]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/UsersSortColumn.swift b/sdk/swift/TimrApi/Models/UsersSortColumn.swift new file mode 100644 index 0000000..a938ba1 --- /dev/null +++ b/sdk/swift/TimrApi/Models/UsersSortColumn.swift @@ -0,0 +1,16 @@ +// +// UsersSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Users. `name` orders by last name, then first name. */ +public enum UsersSortColumn: String, Codable, CaseIterable { + case name = "name" +} diff --git a/sdk/swift/TimrApi/Models/VacationAccount.swift b/sdk/swift/TimrApi/Models/VacationAccount.swift new file mode 100644 index 0000000..6308ca6 --- /dev/null +++ b/sdk/swift/TimrApi/Models/VacationAccount.swift @@ -0,0 +1,50 @@ +// +// VacationAccount.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum VacationAccount: Codable, JSONEncodable, Hashable { + case typeVacationAccountDays(VacationAccountDays) + case typeVacationAccountMinutes(VacationAccountMinutes) + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .typeVacationAccountDays(let value): + try container.encode(value) + case .typeVacationAccountMinutes(let value): + try container.encode(value) + } + } + + private enum DiscriminatorCodingKey: String, CodingKey { + case unit = "unit" + } + + public init(from decoder: Decoder) throws { + let keyedContainer = try decoder.container(keyedBy: DiscriminatorCodingKey.self) + let discriminatorValue = try keyedContainer.decode(String.self, forKey: .unit) + + switch discriminatorValue { + case "days": + self = .typeVacationAccountDays(try VacationAccountDays(from: decoder)) + case "minutes": + self = .typeVacationAccountMinutes(try VacationAccountMinutes(from: decoder)) + default: + throw DecodingError.dataCorrupted( + DecodingError.Context( + codingPath: decoder.codingPath, + debugDescription: "Unknown discriminator value '\(discriminatorValue)' for VacationAccount" + ) + ) + } + } +} + diff --git a/sdk/swift/TimrApi/Models/VacationAccountBase.swift b/sdk/swift/TimrApi/Models/VacationAccountBase.swift new file mode 100644 index 0000000..664d644 --- /dev/null +++ b/sdk/swift/TimrApi/Models/VacationAccountBase.swift @@ -0,0 +1,33 @@ +// +// VacationAccountBase.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Members shared by every kind of vacation account, including the discriminator. */ +public struct VacationAccountBase: Codable, JSONEncodable, Hashable { + + public var unit: VacationUnit + + public init(unit: VacationUnit) { + self.unit = unit + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case unit + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(unit, forKey: .unit) + } +} + diff --git a/sdk/swift/TimrApi/Models/VacationAccountDays.swift b/sdk/swift/TimrApi/Models/VacationAccountDays.swift new file mode 100644 index 0000000..5770a74 --- /dev/null +++ b/sdk/swift/TimrApi/Models/VacationAccountDays.swift @@ -0,0 +1,52 @@ +// +// VacationAccountDays.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct VacationAccountDays: Codable, JSONEncodable, Hashable { + + public var unit: VacationUnit + /** vacation balance carried over from the previous vacation period, in days */ + public var balanceLastPeriodDays: Double? + /** vacation consumed in the current vacation period, in days */ + public var consumedDays: Double? + /** vacation newly granted in the current vacation period, in days */ + public var newDays: Double? + /** total vacation balance for the current vacation period, in days */ + public var balanceTotalDays: Double? + + public init(unit: VacationUnit, balanceLastPeriodDays: Double? = nil, consumedDays: Double? = nil, newDays: Double? = nil, balanceTotalDays: Double? = nil) { + self.unit = unit + self.balanceLastPeriodDays = balanceLastPeriodDays + self.consumedDays = consumedDays + self.newDays = newDays + self.balanceTotalDays = balanceTotalDays + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case unit + case balanceLastPeriodDays = "balance_last_period_days" + case consumedDays = "consumed_days" + case newDays = "new_days" + case balanceTotalDays = "balance_total_days" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(unit, forKey: .unit) + try container.encodeIfPresent(balanceLastPeriodDays, forKey: .balanceLastPeriodDays) + try container.encodeIfPresent(consumedDays, forKey: .consumedDays) + try container.encodeIfPresent(newDays, forKey: .newDays) + try container.encodeIfPresent(balanceTotalDays, forKey: .balanceTotalDays) + } +} + diff --git a/sdk/swift/TimrApi/Models/VacationAccountMinutes.swift b/sdk/swift/TimrApi/Models/VacationAccountMinutes.swift new file mode 100644 index 0000000..8a8524d --- /dev/null +++ b/sdk/swift/TimrApi/Models/VacationAccountMinutes.swift @@ -0,0 +1,52 @@ +// +// VacationAccountMinutes.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct VacationAccountMinutes: Codable, JSONEncodable, Hashable { + + public var unit: VacationUnit + /** vacation balance carried over from the previous vacation period, in minutes */ + public var balanceLastPeriodMinutes: Double? + /** vacation consumed in the current vacation period, in minutes */ + public var consumedMinutes: Double? + /** vacation newly granted in the current vacation period, in minutes */ + public var newMinutes: Double? + /** total vacation balance for the current vacation period, in minutes */ + public var balanceTotalMinutes: Double? + + public init(unit: VacationUnit, balanceLastPeriodMinutes: Double? = nil, consumedMinutes: Double? = nil, newMinutes: Double? = nil, balanceTotalMinutes: Double? = nil) { + self.unit = unit + self.balanceLastPeriodMinutes = balanceLastPeriodMinutes + self.consumedMinutes = consumedMinutes + self.newMinutes = newMinutes + self.balanceTotalMinutes = balanceTotalMinutes + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case unit + case balanceLastPeriodMinutes = "balance_last_period_minutes" + case consumedMinutes = "consumed_minutes" + case newMinutes = "new_minutes" + case balanceTotalMinutes = "balance_total_minutes" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(unit, forKey: .unit) + try container.encodeIfPresent(balanceLastPeriodMinutes, forKey: .balanceLastPeriodMinutes) + try container.encodeIfPresent(consumedMinutes, forKey: .consumedMinutes) + try container.encodeIfPresent(newMinutes, forKey: .newMinutes) + try container.encodeIfPresent(balanceTotalMinutes, forKey: .balanceTotalMinutes) + } +} + diff --git a/sdk/swift/TimrApi/Models/VacationUnit.swift b/sdk/swift/TimrApi/Models/VacationUnit.swift new file mode 100644 index 0000000..386ed90 --- /dev/null +++ b/sdk/swift/TimrApi/Models/VacationUnit.swift @@ -0,0 +1,17 @@ +// +// VacationUnit.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Unit a vacation entitlement is expressed in. */ +public enum VacationUnit: String, Codable, CaseIterable { + case days = "days" + case minutes = "minutes" +} diff --git a/sdk/swift/TimrApi/Models/VenuePartial.swift b/sdk/swift/TimrApi/Models/VenuePartial.swift new file mode 100644 index 0000000..f5297d8 --- /dev/null +++ b/sdk/swift/TimrApi/Models/VenuePartial.swift @@ -0,0 +1,70 @@ +// +// VenuePartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct VenuePartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + public var city: String + public var zipCode: String + public var street: String + public var streetNumber: String + public var country: String + /** Latitude in decimal degrees. */ + public var lat: Float? + /** Longitude in decimal degrees. */ + public var lon: Float? + + public init(id: String, name: String, city: String, zipCode: String, street: String, streetNumber: String, country: String, lat: Float? = nil, lon: Float? = nil) { + self.id = id + self.name = name + self.city = city + self.zipCode = zipCode + self.street = street + self.streetNumber = streetNumber + self.country = country + self.lat = lat + self.lon = lon + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case city + case zipCode = "zip_code" + case street + case streetNumber = "street_number" + case country + case lat + case lon + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(city, forKey: .city) + try container.encode(zipCode, forKey: .zipCode) + try container.encode(street, forKey: .street) + try container.encode(streetNumber, forKey: .streetNumber) + try container.encode(country, forKey: .country) + try container.encodeIfPresent(lat, forKey: .lat) + try container.encodeIfPresent(lon, forKey: .lon) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension VenuePartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/Waypoint.swift b/sdk/swift/TimrApi/Models/Waypoint.swift new file mode 100644 index 0000000..01f0645 --- /dev/null +++ b/sdk/swift/TimrApi/Models/Waypoint.swift @@ -0,0 +1,36 @@ +// +// Waypoint.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Waypoint: Codable, JSONEncodable, Hashable { + + public var lat: Double + public var lon: Double + + public init(lat: Double, lon: Double) { + self.lat = lat + self.lon = lon + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case lat + case lon + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(lat, forKey: .lat) + try container.encode(lon, forKey: .lon) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkScheduleModel.swift b/sdk/swift/TimrApi/Models/WorkScheduleModel.swift new file mode 100644 index 0000000..2404fd3 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkScheduleModel.swift @@ -0,0 +1,54 @@ +// +// WorkScheduleModel.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** The weekday targets a user is measured against: `weeks` holds the layout, `type` selects the calculation mode, and `working_time_rules` the recording constraints. */ +public struct WorkScheduleModel: Codable, JSONEncodable, Hashable { + + public var id: String + public var name: String + /** working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks) */ + public var type: WorkScheduleModelType + /** for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name */ + public var weeks: [WorkScheduleModelWeek] + public var workingTimeRules: WorkingTimeRules? + + public init(id: String, name: String, type: WorkScheduleModelType, weeks: [WorkScheduleModelWeek], workingTimeRules: WorkingTimeRules?) { + self.id = id + self.name = name + self.type = type + self.weeks = weeks + self.workingTimeRules = workingTimeRules + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case type + case weeks + case workingTimeRules = "working_time_rules" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(type, forKey: .type) + try container.encode(weeks, forKey: .weeks) + try container.encode(workingTimeRules, forKey: .workingTimeRules) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension WorkScheduleModel: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/WorkScheduleModelPartial.swift b/sdk/swift/TimrApi/Models/WorkScheduleModelPartial.swift new file mode 100644 index 0000000..99e60d5 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkScheduleModelPartial.swift @@ -0,0 +1,40 @@ +// +// WorkScheduleModelPartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkScheduleModelPartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + + public init(id: String, name: String) { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension WorkScheduleModelPartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/WorkScheduleModelSortColumn.swift b/sdk/swift/TimrApi/Models/WorkScheduleModelSortColumn.swift new file mode 100644 index 0000000..ae8626b --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkScheduleModelSortColumn.swift @@ -0,0 +1,16 @@ +// +// WorkScheduleModelSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Work Schedule Models. */ +public enum WorkScheduleModelSortColumn: String, Codable, CaseIterable { + case name = "name" +} diff --git a/sdk/swift/TimrApi/Models/WorkScheduleModelType.swift b/sdk/swift/TimrApi/Models/WorkScheduleModelType.swift new file mode 100644 index 0000000..c58c8cd --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkScheduleModelType.swift @@ -0,0 +1,17 @@ +// +// WorkScheduleModelType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** How the target working time of the model is defined. */ +public enum WorkScheduleModelType: String, Codable, CaseIterable { + case dailyTargetHours = "daily_target_hours" + case normalWorkingTime = "normal_working_time" +} diff --git a/sdk/swift/TimrApi/Models/WorkScheduleModelWeek.swift b/sdk/swift/TimrApi/Models/WorkScheduleModelWeek.swift new file mode 100644 index 0000000..7688983 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkScheduleModelWeek.swift @@ -0,0 +1,71 @@ +// +// WorkScheduleModelWeek.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkScheduleModelWeek: Codable, JSONEncodable, Hashable { + + /** index of the week in alternating_weeks models (0-based); omitted for fixed_week models */ + public var weekNumber: Int? + /** display name of the week in alternating_weeks models; omitted for fixed_week models */ + public var name: String? + /** value in minutes */ + public var targetDurationWeeklyMinutes: Int64 + public var monday: DailyWorkSchedule + public var tuesday: DailyWorkSchedule + public var wednesday: DailyWorkSchedule + public var thursday: DailyWorkSchedule + public var friday: DailyWorkSchedule + public var saturday: DailyWorkSchedule + public var sunday: DailyWorkSchedule + + public init(weekNumber: Int? = nil, name: String? = nil, targetDurationWeeklyMinutes: Int64, monday: DailyWorkSchedule, tuesday: DailyWorkSchedule, wednesday: DailyWorkSchedule, thursday: DailyWorkSchedule, friday: DailyWorkSchedule, saturday: DailyWorkSchedule, sunday: DailyWorkSchedule) { + self.weekNumber = weekNumber + self.name = name + self.targetDurationWeeklyMinutes = targetDurationWeeklyMinutes + self.monday = monday + self.tuesday = tuesday + self.wednesday = wednesday + self.thursday = thursday + self.friday = friday + self.saturday = saturday + self.sunday = sunday + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case weekNumber = "week_number" + case name + case targetDurationWeeklyMinutes = "target_duration_weekly_minutes" + case monday + case tuesday + case wednesday + case thursday + case friday + case saturday + case sunday + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(weekNumber, forKey: .weekNumber) + try container.encodeIfPresent(name, forKey: .name) + try container.encode(targetDurationWeeklyMinutes, forKey: .targetDurationWeeklyMinutes) + try container.encode(monday, forKey: .monday) + try container.encode(tuesday, forKey: .tuesday) + try container.encode(wednesday, forKey: .wednesday) + try container.encode(thursday, forKey: .thursday) + try container.encode(friday, forKey: .friday) + try container.encode(saturday, forKey: .saturday) + try container.encode(sunday, forKey: .sunday) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkScheduleModelsPage.swift b/sdk/swift/TimrApi/Models/WorkScheduleModelsPage.swift new file mode 100644 index 0000000..a64060c --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkScheduleModelsPage.swift @@ -0,0 +1,37 @@ +// +// WorkScheduleModelsPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkScheduleModelsPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [WorkScheduleModel] + + public init(nextPageToken: String?, data: [WorkScheduleModel]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkingTime.swift b/sdk/swift/TimrApi/Models/WorkingTime.swift new file mode 100644 index 0000000..7b263b1 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTime.swift @@ -0,0 +1,114 @@ +// +// WorkingTime.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** One continuous stretch from `start` to `end`, classified by its `working_time_type`. Attendance entries carry `break_times`, locations and the platform they were recorded on; an entry derived from a multi-day absence links back to its `working_time_date_span`. */ +public struct WorkingTime: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + /** RFC 3339 date-time (ISO-8601) */ + public var start: Date + /** RFC 3339 date-time (ISO-8601) */ + public var end: Date? + /** Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties */ + public var breakTimeTotalMinutes: Int + public var breakTimes: [BreakTime] + public var duration: Duration? + public var changed: Bool + public var notes: String? + public var user: UserPartial + public var workingTimeType: WorkingTimeTypePartial + public var workingTimeDateSpan: WorkingTimeDateSpanPartial? + public var startLocation: Location? + public var endLocation: Location? + public var startPlatform: Platform? + public var endPlatform: Platform? + /** Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + public var lastModified: Date + /** Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + public var lastModifiedBy: UserPartial? + public var status: WorkingTimeStatus + public var metadata: [String: AnyCodable]? + + public init(id: String, start: Date, end: Date?, breakTimeTotalMinutes: Int, breakTimes: [BreakTime], duration: Duration?, changed: Bool, notes: String?, user: UserPartial, workingTimeType: WorkingTimeTypePartial, workingTimeDateSpan: WorkingTimeDateSpanPartial?, startLocation: Location?, endLocation: Location?, startPlatform: Platform?, endPlatform: Platform?, lastModified: Date, lastModifiedBy: UserPartial?, status: WorkingTimeStatus, metadata: [String: AnyCodable]? = nil) { + self.id = id + self.start = start + self.end = end + self.breakTimeTotalMinutes = breakTimeTotalMinutes + self.breakTimes = breakTimes + self.duration = duration + self.changed = changed + self.notes = notes + self.user = user + self.workingTimeType = workingTimeType + self.workingTimeDateSpan = workingTimeDateSpan + self.startLocation = startLocation + self.endLocation = endLocation + self.startPlatform = startPlatform + self.endPlatform = endPlatform + self.lastModified = lastModified + self.lastModifiedBy = lastModifiedBy + self.status = status + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case start + case end + case breakTimeTotalMinutes = "break_time_total_minutes" + case breakTimes = "break_times" + case duration + case changed + case notes + case user + case workingTimeType = "working_time_type" + case workingTimeDateSpan = "working_time_date_span" + case startLocation = "start_location" + case endLocation = "end_location" + case startPlatform = "start_platform" + case endPlatform = "end_platform" + case lastModified = "last_modified" + case lastModifiedBy = "last_modified_by" + case status + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(start, forKey: .start) + try container.encode(end, forKey: .end) + try container.encode(breakTimeTotalMinutes, forKey: .breakTimeTotalMinutes) + try container.encode(breakTimes, forKey: .breakTimes) + try container.encode(duration, forKey: .duration) + try container.encode(changed, forKey: .changed) + try container.encode(notes, forKey: .notes) + try container.encode(user, forKey: .user) + try container.encode(workingTimeType, forKey: .workingTimeType) + try container.encode(workingTimeDateSpan, forKey: .workingTimeDateSpan) + try container.encode(startLocation, forKey: .startLocation) + try container.encode(endLocation, forKey: .endLocation) + try container.encode(startPlatform, forKey: .startPlatform) + try container.encode(endPlatform, forKey: .endPlatform) + try container.encode(lastModified, forKey: .lastModified) + try container.encode(lastModifiedBy, forKey: .lastModifiedBy) + try container.encode(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension WorkingTime: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeCreate.swift b/sdk/swift/TimrApi/Models/WorkingTimeCreate.swift new file mode 100644 index 0000000..e13d085 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeCreate.swift @@ -0,0 +1,79 @@ +// +// WorkingTimeCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimeCreate: Codable, JSONEncodable, Hashable { + + /** For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) */ + public var start: Date + /** For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var breakTimes: [BreakTimeUpdate]? + /** Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only */ + public var durationType: DurationType? + public var changed: Bool + public var notes: String? + public var workingTimeTypeId: String + public var status: WorkingTimeStatus + public var metadata: [String: AnyCodable]? + public var userId: String + public var startLocation: LocationCreate? + public var endLocation: LocationCreate? + + public init(start: Date, end: Date? = nil, breakTimes: [BreakTimeUpdate]? = nil, durationType: DurationType? = nil, changed: Bool, notes: String? = nil, workingTimeTypeId: String, status: WorkingTimeStatus, metadata: [String: AnyCodable]? = nil, userId: String, startLocation: LocationCreate? = nil, endLocation: LocationCreate? = nil) { + self.start = start + self.end = end + self.breakTimes = breakTimes + self.durationType = durationType + self.changed = changed + self.notes = notes + self.workingTimeTypeId = workingTimeTypeId + self.status = status + self.metadata = metadata + self.userId = userId + self.startLocation = startLocation + self.endLocation = endLocation + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + case breakTimes = "break_times" + case durationType = "duration_type" + case changed + case notes + case workingTimeTypeId = "working_time_type_id" + case status + case metadata + case userId = "user_id" + case startLocation = "start_location" + case endLocation = "end_location" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + try container.encodeIfPresent(breakTimes, forKey: .breakTimes) + try container.encodeIfPresent(durationType, forKey: .durationType) + try container.encode(changed, forKey: .changed) + try container.encodeIfPresent(notes, forKey: .notes) + try container.encode(workingTimeTypeId, forKey: .workingTimeTypeId) + try container.encode(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encode(userId, forKey: .userId) + try container.encodeIfPresent(startLocation, forKey: .startLocation) + try container.encodeIfPresent(endLocation, forKey: .endLocation) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkingTimeDateSpan.swift b/sdk/swift/TimrApi/Models/WorkingTimeDateSpan.swift new file mode 100644 index 0000000..9466794 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeDateSpan.swift @@ -0,0 +1,87 @@ +// +// WorkingTimeDateSpan.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** A span from `start` to `end` of a single `working_time_type`. Every working time derived for a covered day links back to it via `WorkingTime.working_time_date_span`. It can be created directly or become effective through an approved request. */ +public struct WorkingTimeDateSpan: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + /** RFC 3339 date (ISO-8601) */ + public var start: Date + /** Marks the first day of the working time date span as a half day. */ + public var startHalfDay: Bool + /** RFC 3339 date (ISO-8601) */ + public var end: Date + /** Marks the last day of the working time date span as a half day. */ + public var endHalfDay: Bool + public var notes: String? + public var user: UserPartial + public var workingTimeType: WorkingTimeTypePartial + public var substitute: UserPartial? + /** Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) */ + public var lastModified: Date + /** Read-only. The User who last modified the entry, or null if the change was not made in a user context. */ + public var lastModifiedBy: UserPartial? + public var metadata: [String: AnyCodable]? + + public init(id: String, start: Date, startHalfDay: Bool, end: Date, endHalfDay: Bool, notes: String?, user: UserPartial, workingTimeType: WorkingTimeTypePartial, substitute: UserPartial? = nil, lastModified: Date, lastModifiedBy: UserPartial?, metadata: [String: AnyCodable]? = nil) { + self.id = id + self.start = start + self.startHalfDay = startHalfDay + self.end = end + self.endHalfDay = endHalfDay + self.notes = notes + self.user = user + self.workingTimeType = workingTimeType + self.substitute = substitute + self.lastModified = lastModified + self.lastModifiedBy = lastModifiedBy + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case start + case startHalfDay = "start_half_day" + case end + case endHalfDay = "end_half_day" + case notes + case user + case workingTimeType = "working_time_type" + case substitute + case lastModified = "last_modified" + case lastModifiedBy = "last_modified_by" + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(start, forKey: .start) + try container.encode(startHalfDay, forKey: .startHalfDay) + try container.encode(end, forKey: .end) + try container.encode(endHalfDay, forKey: .endHalfDay) + try container.encode(notes, forKey: .notes) + try container.encode(user, forKey: .user) + try container.encode(workingTimeType, forKey: .workingTimeType) + try container.encodeIfPresent(substitute, forKey: .substitute) + try container.encode(lastModified, forKey: .lastModified) + try container.encode(lastModifiedBy, forKey: .lastModifiedBy) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension WorkingTimeDateSpan: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeDateSpanCreate.swift b/sdk/swift/TimrApi/Models/WorkingTimeDateSpanCreate.swift new file mode 100644 index 0000000..16c301b --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeDateSpanCreate.swift @@ -0,0 +1,66 @@ +// +// WorkingTimeDateSpanCreate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimeDateSpanCreate: Codable, JSONEncodable, Hashable { + + /** RFC 3339 date (ISO-8601) */ + public var start: Date + public var startHalfDay: Bool? + /** RFC 3339 date (ISO-8601) */ + public var end: Date + public var endHalfDay: Bool? + public var notes: String? + public var workingTimeTypeId: String + public var substituteId: String? + public var metadata: [String: AnyCodable]? + public var userId: String + + public init(start: Date, startHalfDay: Bool? = nil, end: Date, endHalfDay: Bool? = nil, notes: String? = nil, workingTimeTypeId: String, substituteId: String? = nil, metadata: [String: AnyCodable]? = nil, userId: String) { + self.start = start + self.startHalfDay = startHalfDay + self.end = end + self.endHalfDay = endHalfDay + self.notes = notes + self.workingTimeTypeId = workingTimeTypeId + self.substituteId = substituteId + self.metadata = metadata + self.userId = userId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case startHalfDay = "start_half_day" + case end + case endHalfDay = "end_half_day" + case notes + case workingTimeTypeId = "working_time_type_id" + case substituteId = "substitute_id" + case metadata + case userId = "user_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(start, forKey: .start) + try container.encodeIfPresent(startHalfDay, forKey: .startHalfDay) + try container.encode(end, forKey: .end) + try container.encodeIfPresent(endHalfDay, forKey: .endHalfDay) + try container.encodeIfPresent(notes, forKey: .notes) + try container.encode(workingTimeTypeId, forKey: .workingTimeTypeId) + try container.encodeIfPresent(substituteId, forKey: .substituteId) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encode(userId, forKey: .userId) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkingTimeDateSpanPage.swift b/sdk/swift/TimrApi/Models/WorkingTimeDateSpanPage.swift new file mode 100644 index 0000000..dfc67a4 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeDateSpanPage.swift @@ -0,0 +1,37 @@ +// +// WorkingTimeDateSpanPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimeDateSpanPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [WorkingTimeDateSpan] + + public init(nextPageToken: String?, data: [WorkingTimeDateSpan]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkingTimeDateSpanPartial.swift b/sdk/swift/TimrApi/Models/WorkingTimeDateSpanPartial.swift new file mode 100644 index 0000000..7c5022c --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeDateSpanPartial.swift @@ -0,0 +1,37 @@ +// +// WorkingTimeDateSpanPartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** References the date span this working time belongs to, if any. All working times generated for a date span reference the same span; working times recorded on their own have none. */ +public struct WorkingTimeDateSpanPartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + + public init(id: String) { + self.id = id + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension WorkingTimeDateSpanPartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeDateSpanUpdate.swift b/sdk/swift/TimrApi/Models/WorkingTimeDateSpanUpdate.swift new file mode 100644 index 0000000..a8c7913 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeDateSpanUpdate.swift @@ -0,0 +1,62 @@ +// +// WorkingTimeDateSpanUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimeDateSpanUpdate: Codable, JSONEncodable, Hashable { + + /** RFC 3339 date (ISO-8601) */ + public var start: Date? + public var startHalfDay: Bool? + /** RFC 3339 date (ISO-8601) */ + public var end: Date? + public var endHalfDay: Bool? + public var notes: String? + public var workingTimeTypeId: String? + public var substituteId: String? + public var metadata: [String: AnyCodable]? + + public init(start: Date? = nil, startHalfDay: Bool? = nil, end: Date? = nil, endHalfDay: Bool? = nil, notes: String? = nil, workingTimeTypeId: String? = nil, substituteId: String? = nil, metadata: [String: AnyCodable]? = nil) { + self.start = start + self.startHalfDay = startHalfDay + self.end = end + self.endHalfDay = endHalfDay + self.notes = notes + self.workingTimeTypeId = workingTimeTypeId + self.substituteId = substituteId + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case startHalfDay = "start_half_day" + case end + case endHalfDay = "end_half_day" + case notes + case workingTimeTypeId = "working_time_type_id" + case substituteId = "substitute_id" + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(start, forKey: .start) + try container.encodeIfPresent(startHalfDay, forKey: .startHalfDay) + try container.encodeIfPresent(end, forKey: .end) + try container.encodeIfPresent(endHalfDay, forKey: .endHalfDay) + try container.encodeIfPresent(notes, forKey: .notes) + try container.encodeIfPresent(workingTimeTypeId, forKey: .workingTimeTypeId) + try container.encodeIfPresent(substituteId, forKey: .substituteId) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkingTimeDateSpansSortColumn.swift b/sdk/swift/TimrApi/Models/WorkingTimeDateSpansSortColumn.swift new file mode 100644 index 0000000..15a1134 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeDateSpansSortColumn.swift @@ -0,0 +1,16 @@ +// +// WorkingTimeDateSpansSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Working Time Date Spans. */ +public enum WorkingTimeDateSpansSortColumn: String, Codable, CaseIterable { + case start = "start" +} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeRules.swift b/sdk/swift/TimrApi/Models/WorkingTimeRules.swift new file mode 100644 index 0000000..4987f44 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeRules.swift @@ -0,0 +1,40 @@ +// +// WorkingTimeRules.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimeRules: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + + public init(id: String, name: String) { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension WorkingTimeRules: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeStatus.swift b/sdk/swift/TimrApi/Models/WorkingTimeStatus.swift new file mode 100644 index 0000000..8b4253c --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeStatus.swift @@ -0,0 +1,22 @@ +// +// WorkingTimeStatus.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Processing state of a Working Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, closed and archived. */ +public enum WorkingTimeStatus: String, Codable, CaseIterable { + case running = "running" + case paused = "paused" + case changeable = "changeable" + case locked = "locked" + case approved = "approved" + case closed = "closed" + case archived = "archived" +} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeType.swift b/sdk/swift/TimrApi/Models/WorkingTimeType.swift new file mode 100644 index 0000000..820bd25 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeType.swift @@ -0,0 +1,79 @@ +// +// WorkingTimeType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** A working time type. `category` and `sub_category` place it in the classification, `edit_unit` decides whether it is recorded by time or by day, and `requires_substitute` governs how it is recorded. */ +public struct WorkingTimeType: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + public var shortName: String? + public var description: String? + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + public var editUnit: DurationUnit + public var category: WorkingTimeTypeCategory + public var subCategory: WorkingTimeTypeSubCategory? + /** Specifies how the user can record this working time type. */ + public var recordingModeUser: RecordingModeUser + public var archived: Bool + public var requiresSubstitute: Bool? + + public init(id: String, name: String, shortName: String?, description: String?, externalId: String?, editUnit: DurationUnit, category: WorkingTimeTypeCategory, subCategory: WorkingTimeTypeSubCategory?, recordingModeUser: RecordingModeUser, archived: Bool, requiresSubstitute: Bool? = nil) { + self.id = id + self.name = name + self.shortName = shortName + self.description = description + self.externalId = externalId + self.editUnit = editUnit + self.category = category + self.subCategory = subCategory + self.recordingModeUser = recordingModeUser + self.archived = archived + self.requiresSubstitute = requiresSubstitute + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case shortName = "short_name" + case description + case externalId = "external_id" + case editUnit = "edit_unit" + case category + case subCategory = "sub_category" + case recordingModeUser = "recording_mode_user" + case archived + case requiresSubstitute = "requires_substitute" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(shortName, forKey: .shortName) + try container.encode(description, forKey: .description) + try container.encode(externalId, forKey: .externalId) + try container.encode(editUnit, forKey: .editUnit) + try container.encode(category, forKey: .category) + try container.encode(subCategory, forKey: .subCategory) + try container.encode(recordingModeUser, forKey: .recordingModeUser) + try container.encode(archived, forKey: .archived) + try container.encodeIfPresent(requiresSubstitute, forKey: .requiresSubstitute) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension WorkingTimeType: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeTypeCategory.swift b/sdk/swift/TimrApi/Models/WorkingTimeTypeCategory.swift new file mode 100644 index 0000000..2142c82 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeTypeCategory.swift @@ -0,0 +1,21 @@ +// +// WorkingTimeTypeCategory.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Category of a Working Time Type. `attendance_time` counts as time at work, the remaining categories describe kinds of absence. */ +public enum WorkingTimeTypeCategory: String, Codable, CaseIterable { + case attendanceTime = "attendance_time" + case vacation = "vacation" + case paidTimeOff = "paid_time_off" + case unpaidTimeOff = "unpaid_time_off" + case suspension = "suspension" + case breakTime = "break_time" +} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeTypePartial.swift b/sdk/swift/TimrApi/Models/WorkingTimeTypePartial.swift new file mode 100644 index 0000000..0579f26 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeTypePartial.swift @@ -0,0 +1,45 @@ +// +// WorkingTimeTypePartial.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimeTypePartial: Codable, JSONEncodable, Hashable { + + /** Unique identifier. Treat it as an opaque string. */ + public var id: String + public var name: String + /** Identifier of the corresponding object in an external system. Set and owned by the client. */ + public var externalId: String? + + public init(id: String, name: String, externalId: String?) { + self.id = id + self.name = name + self.externalId = externalId + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + case externalId = "external_id" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(id, forKey: .id) + try container.encode(name, forKey: .name) + try container.encode(externalId, forKey: .externalId) + } +} + + +@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *) +extension WorkingTimeTypePartial: Identifiable {} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeTypeSubCategory.swift b/sdk/swift/TimrApi/Models/WorkingTimeTypeSubCategory.swift new file mode 100644 index 0000000..2a184d2 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeTypeSubCategory.swift @@ -0,0 +1,20 @@ +// +// WorkingTimeTypeSubCategory.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Further classification of a Working Time Type within its category. */ +public enum WorkingTimeTypeSubCategory: String, Codable, CaseIterable { + case present = "present" + case workFromHome = "work_from_home" + case away = "away" + case activeDrivingTime = "active_driving_time" + case passiveTravellingTime = "passive_travelling_time" +} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeTypesPage.swift b/sdk/swift/TimrApi/Models/WorkingTimeTypesPage.swift new file mode 100644 index 0000000..9562f6b --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeTypesPage.swift @@ -0,0 +1,37 @@ +// +// WorkingTimeTypesPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimeTypesPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [WorkingTimeType] + + public init(nextPageToken: String?, data: [WorkingTimeType]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkingTimeTypesSortColumn.swift b/sdk/swift/TimrApi/Models/WorkingTimeTypesSortColumn.swift new file mode 100644 index 0000000..002a7f6 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeTypesSortColumn.swift @@ -0,0 +1,16 @@ +// +// WorkingTimeTypesSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Working Time Types. */ +public enum WorkingTimeTypesSortColumn: String, Codable, CaseIterable { + case name = "name" +} diff --git a/sdk/swift/TimrApi/Models/WorkingTimeUpdate.swift b/sdk/swift/TimrApi/Models/WorkingTimeUpdate.swift new file mode 100644 index 0000000..27d2e94 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeUpdate.swift @@ -0,0 +1,75 @@ +// +// WorkingTimeUpdate.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimeUpdate: Codable, JSONEncodable, Hashable { + + /** For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) */ + public var start: Date? + /** For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var breakTimes: [BreakTimeUpdate]? + /** Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only */ + public var durationType: DurationType? + public var changed: Bool? + public var notes: String? + public var workingTimeTypeId: String? + public var status: WorkingTimeStatus? + public var metadata: [String: AnyCodable]? + public var startLocation: LocationUpdate? + public var endLocation: LocationUpdate? + + public init(start: Date? = nil, end: Date? = nil, breakTimes: [BreakTimeUpdate]? = nil, durationType: DurationType? = nil, changed: Bool? = nil, notes: String? = nil, workingTimeTypeId: String? = nil, status: WorkingTimeStatus? = nil, metadata: [String: AnyCodable]? = nil, startLocation: LocationUpdate? = nil, endLocation: LocationUpdate? = nil) { + self.start = start + self.end = end + self.breakTimes = breakTimes + self.durationType = durationType + self.changed = changed + self.notes = notes + self.workingTimeTypeId = workingTimeTypeId + self.status = status + self.metadata = metadata + self.startLocation = startLocation + self.endLocation = endLocation + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + case breakTimes = "break_times" + case durationType = "duration_type" + case changed + case notes + case workingTimeTypeId = "working_time_type_id" + case status + case metadata + case startLocation = "start_location" + case endLocation = "end_location" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + try container.encodeIfPresent(breakTimes, forKey: .breakTimes) + try container.encodeIfPresent(durationType, forKey: .durationType) + try container.encodeIfPresent(changed, forKey: .changed) + try container.encodeIfPresent(notes, forKey: .notes) + try container.encodeIfPresent(workingTimeTypeId, forKey: .workingTimeTypeId) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + try container.encodeIfPresent(startLocation, forKey: .startLocation) + try container.encodeIfPresent(endLocation, forKey: .endLocation) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkingTimeUpsert.swift b/sdk/swift/TimrApi/Models/WorkingTimeUpsert.swift new file mode 100644 index 0000000..c95d7e1 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimeUpsert.swift @@ -0,0 +1,67 @@ +// +// WorkingTimeUpsert.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimeUpsert: Codable, JSONEncodable, Hashable { + + /** For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) */ + public var start: Date? + /** For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) */ + public var end: Date? + public var breakTimes: [BreakTimeUpdate]? + /** Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only */ + public var durationType: DurationType? + public var changed: Bool? + public var notes: String? + public var workingTimeTypeId: String? + public var status: WorkingTimeStatus? + public var metadata: [String: AnyCodable]? + + public init(start: Date? = nil, end: Date? = nil, breakTimes: [BreakTimeUpdate]? = nil, durationType: DurationType? = nil, changed: Bool? = nil, notes: String? = nil, workingTimeTypeId: String? = nil, status: WorkingTimeStatus? = nil, metadata: [String: AnyCodable]? = nil) { + self.start = start + self.end = end + self.breakTimes = breakTimes + self.durationType = durationType + self.changed = changed + self.notes = notes + self.workingTimeTypeId = workingTimeTypeId + self.status = status + self.metadata = metadata + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case start + case end + case breakTimes = "break_times" + case durationType = "duration_type" + case changed + case notes + case workingTimeTypeId = "working_time_type_id" + case status + case metadata + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(start, forKey: .start) + try container.encodeIfPresent(end, forKey: .end) + try container.encodeIfPresent(breakTimes, forKey: .breakTimes) + try container.encodeIfPresent(durationType, forKey: .durationType) + try container.encodeIfPresent(changed, forKey: .changed) + try container.encodeIfPresent(notes, forKey: .notes) + try container.encodeIfPresent(workingTimeTypeId, forKey: .workingTimeTypeId) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(metadata, forKey: .metadata) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkingTimesPage.swift b/sdk/swift/TimrApi/Models/WorkingTimesPage.swift new file mode 100644 index 0000000..c988c01 --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimesPage.swift @@ -0,0 +1,37 @@ +// +// WorkingTimesPage.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct WorkingTimesPage: Codable, JSONEncodable, Hashable { + + /** Token for the next page, or null when this is the last page. */ + public var nextPageToken: String? + public var data: [WorkingTime] + + public init(nextPageToken: String?, data: [WorkingTime]) { + self.nextPageToken = nextPageToken + self.data = data + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case nextPageToken = "next_page_token" + case data + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(nextPageToken, forKey: .nextPageToken) + try container.encode(data, forKey: .data) + } +} + diff --git a/sdk/swift/TimrApi/Models/WorkingTimesSortColumn.swift b/sdk/swift/TimrApi/Models/WorkingTimesSortColumn.swift new file mode 100644 index 0000000..76a268f --- /dev/null +++ b/sdk/swift/TimrApi/Models/WorkingTimesSortColumn.swift @@ -0,0 +1,17 @@ +// +// WorkingTimesSortColumn.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Sort property for Working Times. */ +public enum WorkingTimesSortColumn: String, Codable, CaseIterable { + case start = "start" + case lastModified = "last_modified" +} diff --git a/sdk/swift/TimrApi/OpenISO8601DateFormatter.swift b/sdk/swift/TimrApi/OpenISO8601DateFormatter.swift new file mode 100644 index 0000000..cc32888 --- /dev/null +++ b/sdk/swift/TimrApi/OpenISO8601DateFormatter.swift @@ -0,0 +1,56 @@ +// +// OpenISO8601DateFormatter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +// https://stackoverflow.com/a/50281094/976628 +public class OpenISO8601DateFormatter: DateFormatter { + static let withoutSeconds: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + return formatter + }() + + static let withoutTime: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd" + return formatter + }() + + private func setup() { + calendar = Calendar(identifier: .iso8601) + locale = Locale(identifier: "en_US_POSIX") + timeZone = TimeZone(secondsFromGMT: 0) + dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + } + + override init() { + super.init() + setup() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + override public func date(from string: String) -> Date? { + if let result = super.date(from: string) { + return result + } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) { + return result + } + + return OpenISO8601DateFormatter.withoutTime.date(from: string) + } +} diff --git a/sdk/swift/TimrApi/SynchronizedDictionary.swift b/sdk/swift/TimrApi/SynchronizedDictionary.swift new file mode 100644 index 0000000..fbaa624 --- /dev/null +++ b/sdk/swift/TimrApi/SynchronizedDictionary.swift @@ -0,0 +1,26 @@ +// SynchronizedDictionary.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +internal struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let lock = NSRecursiveLock() + + internal subscript(key: K) -> V? { + get { + lock.lock() + defer { lock.unlock() } + return self.dictionary[key] + } + set { + lock.lock() + defer { lock.unlock() } + self.dictionary[key] = newValue + } + } +} diff --git a/sdk/swift/TimrApi/Validation.swift b/sdk/swift/TimrApi/Validation.swift new file mode 100644 index 0000000..3bf4ec0 --- /dev/null +++ b/sdk/swift/TimrApi/Validation.swift @@ -0,0 +1,161 @@ +// Validation.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct StringRule { + public var minLength: Int? + public var maxLength: Int? + public var pattern: String? +} + +public struct NumericRule { + public var minimum: T? + public var exclusiveMinimum = false + public var maximum: T? + public var exclusiveMaximum = false + public var multipleOf: T? +} + +public struct ArrayRule { + public var minItems: Int? + public var maxItems: Int? + public var uniqueItems: Bool +} + +public enum StringValidationErrorKind: Error { + case minLength, maxLength, pattern +} + +public enum NumericValidationErrorKind: Error { + case minimum, maximum, multipleOf +} + +public enum ArrayValidationErrorKind: Error { + case minItems, maxItems, uniqueItems +} + +public struct ValidationError: Error { + public fileprivate(set) var kinds: Set +} + +public struct Validator { + /// Validate a string against a rule. + /// - Parameter string: The String you wish to validate. + /// - Parameter rule: The StringRule you wish to use for validation. + /// - Returns: A validated string. + /// - Throws: `ValidationError` if the string is invalid against the rule, + /// `NSError` if the rule.pattern is invalid. + public static func validate(_ string: String, against rule: StringRule) throws -> String { + var error = ValidationError(kinds: []) + if let minLength = rule.minLength, !(minLength <= string.count) { + error.kinds.insert(.minLength) + } + if let maxLength = rule.maxLength, !(string.count <= maxLength) { + error.kinds.insert(.maxLength) + } + if let pattern = rule.pattern { + let matches = try NSRegularExpression(pattern: pattern, options: .caseInsensitive) + .matches(in: string, range: .init(location: 0, length: string.utf16.count)) + if matches.isEmpty { + error.kinds.insert(.pattern) + } + } + guard error.kinds.isEmpty else { + throw error + } + return string + } + + /// Validate a integer against a rule. + /// - Parameter numeric: The integer you wish to validate. + /// - Parameter rule: The NumericRule you wish to use for validation. + /// - Returns: A validated integer. + /// - Throws: `ValidationError` if the numeric is invalid against the rule. + public static func validate(_ numeric: T, against rule: NumericRule) throws -> T { + var error = ValidationError(kinds: []) + if let minimum = rule.minimum { + if !rule.exclusiveMinimum, minimum > numeric { + error.kinds.insert(.minimum) + } + if rule.exclusiveMinimum, minimum >= numeric { + error.kinds.insert(.minimum) + } + } + if let maximum = rule.maximum { + if !rule.exclusiveMaximum, numeric > maximum { + error.kinds.insert(.maximum) + } + if rule.exclusiveMaximum, numeric >= maximum { + error.kinds.insert(.maximum) + } + } + if let multipleOf = rule.multipleOf, !numeric.isMultiple(of: multipleOf) { + error.kinds.insert(.multipleOf) + } + guard error.kinds.isEmpty else { + throw error + } + return numeric + } + + /// Validate a fractional number against a rule. + /// - Parameter numeric: The fractional number you wish to validate. + /// - Parameter rule: The NumericRule you wish to use for validation. + /// - Returns: A validated fractional number. + /// - Throws: `ValidationError` if the numeric is invalid against the rule. + public static func validate(_ numeric: T, against rule: NumericRule) throws -> T { + var error = ValidationError(kinds: []) + if let minimum = rule.minimum { + if !rule.exclusiveMinimum, minimum > numeric { + error.kinds.insert(.minimum) + } + if rule.exclusiveMinimum, minimum >= numeric { + error.kinds.insert(.minimum) + } + } + if let maximum = rule.maximum { + if !rule.exclusiveMaximum, numeric > maximum { + error.kinds.insert(.maximum) + } + if rule.exclusiveMaximum, numeric >= maximum { + error.kinds.insert(.maximum) + } + } + if let multipleOf = rule.multipleOf, numeric.remainder(dividingBy: multipleOf) != 0 { + error.kinds.insert(.multipleOf) + } + guard error.kinds.isEmpty else { + throw error + } + return numeric + } + + /// Validate a array against a rule. + /// - Parameter array: The Array you wish to validate. + /// - Parameter rule: The ArrayRule you wish to use for validation. + /// - Returns: A validated array. + /// - Throws: `ValidationError` if the string is invalid against the rule. + public static func validate(_ array: Array, against rule: ArrayRule) throws -> Array { + var error = ValidationError(kinds: []) + if let minItems = rule.minItems, !(minItems <= array.count) { + error.kinds.insert(.minItems) + } + if let maxItems = rule.maxItems, !(array.count <= maxItems) { + error.kinds.insert(.maxItems) + } + if rule.uniqueItems { + let unique = Set(array) + if unique.count != array.count { + error.kinds.insert(.uniqueItems) + } + } + guard error.kinds.isEmpty else { + throw error + } + return array + } +} diff --git a/sdk/swift/build.gradle b/sdk/swift/build.gradle new file mode 100644 index 0000000..76af43f --- /dev/null +++ b/sdk/swift/build.gradle @@ -0,0 +1,41 @@ +plugins { + alias(libs.plugins.openapi) + id "swift-library" +} + +// swift5 ties the API class, the Swift module, the SwiftPM package and the podspec filename all to +// projectName. The class should read TimrAPI while the module and pod are TimrApi, so projectName +// supplies the class and moduleName — read by our Package.swift and Podspec templates — supplies the +// packaging identity. +def apiClassPrefix = 'Timr' +def moduleName = 'TimrApi' + +def cleanOpenApiGenerateTask = tasks.register('cleanOpenApiGenerate', Delete) { + delete fileTree("$projectDir/$moduleName") +} + + +openApiGenerate { + generatorName = "swift5" + additionalProperties = [moduleName: moduleName] + library = "alamofire" + outputDir = "$projectDir" + templateDir = "$projectDir/templates" + configOptions = [ + projectName : apiClassPrefix, + library : "alamofire", + responseAs : "AsyncAwait", + swiftPackagePath : moduleName, + podAuthors : "troii Software GmbH", + podSummary : "Official Swift client for the timr API", + podDescription : "Official Swift client for the timr API, generated from its OpenAPI specification.", + podHomepage : "https://developer.timr.com", + podDocumentationURL: "https://developer.timr.com", + podLicense : "'Apache-2.0'", + podSource : "{ :git => 'https://github.com/troii/timr-api.git', :tag => s.version.to_s }" + ] +} + +tasks.named('openApiGenerate').configure { task -> + task.dependsOn(cleanOpenApiGenerateTask) +} diff --git a/sdk/swift/project.yml b/sdk/swift/project.yml new file mode 100644 index 0000000..727c225 --- /dev/null +++ b/sdk/swift/project.yml @@ -0,0 +1,15 @@ +name: TimrApi +targets: + TimrApi: + type: framework + platform: iOS + deploymentTarget: "11.0" + sources: [TimrApi] + info: + path: ./Info.plist + version: 1.0.0 + settings: + APPLICATION_EXTENSION_API_ONLY: true + scheme: {} + dependencies: + - carthage: AnyCodable diff --git a/sdk/swift/templates/APIs.mustache b/sdk/swift/templates/APIs.mustache new file mode 100644 index 0000000..dd10b6c --- /dev/null +++ b/sdk/swift/templates/APIs.mustache @@ -0,0 +1,104 @@ +// APIs.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif{{#useVapor}} +import Vapor +{{/useVapor}} + +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{projectName}}API { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var basePath = "{{{basePath}}}" + {{#useVapor}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var customHeaders: HTTPHeaders = [:] + {{/useVapor}} + {{^useVapor}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var customHeaders: [String: String] = [:] + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var credential: URLCredential?{{#useAlamofire}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory(){{/useAlamofire}}{{#useURLSession}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory(){{/useURLSession}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var apiResponseQueue: DispatchQueue = .main + {{/useVapor}} +}{{^useVapor}} + +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class RequestBuilder { + var credential: URLCredential? + var headers: [String: String] + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let parameters: [String: Any]? + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let method: String + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let URLString: String + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let requestTask: RequestTask = RequestTask() + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let requiresAuthentication: Bool + + /// Optional block to obtain a reference to the request's progress instance when available. + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var onProgressReady: ((Progress) -> Void)? + + required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.headers = headers + self.requiresAuthentication = requiresAuthentication + + addHeaders({{projectName}}API.customHeaders) + } + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addHeaders(_ aHeaders: [String: String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + @discardableResult + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> RequestTask { + return requestTask + } + + {{#useAsyncAwait}} + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + @discardableResult + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute() async throws -> Response { + return try await withTaskCancellationHandler { + try _Concurrency.Task.checkCancellation() + return try await withCheckedThrowingContinuation { continuation in + guard !_Concurrency.Task.isCancelled else { + continuation.resume(throwing: CancellationError()) + return + } + + self.execute { result in + switch result { + case let .success(response): + continuation.resume(returning: response) + case let .failure(error): + continuation.resume(throwing: error) + } + } + } + } onCancel: { + self.requestTask.cancel() + } + } + + {{/useAsyncAwait}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addCredential() -> Self { + credential = {{projectName}}API.credential + return self + } +} + +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +}{{/useVapor}} diff --git a/sdk/typescript-fetch/.gitignore b/sdk/typescript-fetch/.gitignore new file mode 100644 index 0000000..f0cb326 --- /dev/null +++ b/sdk/typescript-fetch/.gitignore @@ -0,0 +1,8 @@ +node_modules +dist +package-lock.json + + + +# OpenApiGenerator generated meta files +.openapi-generator diff --git a/sdk/typescript-fetch/.npmignore b/sdk/typescript-fetch/.npmignore new file mode 100644 index 0000000..42061c0 --- /dev/null +++ b/sdk/typescript-fetch/.npmignore @@ -0,0 +1 @@ +README.md \ No newline at end of file diff --git a/sdk/typescript-fetch/.openapi-generator-ignore b/sdk/typescript-fetch/.openapi-generator-ignore new file mode 100644 index 0000000..3822609 --- /dev/null +++ b/sdk/typescript-fetch/.openapi-generator-ignore @@ -0,0 +1,5 @@ +.gitignore +docs/** +# package.json is hand-maintained: what npm publishes and how is not the generator's business, and +# the version is stamped at publish time from sdk/versions.properties. +package.json diff --git a/sdk/typescript-fetch/README.md b/sdk/typescript-fetch/README.md new file mode 100644 index 0000000..0f20729 --- /dev/null +++ b/sdk/typescript-fetch/README.md @@ -0,0 +1,352 @@ +# timr-api@1.0.0 + +A TypeScript SDK client for the api.timr.com API. + +## Usage + +First, install the SDK from npm. + +```bash +npm install timr-api --save +``` + +Next, try it out. + + +```ts +import { + Configuration, + CarApi, +} from 'timr-api'; +import type { CreateCarRequest } from 'timr-api'; + +async function example() { + console.log("🚀 Testing timr-api SDK..."); + const config = new Configuration({ + // To configure OAuth2 access token for authorization: OAuth2 application + accessToken: "YOUR ACCESS TOKEN", + // To configure OAuth2 access token for authorization: OAuth2 accessCode + accessToken: "YOUR ACCESS TOKEN", + }); + const api = new CarApi(config); + + const body = { + // CarCreate | Car entity + carCreate: ..., + } satisfies CreateCarRequest; + + try { + const data = await api.createCar(body); + console.log(data); + } catch (error) { + console.error(error); + } +} + +// Run the test +example().catch(console.error); +``` + + +## Documentation + +### API Endpoints + +All URIs are relative to *https://api.timr.com/v1* + +| Class | Method | HTTP request | Description +| ----- | ------ | ------------ | ------------- +*CarApi* | [**createCar**](docs/CarApi.md#createcar) | **POST** /cars | Create a Car +*CarApi* | [**fetchCars**](docs/CarApi.md#fetchcars) | **GET** /cars | List Cars +*CarApi* | [**getCar**](docs/CarApi.md#getcar) | **GET** /cars/{id} | Get a Car +*CarApi* | [**updateCar**](docs/CarApi.md#updatecar) | **PATCH** /cars/{id} | Update a Car +*DriveLogApi* | [**createDriveLog**](docs/DriveLogApi.md#createdrivelog) | **POST** /drive-logs | Create a Drive Log +*DriveLogApi* | [**deleteDriveLog**](docs/DriveLogApi.md#deletedrivelog) | **DELETE** /drive-logs/{id} | Delete a Drive Log +*DriveLogApi* | [**fetchDeletedDriveLogs**](docs/DriveLogApi.md#fetchdeleteddrivelogs) | **GET** /drive-logs:deleted | List deleted Drive Logs +*DriveLogApi* | [**fetchDriveLogs**](docs/DriveLogApi.md#fetchdrivelogs) | **GET** /drive-logs | List Drive Logs +*DriveLogApi* | [**getDriveLog**](docs/DriveLogApi.md#getdrivelog) | **GET** /drive-logs/{id} | Get a Drive Log +*DriveLogApi* | [**updateDriveLog**](docs/DriveLogApi.md#updatedrivelog) | **PATCH** /drive-logs/{id} | Update a Drive Log +*DriveLogCategoryApi* | [**fetchDriveLogCategories**](docs/DriveLogCategoryApi.md#fetchdrivelogcategories) | **GET** /drive-log-categories | List Drive Log Categories +*DriveLogCategoryApi* | [**getDriveLogCategory**](docs/DriveLogCategoryApi.md#getdrivelogcategory) | **GET** /drive-log-categories/{id} | Get a Drive Log Category +*HolidayCalendarApi* | [**fetchHolidayCalendars**](docs/HolidayCalendarApi.md#fetchholidaycalendars) | **GET** /holiday-calendars | List Holiday Calendars +*HolidayCalendarApi* | [**fetchHolidays**](docs/HolidayCalendarApi.md#fetchholidays) | **GET** /holiday-calendars/{id}/holidays | List Holidays +*HolidayCalendarApi* | [**getHolidayCalendar**](docs/HolidayCalendarApi.md#getholidaycalendar) | **GET** /holiday-calendars/{id} | Get a Holiday Calendar +*ProjectTimeApi* | [**createProjectTime**](docs/ProjectTimeApi.md#createprojecttime) | **POST** /project-times | Create a Project Time +*ProjectTimeApi* | [**deleteProjectTime**](docs/ProjectTimeApi.md#deleteprojecttime) | **DELETE** /project-times/{id} | Delete a Project Time +*ProjectTimeApi* | [**fetchDeletedProjectTimes**](docs/ProjectTimeApi.md#fetchdeletedprojecttimes) | **GET** /project-times:deleted | List deleted Project Times +*ProjectTimeApi* | [**fetchProjectTimes**](docs/ProjectTimeApi.md#fetchprojecttimes) | **GET** /project-times | List Project Times +*ProjectTimeApi* | [**getProjectTime**](docs/ProjectTimeApi.md#getprojecttime) | **GET** /project-times/{id} | Get a Project Time +*ProjectTimeApi* | [**updateProjectTime**](docs/ProjectTimeApi.md#updateprojecttime) | **PATCH** /project-times/{id} | Update a Project Time +*TaskApi* | [**createTask**](docs/TaskApi.md#createtask) | **POST** /tasks | Create a Task +*TaskApi* | [**fetchTasks**](docs/TaskApi.md#fetchtasks) | **GET** /tasks | List Tasks +*TaskApi* | [**fetchUserTasks**](docs/TaskApi.md#fetchusertasks) | **GET** /users/{id}/tasks | List a User\'s Tasks +*TaskApi* | [**getTask**](docs/TaskApi.md#gettask) | **GET** /tasks/{id} | Get a Task +*TaskApi* | [**updateTask**](docs/TaskApi.md#updatetask) | **PATCH** /tasks/{id} | Update a Task +*TaskToLeaderAssignmentApi* | [**createTaskToLeaderAssignment**](docs/TaskToLeaderAssignmentApi.md#createtasktoleaderassignment) | **PUT** /tasks/{task_id}/leaders/{user_id} | Create a Task to Leader Assignment +*TaskToLeaderAssignmentApi* | [**deleteTaskToLeaderAssignment**](docs/TaskToLeaderAssignmentApi.md#deletetasktoleaderassignment) | **DELETE** /tasks/{task_id}/leaders/{user_id} | Delete a Task to Leader Assignment +*TaskToLeaderAssignmentApi* | [**fetchTaskToLeaderAssignments**](docs/TaskToLeaderAssignmentApi.md#fetchtasktoleaderassignments) | **GET** /tasks/{task_id}/leaders | List Task to Leader Assignments +*TaskToLeaderAssignmentApi* | [**getTaskToLeaderAssignment**](docs/TaskToLeaderAssignmentApi.md#gettasktoleaderassignment) | **GET** /tasks/{task_id}/leaders/{user_id} | Get a Task to Leader Assignment +*TaskToTeamAssignmentApi* | [**createTaskToTeamAssignment**](docs/TaskToTeamAssignmentApi.md#createtasktoteamassignment) | **PUT** /tasks/{task_id}/teams/{team_id} | Create a Task to Team Assignment +*TaskToTeamAssignmentApi* | [**deleteTaskToTeamAssignment**](docs/TaskToTeamAssignmentApi.md#deletetasktoteamassignment) | **DELETE** /tasks/{task_id}/teams/{team_id} | Delete a Task to Team Assignment +*TaskToTeamAssignmentApi* | [**fetchTaskToTeamAssignments**](docs/TaskToTeamAssignmentApi.md#fetchtasktoteamassignments) | **GET** /tasks/{task_id}/teams | List Task to Team Assignments +*TaskToTeamAssignmentApi* | [**getTaskToTeamAssignment**](docs/TaskToTeamAssignmentApi.md#gettasktoteamassignment) | **GET** /tasks/{task_id}/teams/{team_id} | Get a Task to Team Assignment +*TaskToUserAssignmentApi* | [**deleteTaskToUserAssignment**](docs/TaskToUserAssignmentApi.md#deletetasktouserassignment) | **DELETE** /tasks/{task_id}/users/{user_id} | Delete a Task to User Assignment +*TaskToUserAssignmentApi* | [**fetchTaskToUserAssignments**](docs/TaskToUserAssignmentApi.md#fetchtasktouserassignments) | **GET** /tasks/{task_id}/users | List Task to User Assignments +*TaskToUserAssignmentApi* | [**getTaskToUserAssignment**](docs/TaskToUserAssignmentApi.md#gettasktouserassignment) | **GET** /tasks/{task_id}/users/{user_id} | Get a Task to User Assignment +*TaskToUserAssignmentApi* | [**upsertTaskToUserAssignment**](docs/TaskToUserAssignmentApi.md#upserttasktouserassignment) | **PUT** /tasks/{task_id}/users/{user_id} | Create or update a Task to User Assignment +*TeamApi* | [**addTeamLeader**](docs/TeamApi.md#addteamleader) | **PUT** /teams/{team_id}/leaders/{user_id} | Add a Team Leader +*TeamApi* | [**addTeamMember**](docs/TeamApi.md#addteammember) | **PUT** /teams/{team_id}/members/{user_id} | Add a Team Member +*TeamApi* | [**createTeam**](docs/TeamApi.md#createteam) | **POST** /teams | Create a Team +*TeamApi* | [**deleteTeam**](docs/TeamApi.md#deleteteam) | **DELETE** /teams/{id} | Delete a Team +*TeamApi* | [**fetchTeamLeaders**](docs/TeamApi.md#fetchteamleaders) | **GET** /teams/{id}/leaders | List Team Leaders +*TeamApi* | [**fetchTeamMembers**](docs/TeamApi.md#fetchteammembers) | **GET** /teams/{id}/members | List Team Members +*TeamApi* | [**fetchTeams**](docs/TeamApi.md#fetchteams) | **GET** /teams | List Teams +*TeamApi* | [**getTeam**](docs/TeamApi.md#getteam) | **GET** /teams/{id} | Get a Team +*TeamApi* | [**getTeamLeader**](docs/TeamApi.md#getteamleader) | **GET** /teams/{team_id}/leaders/{user_id} | Get a Team Leader +*TeamApi* | [**getTeamMember**](docs/TeamApi.md#getteammember) | **GET** /teams/{team_id}/members/{user_id} | Get a Team Member +*TeamApi* | [**removeTeamLeader**](docs/TeamApi.md#removeteamleader) | **DELETE** /teams/{team_id}/leaders/{user_id} | Remove a Team Leader +*TeamApi* | [**removeTeamMember**](docs/TeamApi.md#removeteammember) | **DELETE** /teams/{team_id}/members/{user_id} | Remove a Team Member +*TeamApi* | [**updateTeam**](docs/TeamApi.md#updateteam) | **PATCH** /teams/{id} | Update a Team +*TimeAccountApi* | [**getUserAccounts**](docs/TimeAccountApi.md#getuseraccounts) | **GET** /users/{id}/accounts/{date} | Get a User\'s accounts +*TimeAccountApi* | [**getUserWorkingTimeAccounts**](docs/TimeAccountApi.md#getuserworkingtimeaccounts) | **GET** /users/{id}/working-time-accounts/{date} | Get a User\'s working time accounts +*TrackApi* | [**createTrack**](docs/TrackApi.md#createtrack) | **POST** /drive-logs/{id}/track | Create a Drive Log\'s Track +*TrackApi* | [**deleteTrack**](docs/TrackApi.md#deletetrack) | **DELETE** /drive-logs/{id}/track | Delete a Drive Log\'s Track +*TrackApi* | [**getTrack**](docs/TrackApi.md#gettrack) | **GET** /drive-logs/{id}/track | Get a Drive Log\'s Track +*TrackApi* | [**updateTrack**](docs/TrackApi.md#updatetrack) | **PUT** /drive-logs/{id}/track | Replace a Drive Log\'s Track +*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** /users | Create a User +*UserApi* | [**fetchUserTeamLeaderships**](docs/UserApi.md#fetchuserteamleaderships) | **GET** /users/{id}/team-leaderships | List a User\'s Team leaderships +*UserApi* | [**fetchUserTeamMemberships**](docs/UserApi.md#fetchuserteammemberships) | **GET** /users/{id}/team-memberships | List a User\'s Team memberships +*UserApi* | [**fetchUsers**](docs/UserApi.md#fetchusers) | **GET** /users | List Users +*UserApi* | [**getUser**](docs/UserApi.md#getuser) | **GET** /users/{id} | Get a User +*UserApi* | [**getUserWorkScheduleModel**](docs/UserApi.md#getuserworkschedulemodel) | **GET** /users/{id}/work-schedule-model | Get a User\'s Work Schedule Model +*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PATCH** /users/{id} | Update a User +*WorkScheduleModelApi* | [**deleteWorkScheduleModel**](docs/WorkScheduleModelApi.md#deleteworkschedulemodel) | **DELETE** /work-schedule-models/{id} | Delete a Work Schedule Model +*WorkScheduleModelApi* | [**fetchWorkScheduleModels**](docs/WorkScheduleModelApi.md#fetchworkschedulemodels) | **GET** /work-schedule-models | List Work Schedule Models +*WorkScheduleModelApi* | [**getWorkScheduleModel**](docs/WorkScheduleModelApi.md#getworkschedulemodel) | **GET** /work-schedule-models/{id} | Get a Work Schedule Model +*WorkingTimeApi* | [**createWorkingTime**](docs/WorkingTimeApi.md#createworkingtime) | **POST** /working-times | Create a Working Time +*WorkingTimeApi* | [**deleteWorkingTime**](docs/WorkingTimeApi.md#deleteworkingtime) | **DELETE** /working-times/{id} | Delete a Working Time +*WorkingTimeApi* | [**fetchDeletedWorkingTimes**](docs/WorkingTimeApi.md#fetchdeletedworkingtimes) | **GET** /working-times:deleted | List deleted Working Times +*WorkingTimeApi* | [**fetchWorkingTimes**](docs/WorkingTimeApi.md#fetchworkingtimes) | **GET** /working-times | List Working Times +*WorkingTimeApi* | [**getWorkingTime**](docs/WorkingTimeApi.md#getworkingtime) | **GET** /working-times/{id} | Get a Working Time +*WorkingTimeApi* | [**updateWorkingTime**](docs/WorkingTimeApi.md#updateworkingtime) | **PATCH** /working-times/{id} | Update a Working Time +*WorkingTimeDateSpanApi* | [**createWorkingTimeDateSpan**](docs/WorkingTimeDateSpanApi.md#createworkingtimedatespan) | **POST** /working-time-date-spans | Create a Working Time Date Span +*WorkingTimeDateSpanApi* | [**deleteWorkingTimeDateSpan**](docs/WorkingTimeDateSpanApi.md#deleteworkingtimedatespan) | **DELETE** /working-time-date-spans/{id} | Delete a Working Time Date Span +*WorkingTimeDateSpanApi* | [**fetchDeletedWorkingTimeDateSpans**](docs/WorkingTimeDateSpanApi.md#fetchdeletedworkingtimedatespans) | **GET** /working-time-date-spans:deleted | List deleted Working Time Date Spans +*WorkingTimeDateSpanApi* | [**fetchWorkingTimeDateSpans**](docs/WorkingTimeDateSpanApi.md#fetchworkingtimedatespans) | **GET** /working-time-date-spans | List Working Time Date Spans +*WorkingTimeDateSpanApi* | [**getWorkingTimeDateSpan**](docs/WorkingTimeDateSpanApi.md#getworkingtimedatespan) | **GET** /working-time-date-spans/{id} | Get a Working Time Date Span +*WorkingTimeDateSpanApi* | [**updateWorkingTimeDateSpan**](docs/WorkingTimeDateSpanApi.md#updateworkingtimedatespan) | **PATCH** /working-time-date-spans/{id} | Update a Working Time Date Span +*WorkingTimeTypeApi* | [**deleteWorkingTimeType**](docs/WorkingTimeTypeApi.md#deleteworkingtimetype) | **DELETE** /working-time-types/{id} | Delete a Working Time Type +*WorkingTimeTypeApi* | [**fetchWorkingTimeTypes**](docs/WorkingTimeTypeApi.md#fetchworkingtimetypes) | **GET** /working-time-types | List Working Time Types +*WorkingTimeTypeApi* | [**getWorkingTimeType**](docs/WorkingTimeTypeApi.md#getworkingtimetype) | **GET** /working-time-types/{id} | Get a Working Time Type + + +### Models + +- [Accounts](docs/Accounts.md) +- [BreakTime](docs/BreakTime.md) +- [BreakTimeAutomatic](docs/BreakTimeAutomatic.md) +- [BreakTimeBase](docs/BreakTimeBase.md) +- [BreakTimeManual](docs/BreakTimeManual.md) +- [BreakTimeOngoing](docs/BreakTimeOngoing.md) +- [BreakTimeType](docs/BreakTimeType.md) +- [BreakTimeUpdate](docs/BreakTimeUpdate.md) +- [BudgetPlanningType](docs/BudgetPlanningType.md) +- [BudgetPlanningTypeRequest](docs/BudgetPlanningTypeRequest.md) +- [Car](docs/Car.md) +- [CarCreate](docs/CarCreate.md) +- [CarPartial](docs/CarPartial.md) +- [CarUpdate](docs/CarUpdate.md) +- [CarsPage](docs/CarsPage.md) +- [CarsSortColumn](docs/CarsSortColumn.md) +- [DailyWorkSchedule](docs/DailyWorkSchedule.md) +- [DeletedEntryPage](docs/DeletedEntryPage.md) +- [DeletedEntryPartial](docs/DeletedEntryPartial.md) +- [DeletedEntrySortColumn](docs/DeletedEntrySortColumn.md) +- [DeletedEntryWithMetadata](docs/DeletedEntryWithMetadata.md) +- [DeletedEntryWithMetadataPage](docs/DeletedEntryWithMetadataPage.md) +- [DriveLog](docs/DriveLog.md) +- [DriveLogCategoriesPage](docs/DriveLogCategoriesPage.md) +- [DriveLogCategoriesSortColumn](docs/DriveLogCategoriesSortColumn.md) +- [DriveLogCategory](docs/DriveLogCategory.md) +- [DriveLogCategoryPartial](docs/DriveLogCategoryPartial.md) +- [DriveLogCreate](docs/DriveLogCreate.md) +- [DriveLogStatus](docs/DriveLogStatus.md) +- [DriveLogUpdate](docs/DriveLogUpdate.md) +- [DriveLogUpsert](docs/DriveLogUpsert.md) +- [DriveLogsPage](docs/DriveLogsPage.md) +- [DriveLogsSortColumn](docs/DriveLogsSortColumn.md) +- [Duration](docs/Duration.md) +- [DurationType](docs/DurationType.md) +- [DurationUnit](docs/DurationUnit.md) +- [ErrorEntry](docs/ErrorEntry.md) +- [FlexTimeIndicator](docs/FlexTimeIndicator.md) +- [Holiday](docs/Holiday.md) +- [HolidayCalendarPartial](docs/HolidayCalendarPartial.md) +- [HolidayCalendarsPage](docs/HolidayCalendarsPage.md) +- [HolidayCalendarsSortColumn](docs/HolidayCalendarsSortColumn.md) +- [HolidaysPage](docs/HolidaysPage.md) +- [HolidaysSortColumn](docs/HolidaysSortColumn.md) +- [Location](docs/Location.md) +- [LocationCreate](docs/LocationCreate.md) +- [LocationUpdate](docs/LocationUpdate.md) +- [ModelError](docs/ModelError.md) +- [NormalWorkingTimes](docs/NormalWorkingTimes.md) +- [OvertimeSurchargeAccount](docs/OvertimeSurchargeAccount.md) +- [OvertimeSurchargeAccounts](docs/OvertimeSurchargeAccounts.md) +- [OvertimeSurchargeRule](docs/OvertimeSurchargeRule.md) +- [PagingInformation](docs/PagingInformation.md) +- [Platform](docs/Platform.md) +- [ProblemDetail](docs/ProblemDetail.md) +- [ProjectTime](docs/ProjectTime.md) +- [ProjectTimeCreate](docs/ProjectTimeCreate.md) +- [ProjectTimeStatus](docs/ProjectTimeStatus.md) +- [ProjectTimeUpdate](docs/ProjectTimeUpdate.md) +- [ProjectTimeUpsert](docs/ProjectTimeUpsert.md) +- [ProjectTimesPage](docs/ProjectTimesPage.md) +- [ProjectTimesSortColumn](docs/ProjectTimesSortColumn.md) +- [RecordingLockType](docs/RecordingLockType.md) +- [RecordingModeUser](docs/RecordingModeUser.md) +- [SortDirection](docs/SortDirection.md) +- [Task](docs/Task.md) +- [TaskBase](docs/TaskBase.md) +- [TaskCreate](docs/TaskCreate.md) +- [TaskLocation](docs/TaskLocation.md) +- [TaskPartial](docs/TaskPartial.md) +- [TaskReduced](docs/TaskReduced.md) +- [TaskToLeaderAssignment](docs/TaskToLeaderAssignment.md) +- [TaskToLeaderAssignmentsPage](docs/TaskToLeaderAssignmentsPage.md) +- [TaskToLeaderAssignmentsSortColumn](docs/TaskToLeaderAssignmentsSortColumn.md) +- [TaskToTeamAssignment](docs/TaskToTeamAssignment.md) +- [TaskToTeamAssignmentsPage](docs/TaskToTeamAssignmentsPage.md) +- [TaskToTeamAssignmentsSortColumn](docs/TaskToTeamAssignmentsSortColumn.md) +- [TaskToUserAssignment](docs/TaskToUserAssignment.md) +- [TaskToUserAssignmentUpsert](docs/TaskToUserAssignmentUpsert.md) +- [TaskToUserAssignmentsPage](docs/TaskToUserAssignmentsPage.md) +- [TaskToUserAssignmentsSortColumn](docs/TaskToUserAssignmentsSortColumn.md) +- [TaskUpdate](docs/TaskUpdate.md) +- [TasksPage](docs/TasksPage.md) +- [TasksReducedPage](docs/TasksReducedPage.md) +- [TasksSortColumn](docs/TasksSortColumn.md) +- [Team](docs/Team.md) +- [TeamCreate](docs/TeamCreate.md) +- [TeamPartial](docs/TeamPartial.md) +- [TeamUpdate](docs/TeamUpdate.md) +- [TeamsPage](docs/TeamsPage.md) +- [TeamsPartialPage](docs/TeamsPartialPage.md) +- [TeamsSortColumn](docs/TeamsSortColumn.md) +- [TimeAccount](docs/TimeAccount.md) +- [User](docs/User.md) +- [UserCreate](docs/UserCreate.md) +- [UserPartial](docs/UserPartial.md) +- [UserUpdate](docs/UserUpdate.md) +- [UsersPage](docs/UsersPage.md) +- [UsersPartialPage](docs/UsersPartialPage.md) +- [UsersSortColumn](docs/UsersSortColumn.md) +- [VacationAccount](docs/VacationAccount.md) +- [VacationAccountBase](docs/VacationAccountBase.md) +- [VacationAccountDays](docs/VacationAccountDays.md) +- [VacationAccountMinutes](docs/VacationAccountMinutes.md) +- [VacationUnit](docs/VacationUnit.md) +- [VenuePartial](docs/VenuePartial.md) +- [Waypoint](docs/Waypoint.md) +- [WorkScheduleModel](docs/WorkScheduleModel.md) +- [WorkScheduleModelPartial](docs/WorkScheduleModelPartial.md) +- [WorkScheduleModelSortColumn](docs/WorkScheduleModelSortColumn.md) +- [WorkScheduleModelType](docs/WorkScheduleModelType.md) +- [WorkScheduleModelWeek](docs/WorkScheduleModelWeek.md) +- [WorkScheduleModelsPage](docs/WorkScheduleModelsPage.md) +- [WorkingTime](docs/WorkingTime.md) +- [WorkingTimeCreate](docs/WorkingTimeCreate.md) +- [WorkingTimeDateSpan](docs/WorkingTimeDateSpan.md) +- [WorkingTimeDateSpanCreate](docs/WorkingTimeDateSpanCreate.md) +- [WorkingTimeDateSpanPage](docs/WorkingTimeDateSpanPage.md) +- [WorkingTimeDateSpanPartial](docs/WorkingTimeDateSpanPartial.md) +- [WorkingTimeDateSpanUpdate](docs/WorkingTimeDateSpanUpdate.md) +- [WorkingTimeDateSpansSortColumn](docs/WorkingTimeDateSpansSortColumn.md) +- [WorkingTimeRules](docs/WorkingTimeRules.md) +- [WorkingTimeStatus](docs/WorkingTimeStatus.md) +- [WorkingTimeType](docs/WorkingTimeType.md) +- [WorkingTimeTypeCategory](docs/WorkingTimeTypeCategory.md) +- [WorkingTimeTypePartial](docs/WorkingTimeTypePartial.md) +- [WorkingTimeTypeSubCategory](docs/WorkingTimeTypeSubCategory.md) +- [WorkingTimeTypesPage](docs/WorkingTimeTypesPage.md) +- [WorkingTimeTypesSortColumn](docs/WorkingTimeTypesSortColumn.md) +- [WorkingTimeUpdate](docs/WorkingTimeUpdate.md) +- [WorkingTimeUpsert](docs/WorkingTimeUpsert.md) +- [WorkingTimesPage](docs/WorkingTimesPage.md) +- [WorkingTimesSortColumn](docs/WorkingTimesSortColumn.md) + +### Authorization + + +Authentication schemes defined for the API: + +#### OAuth2 application + + +- **Type**: OAuth +- **Flow**: application +- **Authorization URL**: +- **Scopes**: + - `openid`: Authenticate the OAuth client. + - `timrclient`: Access timr data in the client context. + +#### OAuth2 accessCode + + +- **Type**: OAuth +- **Flow**: accessCode +- **Authorization URL**: https://system.timr.com/id/oauth2/authorize +- **Scopes**: + - `openid`: Authenticate the timr user. + - `offline_access`: Request a refresh token for continued access. + +## About + +This TypeScript SDK client supports the [Fetch API](https://fetch.spec.whatwg.org/) +and is automatically generated by the +[OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: `1.0.0` +- Package version: `1.0.0` +- Generator version: `7.22.0` +- Build package: `org.openapitools.codegen.languages.TypeScriptFetchClientCodegen` + +The generated npm module supports the following: + +- Environments + * Node.js + * Webpack + * Browserify +- Language levels + * ES5 - you must have a Promises/A+ library installed + * ES6 +- Module systems + * CommonJS + * ES6 module system + +For more information, please visit [https://www.timr.com](https://www.timr.com) + +## Development + +### Building + +To build the TypeScript source code, you need to have Node.js and npm installed. +After cloning the repository, navigate to the project directory and run: + +```bash +npm install +npm run build +``` + +### Publishing + +Once you've built the package, you can publish it to npm: + +```bash +npm publish +``` + +## License + +[Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.html) diff --git a/sdk/typescript-fetch/build.gradle b/sdk/typescript-fetch/build.gradle new file mode 100644 index 0000000..14d3c1a --- /dev/null +++ b/sdk/typescript-fetch/build.gradle @@ -0,0 +1,26 @@ +plugins { + alias(libs.plugins.openapi) +} + +openApiGenerate { + generatorName = 'typescript-fetch' + gitHost = 'github.com' + gitUserId = 'troii' + gitRepoId = 'timr-api' + outputDir = "$projectDir" + additionalProperties = [ + npmName : 'timr-api', + licenseName : 'Apache-2.0', + npmVersion : project.version, + supportsES6 : 'true' + ] +} + +tasks.register('cleanOpenApiGenerate', Delete) { + delete fileTree("$projectDir/src/apis") + delete fileTree("$projectDir/src/models") +} + +tasks.named('openApiGenerate').configure { task -> + task.dependsOn('cleanOpenApiGenerate') +} diff --git a/sdk/typescript-fetch/package.json b/sdk/typescript-fetch/package.json new file mode 100644 index 0000000..a06d880 --- /dev/null +++ b/sdk/typescript-fetch/package.json @@ -0,0 +1,23 @@ +{ + "name": "timr-api", + "version": "1.0.0", + "description": "Official TypeScript client for the timr API", + "author": "troii Software GmbH", + "homepage": "https://developer.timr.com", + "repository": { + "type": "git", + "url": "https://github.com/troii/timr-api.git" + }, + "license": "Apache-2.0", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "module": "./dist/esm/index.js", + "sideEffects": false, + "scripts": { + "build": "tsc && tsc -p tsconfig.esm.json", + "prepare": "npm run build" + }, + "devDependencies": { + "typescript": "^4.0 || ^5.0" + } +} diff --git a/sdk/typescript-fetch/src/apis/CarApi.ts b/sdk/typescript-fetch/src/apis/CarApi.ts new file mode 100644 index 0000000..349fdad --- /dev/null +++ b/sdk/typescript-fetch/src/apis/CarApi.ts @@ -0,0 +1,330 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type Car, + CarFromJSON, + CarToJSON, +} from '../models/Car'; +import { + type CarCreate, + CarCreateFromJSON, + CarCreateToJSON, +} from '../models/CarCreate'; +import { + type CarUpdate, + CarUpdateFromJSON, + CarUpdateToJSON, +} from '../models/CarUpdate'; +import { + type CarsPage, + CarsPageFromJSON, + CarsPageToJSON, +} from '../models/CarsPage'; +import { + type CarsSortColumn, + CarsSortColumnFromJSON, + CarsSortColumnToJSON, +} from '../models/CarsSortColumn'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; + +export interface CreateCarRequest { + carCreate: CarCreate; +} + +export interface FetchCarsRequest { + nameOrPlate?: string; + usable?: boolean; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: CarsSortColumn; +} + +export interface GetCarRequest { + id: string; +} + +export interface UpdateCarRequest { + id: string; + carUpdate: CarUpdate; +} + +/** + * + */ +export class CarApi extends runtime.BaseAPI { + + /** + * Creates request options for createCar without sending the request + */ + async createCarRequestOpts(requestParameters: CreateCarRequest): Promise { + if (requestParameters['carCreate'] == null) { + throw new runtime.RequiredError( + 'carCreate', + 'Required parameter "carCreate" was null or undefined when calling createCar().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/cars`; + + return { + path: urlPath, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: CarCreateToJSON(requestParameters['carCreate']), + }; + } + + /** + * Creates a Car from the data in the request body. + * Create a Car + */ + async createCarRaw(requestParameters: CreateCarRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createCarRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => CarFromJSON(jsonValue)); + } + + /** + * Creates a Car from the data in the request body. + * Create a Car + */ + async createCar(requestParameters: CreateCarRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createCarRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchCars without sending the request + */ + async fetchCarsRequestOpts(requestParameters: FetchCarsRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['nameOrPlate'] != null) { + queryParameters['name_or_plate'] = requestParameters['nameOrPlate']; + } + + if (requestParameters['usable'] != null) { + queryParameters['usable'] = requestParameters['usable']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/cars`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Cars the authenticated user or API token can access. + * List Cars + */ + async fetchCarsRaw(requestParameters: FetchCarsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchCarsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => CarsPageFromJSON(jsonValue)); + } + + /** + * Lists the Cars the authenticated user or API token can access. + * List Cars + */ + async fetchCars(requestParameters: FetchCarsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchCarsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getCar without sending the request + */ + async getCarRequestOpts(requestParameters: GetCarRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getCar().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/cars/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Car by its ID. + * Get a Car + */ + async getCarRaw(requestParameters: GetCarRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getCarRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => CarFromJSON(jsonValue)); + } + + /** + * Returns a single Car by its ID. + * Get a Car + */ + async getCar(requestParameters: GetCarRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getCarRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for updateCar without sending the request + */ + async updateCarRequestOpts(requestParameters: UpdateCarRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling updateCar().' + ); + } + + if (requestParameters['carUpdate'] == null) { + throw new runtime.RequiredError( + 'carUpdate', + 'Required parameter "carUpdate" was null or undefined when calling updateCar().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/cars/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'PATCH', + headers: headerParameters, + query: queryParameters, + body: CarUpdateToJSON(requestParameters['carUpdate']), + }; + } + + /** + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Car + */ + async updateCarRaw(requestParameters: UpdateCarRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.updateCarRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => CarFromJSON(jsonValue)); + } + + /** + * Updates the Car with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Car + */ + async updateCar(requestParameters: UpdateCarRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.updateCarRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/DriveLogApi.ts b/sdk/typescript-fetch/src/apis/DriveLogApi.ts new file mode 100644 index 0000000..64e9793 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/DriveLogApi.ts @@ -0,0 +1,522 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type DeletedEntryPage, + DeletedEntryPageFromJSON, + DeletedEntryPageToJSON, +} from '../models/DeletedEntryPage'; +import { + type DeletedEntrySortColumn, + DeletedEntrySortColumnFromJSON, + DeletedEntrySortColumnToJSON, +} from '../models/DeletedEntrySortColumn'; +import { + type DriveLog, + DriveLogFromJSON, + DriveLogToJSON, +} from '../models/DriveLog'; +import { + type DriveLogCreate, + DriveLogCreateFromJSON, + DriveLogCreateToJSON, +} from '../models/DriveLogCreate'; +import { + type DriveLogStatus, + DriveLogStatusFromJSON, + DriveLogStatusToJSON, +} from '../models/DriveLogStatus'; +import { + type DriveLogUpdate, + DriveLogUpdateFromJSON, + DriveLogUpdateToJSON, +} from '../models/DriveLogUpdate'; +import { + type DriveLogsPage, + DriveLogsPageFromJSON, + DriveLogsPageToJSON, +} from '../models/DriveLogsPage'; +import { + type DriveLogsSortColumn, + DriveLogsSortColumnFromJSON, + DriveLogsSortColumnToJSON, +} from '../models/DriveLogsSortColumn'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; + +export interface CreateDriveLogRequest { + driveLogCreate: DriveLogCreate; +} + +export interface DeleteDriveLogRequest { + id: string; +} + +export interface FetchDeletedDriveLogsRequest { + lastModifiedAfter?: Date; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: DeletedEntrySortColumn; +} + +export interface FetchDriveLogsRequest { + startFrom?: Date; + startTo?: Date; + lastModifiedAfter?: Date; + cars?: Array; + driveLogCategories?: Array; + statuses?: Array; + users?: Array; + details?: string; + changed?: boolean; + hasTrack?: boolean; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: DriveLogsSortColumn; +} + +export interface GetDriveLogRequest { + id: string; +} + +export interface UpdateDriveLogRequest { + id: string; + driveLogUpdate: DriveLogUpdate; +} + +/** + * + */ +export class DriveLogApi extends runtime.BaseAPI { + + /** + * Creates request options for createDriveLog without sending the request + */ + async createDriveLogRequestOpts(requestParameters: CreateDriveLogRequest): Promise { + if (requestParameters['driveLogCreate'] == null) { + throw new runtime.RequiredError( + 'driveLogCreate', + 'Required parameter "driveLogCreate" was null or undefined when calling createDriveLog().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs`; + + return { + path: urlPath, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: DriveLogCreateToJSON(requestParameters['driveLogCreate']), + }; + } + + /** + * Creates a Drive Log from the data in the request body. + * Create a Drive Log + */ + async createDriveLogRaw(requestParameters: CreateDriveLogRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createDriveLogRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DriveLogFromJSON(jsonValue)); + } + + /** + * Creates a Drive Log from the data in the request body. + * Create a Drive Log + */ + async createDriveLog(requestParameters: CreateDriveLogRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createDriveLogRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for deleteDriveLog without sending the request + */ + async deleteDriveLogRequestOpts(requestParameters: DeleteDriveLogRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling deleteDriveLog().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Deletes the Drive Log, including its Track. + * Delete a Drive Log + */ + async deleteDriveLogRaw(requestParameters: DeleteDriveLogRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteDriveLogRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes the Drive Log, including its Track. + * Delete a Drive Log + */ + async deleteDriveLog(requestParameters: DeleteDriveLogRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteDriveLogRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchDeletedDriveLogs without sending the request + */ + async fetchDeletedDriveLogsRequestOpts(requestParameters: FetchDeletedDriveLogsRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['lastModifiedAfter'] != null) { + queryParameters['last_modified_after'] = (requestParameters['lastModifiedAfter'] as any).toISOString(); + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs:deleted`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + * List deleted Drive Logs + */ + async fetchDeletedDriveLogsRaw(requestParameters: FetchDeletedDriveLogsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchDeletedDriveLogsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DeletedEntryPageFromJSON(jsonValue)); + } + + /** + * Lists Drive Logs that were deleted, so a client holding a local copy can reconcile. + * List deleted Drive Logs + */ + async fetchDeletedDriveLogs(requestParameters: FetchDeletedDriveLogsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchDeletedDriveLogsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchDriveLogs without sending the request + */ + async fetchDriveLogsRequestOpts(requestParameters: FetchDriveLogsRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['startFrom'] != null) { + queryParameters['start_from'] = (requestParameters['startFrom'] as any).toISOString().substring(0,10); + } + + if (requestParameters['startTo'] != null) { + queryParameters['start_to'] = (requestParameters['startTo'] as any).toISOString().substring(0,10); + } + + if (requestParameters['lastModifiedAfter'] != null) { + queryParameters['last_modified_after'] = (requestParameters['lastModifiedAfter'] as any).toISOString(); + } + + if (requestParameters['cars'] != null) { + queryParameters['cars'] = requestParameters['cars']; + } + + if (requestParameters['driveLogCategories'] != null) { + queryParameters['drive_log_categories'] = requestParameters['driveLogCategories']; + } + + if (requestParameters['statuses'] != null) { + queryParameters['statuses'] = requestParameters['statuses']; + } + + if (requestParameters['users'] != null) { + queryParameters['users'] = requestParameters['users']; + } + + if (requestParameters['details'] != null) { + queryParameters['details'] = requestParameters['details']; + } + + if (requestParameters['changed'] != null) { + queryParameters['changed'] = requestParameters['changed']; + } + + if (requestParameters['hasTrack'] != null) { + queryParameters['has_track'] = requestParameters['hasTrack']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Drive Logs the authenticated user or API token can access. + * List Drive Logs + */ + async fetchDriveLogsRaw(requestParameters: FetchDriveLogsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchDriveLogsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DriveLogsPageFromJSON(jsonValue)); + } + + /** + * Lists the Drive Logs the authenticated user or API token can access. + * List Drive Logs + */ + async fetchDriveLogs(requestParameters: FetchDriveLogsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchDriveLogsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getDriveLog without sending the request + */ + async getDriveLogRequestOpts(requestParameters: GetDriveLogRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getDriveLog().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Drive Log by its ID. + * Get a Drive Log + */ + async getDriveLogRaw(requestParameters: GetDriveLogRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getDriveLogRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DriveLogFromJSON(jsonValue)); + } + + /** + * Returns a single Drive Log by its ID. + * Get a Drive Log + */ + async getDriveLog(requestParameters: GetDriveLogRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getDriveLogRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for updateDriveLog without sending the request + */ + async updateDriveLogRequestOpts(requestParameters: UpdateDriveLogRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling updateDriveLog().' + ); + } + + if (requestParameters['driveLogUpdate'] == null) { + throw new runtime.RequiredError( + 'driveLogUpdate', + 'Required parameter "driveLogUpdate" was null or undefined when calling updateDriveLog().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'PATCH', + headers: headerParameters, + query: queryParameters, + body: DriveLogUpdateToJSON(requestParameters['driveLogUpdate']), + }; + } + + /** + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Drive Log + */ + async updateDriveLogRaw(requestParameters: UpdateDriveLogRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.updateDriveLogRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DriveLogFromJSON(jsonValue)); + } + + /** + * Updates the Drive Log with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Drive Log + */ + async updateDriveLog(requestParameters: UpdateDriveLogRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.updateDriveLogRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/DriveLogCategoryApi.ts b/sdk/typescript-fetch/src/apis/DriveLogCategoryApi.ts new file mode 100644 index 0000000..208eee3 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/DriveLogCategoryApi.ts @@ -0,0 +1,175 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type DriveLogCategoriesPage, + DriveLogCategoriesPageFromJSON, + DriveLogCategoriesPageToJSON, +} from '../models/DriveLogCategoriesPage'; +import { + type DriveLogCategoriesSortColumn, + DriveLogCategoriesSortColumnFromJSON, + DriveLogCategoriesSortColumnToJSON, +} from '../models/DriveLogCategoriesSortColumn'; +import { + type DriveLogCategory, + DriveLogCategoryFromJSON, + DriveLogCategoryToJSON, +} from '../models/DriveLogCategory'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; + +export interface FetchDriveLogCategoriesRequest { + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: DriveLogCategoriesSortColumn; +} + +export interface GetDriveLogCategoryRequest { + id: string; +} + +/** + * + */ +export class DriveLogCategoryApi extends runtime.BaseAPI { + + /** + * Creates request options for fetchDriveLogCategories without sending the request + */ + async fetchDriveLogCategoriesRequestOpts(requestParameters: FetchDriveLogCategoriesRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-log-categories`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Drive Log Categories the authenticated user or API token can access. + * List Drive Log Categories + */ + async fetchDriveLogCategoriesRaw(requestParameters: FetchDriveLogCategoriesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchDriveLogCategoriesRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DriveLogCategoriesPageFromJSON(jsonValue)); + } + + /** + * Lists the Drive Log Categories the authenticated user or API token can access. + * List Drive Log Categories + */ + async fetchDriveLogCategories(requestParameters: FetchDriveLogCategoriesRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchDriveLogCategoriesRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getDriveLogCategory without sending the request + */ + async getDriveLogCategoryRequestOpts(requestParameters: GetDriveLogCategoryRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getDriveLogCategory().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-log-categories/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Drive Log Category by its ID. + * Get a Drive Log Category + */ + async getDriveLogCategoryRaw(requestParameters: GetDriveLogCategoryRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getDriveLogCategoryRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DriveLogCategoryFromJSON(jsonValue)); + } + + /** + * Returns a single Drive Log Category by its ID. + * Get a Drive Log Category + */ + async getDriveLogCategory(requestParameters: GetDriveLogCategoryRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getDriveLogCategoryRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/HolidayCalendarApi.ts b/sdk/typescript-fetch/src/apis/HolidayCalendarApi.ts new file mode 100644 index 0000000..12c7e99 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/HolidayCalendarApi.ts @@ -0,0 +1,266 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type HolidayCalendarPartial, + HolidayCalendarPartialFromJSON, + HolidayCalendarPartialToJSON, +} from '../models/HolidayCalendarPartial'; +import { + type HolidayCalendarsPage, + HolidayCalendarsPageFromJSON, + HolidayCalendarsPageToJSON, +} from '../models/HolidayCalendarsPage'; +import { + type HolidayCalendarsSortColumn, + HolidayCalendarsSortColumnFromJSON, + HolidayCalendarsSortColumnToJSON, +} from '../models/HolidayCalendarsSortColumn'; +import { + type HolidaysPage, + HolidaysPageFromJSON, + HolidaysPageToJSON, +} from '../models/HolidaysPage'; +import { + type HolidaysSortColumn, + HolidaysSortColumnFromJSON, + HolidaysSortColumnToJSON, +} from '../models/HolidaysSortColumn'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; + +export interface FetchHolidayCalendarsRequest { + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: HolidayCalendarsSortColumn; +} + +export interface FetchHolidaysRequest { + id: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: HolidaysSortColumn; +} + +export interface GetHolidayCalendarRequest { + id: string; +} + +/** + * + */ +export class HolidayCalendarApi extends runtime.BaseAPI { + + /** + * Creates request options for fetchHolidayCalendars without sending the request + */ + async fetchHolidayCalendarsRequestOpts(requestParameters: FetchHolidayCalendarsRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/holiday-calendars`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Holiday Calendars the authenticated user or API token can access. + * List Holiday Calendars + */ + async fetchHolidayCalendarsRaw(requestParameters: FetchHolidayCalendarsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchHolidayCalendarsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => HolidayCalendarsPageFromJSON(jsonValue)); + } + + /** + * Lists the Holiday Calendars the authenticated user or API token can access. + * List Holiday Calendars + */ + async fetchHolidayCalendars(requestParameters: FetchHolidayCalendarsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchHolidayCalendarsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchHolidays without sending the request + */ + async fetchHolidaysRequestOpts(requestParameters: FetchHolidaysRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling fetchHolidays().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/holiday-calendars/{id}/holidays`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Holidays in the Holiday Calendar. + * List Holidays + */ + async fetchHolidaysRaw(requestParameters: FetchHolidaysRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchHolidaysRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => HolidaysPageFromJSON(jsonValue)); + } + + /** + * Lists the Holidays in the Holiday Calendar. + * List Holidays + */ + async fetchHolidays(requestParameters: FetchHolidaysRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchHolidaysRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getHolidayCalendar without sending the request + */ + async getHolidayCalendarRequestOpts(requestParameters: GetHolidayCalendarRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getHolidayCalendar().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/holiday-calendars/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Holiday Calendar by its ID. + * Get a Holiday Calendar + */ + async getHolidayCalendarRaw(requestParameters: GetHolidayCalendarRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getHolidayCalendarRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => HolidayCalendarPartialFromJSON(jsonValue)); + } + + /** + * Returns a single Holiday Calendar by its ID. + * Get a Holiday Calendar + */ + async getHolidayCalendar(requestParameters: GetHolidayCalendarRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getHolidayCalendarRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/ProjectTimeApi.ts b/sdk/typescript-fetch/src/apis/ProjectTimeApi.ts new file mode 100644 index 0000000..5105d9e --- /dev/null +++ b/sdk/typescript-fetch/src/apis/ProjectTimeApi.ts @@ -0,0 +1,522 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type DeletedEntrySortColumn, + DeletedEntrySortColumnFromJSON, + DeletedEntrySortColumnToJSON, +} from '../models/DeletedEntrySortColumn'; +import { + type DeletedEntryWithMetadataPage, + DeletedEntryWithMetadataPageFromJSON, + DeletedEntryWithMetadataPageToJSON, +} from '../models/DeletedEntryWithMetadataPage'; +import { + type ProjectTime, + ProjectTimeFromJSON, + ProjectTimeToJSON, +} from '../models/ProjectTime'; +import { + type ProjectTimeCreate, + ProjectTimeCreateFromJSON, + ProjectTimeCreateToJSON, +} from '../models/ProjectTimeCreate'; +import { + type ProjectTimeStatus, + ProjectTimeStatusFromJSON, + ProjectTimeStatusToJSON, +} from '../models/ProjectTimeStatus'; +import { + type ProjectTimeUpdate, + ProjectTimeUpdateFromJSON, + ProjectTimeUpdateToJSON, +} from '../models/ProjectTimeUpdate'; +import { + type ProjectTimesPage, + ProjectTimesPageFromJSON, + ProjectTimesPageToJSON, +} from '../models/ProjectTimesPage'; +import { + type ProjectTimesSortColumn, + ProjectTimesSortColumnFromJSON, + ProjectTimesSortColumnToJSON, +} from '../models/ProjectTimesSortColumn'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; + +export interface CreateProjectTimeRequest { + projectTimeCreate: ProjectTimeCreate; +} + +export interface DeleteProjectTimeRequest { + id: string; +} + +export interface FetchDeletedProjectTimesRequest { + lastModifiedAfter?: Date; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: DeletedEntrySortColumn; +} + +export interface FetchProjectTimesRequest { + notes?: string; + startFrom?: Date; + startTo?: Date; + lastModifiedAfter?: Date; + task?: string; + traverseTaskTree?: boolean; + billable?: boolean; + statuses?: Array; + users?: Array; + changed?: boolean; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: ProjectTimesSortColumn; +} + +export interface GetProjectTimeRequest { + id: string; +} + +export interface UpdateProjectTimeRequest { + id: string; + projectTimeUpdate: ProjectTimeUpdate; +} + +/** + * + */ +export class ProjectTimeApi extends runtime.BaseAPI { + + /** + * Creates request options for createProjectTime without sending the request + */ + async createProjectTimeRequestOpts(requestParameters: CreateProjectTimeRequest): Promise { + if (requestParameters['projectTimeCreate'] == null) { + throw new runtime.RequiredError( + 'projectTimeCreate', + 'Required parameter "projectTimeCreate" was null or undefined when calling createProjectTime().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/project-times`; + + return { + path: urlPath, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: ProjectTimeCreateToJSON(requestParameters['projectTimeCreate']), + }; + } + + /** + * Creates a Project Time from the data in the request body. + * Create a Project Time + */ + async createProjectTimeRaw(requestParameters: CreateProjectTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createProjectTimeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ProjectTimeFromJSON(jsonValue)); + } + + /** + * Creates a Project Time from the data in the request body. + * Create a Project Time + */ + async createProjectTime(requestParameters: CreateProjectTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createProjectTimeRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for deleteProjectTime without sending the request + */ + async deleteProjectTimeRequestOpts(requestParameters: DeleteProjectTimeRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling deleteProjectTime().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/project-times/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Deletes the Project Time. + * Delete a Project Time + */ + async deleteProjectTimeRaw(requestParameters: DeleteProjectTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteProjectTimeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes the Project Time. + * Delete a Project Time + */ + async deleteProjectTime(requestParameters: DeleteProjectTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteProjectTimeRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchDeletedProjectTimes without sending the request + */ + async fetchDeletedProjectTimesRequestOpts(requestParameters: FetchDeletedProjectTimesRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['lastModifiedAfter'] != null) { + queryParameters['last_modified_after'] = (requestParameters['lastModifiedAfter'] as any).toISOString(); + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/project-times:deleted`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + * List deleted Project Times + */ + async fetchDeletedProjectTimesRaw(requestParameters: FetchDeletedProjectTimesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchDeletedProjectTimesRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DeletedEntryWithMetadataPageFromJSON(jsonValue)); + } + + /** + * Lists Project Times that were deleted, so a client holding a local copy can reconcile. + * List deleted Project Times + */ + async fetchDeletedProjectTimes(requestParameters: FetchDeletedProjectTimesRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchDeletedProjectTimesRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchProjectTimes without sending the request + */ + async fetchProjectTimesRequestOpts(requestParameters: FetchProjectTimesRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['notes'] != null) { + queryParameters['notes'] = requestParameters['notes']; + } + + if (requestParameters['startFrom'] != null) { + queryParameters['start_from'] = (requestParameters['startFrom'] as any).toISOString().substring(0,10); + } + + if (requestParameters['startTo'] != null) { + queryParameters['start_to'] = (requestParameters['startTo'] as any).toISOString().substring(0,10); + } + + if (requestParameters['lastModifiedAfter'] != null) { + queryParameters['last_modified_after'] = (requestParameters['lastModifiedAfter'] as any).toISOString(); + } + + if (requestParameters['task'] != null) { + queryParameters['task'] = requestParameters['task']; + } + + if (requestParameters['traverseTaskTree'] != null) { + queryParameters['traverse_task_tree'] = requestParameters['traverseTaskTree']; + } + + if (requestParameters['billable'] != null) { + queryParameters['billable'] = requestParameters['billable']; + } + + if (requestParameters['statuses'] != null) { + queryParameters['statuses'] = requestParameters['statuses']; + } + + if (requestParameters['users'] != null) { + queryParameters['users'] = requestParameters['users']; + } + + if (requestParameters['changed'] != null) { + queryParameters['changed'] = requestParameters['changed']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/project-times`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Project Times the authenticated user or API token can access. + * List Project Times + */ + async fetchProjectTimesRaw(requestParameters: FetchProjectTimesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchProjectTimesRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ProjectTimesPageFromJSON(jsonValue)); + } + + /** + * Lists the Project Times the authenticated user or API token can access. + * List Project Times + */ + async fetchProjectTimes(requestParameters: FetchProjectTimesRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchProjectTimesRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getProjectTime without sending the request + */ + async getProjectTimeRequestOpts(requestParameters: GetProjectTimeRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getProjectTime().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/project-times/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Project Time by its ID. + * Get a Project Time + */ + async getProjectTimeRaw(requestParameters: GetProjectTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getProjectTimeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ProjectTimeFromJSON(jsonValue)); + } + + /** + * Returns a single Project Time by its ID. + * Get a Project Time + */ + async getProjectTime(requestParameters: GetProjectTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getProjectTimeRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for updateProjectTime without sending the request + */ + async updateProjectTimeRequestOpts(requestParameters: UpdateProjectTimeRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling updateProjectTime().' + ); + } + + if (requestParameters['projectTimeUpdate'] == null) { + throw new runtime.RequiredError( + 'projectTimeUpdate', + 'Required parameter "projectTimeUpdate" was null or undefined when calling updateProjectTime().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/project-times/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'PATCH', + headers: headerParameters, + query: queryParameters, + body: ProjectTimeUpdateToJSON(requestParameters['projectTimeUpdate']), + }; + } + + /** + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Project Time + */ + async updateProjectTimeRaw(requestParameters: UpdateProjectTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.updateProjectTimeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ProjectTimeFromJSON(jsonValue)); + } + + /** + * Updates the Project Time with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Project Time + */ + async updateProjectTime(requestParameters: UpdateProjectTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.updateProjectTimeRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/TaskApi.ts b/sdk/typescript-fetch/src/apis/TaskApi.ts new file mode 100644 index 0000000..48eaa15 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/TaskApi.ts @@ -0,0 +1,466 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type Task, + TaskFromJSON, + TaskToJSON, +} from '../models/Task'; +import { + type TaskCreate, + TaskCreateFromJSON, + TaskCreateToJSON, +} from '../models/TaskCreate'; +import { + type TaskUpdate, + TaskUpdateFromJSON, + TaskUpdateToJSON, +} from '../models/TaskUpdate'; +import { + type TasksPage, + TasksPageFromJSON, + TasksPageToJSON, +} from '../models/TasksPage'; +import { + type TasksReducedPage, + TasksReducedPageFromJSON, + TasksReducedPageToJSON, +} from '../models/TasksReducedPage'; +import { + type TasksSortColumn, + TasksSortColumnFromJSON, + TasksSortColumnToJSON, +} from '../models/TasksSortColumn'; + +export interface CreateTaskRequest { + taskCreate: TaskCreate; +} + +export interface FetchTasksRequest { + parentTaskId?: string; + traverseTaskTree?: boolean; + name?: string; + bookable?: boolean; + billable?: boolean; + activeAt?: Date; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: TasksSortColumn; +} + +export interface FetchUserTasksRequest { + id: string; + parentTaskId?: string; + traverseTaskTree?: boolean; + name?: string; + bookable?: boolean; + billable?: boolean; + activeAt?: Date; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: TasksSortColumn; +} + +export interface GetTaskRequest { + id: string; +} + +export interface UpdateTaskRequest { + id: string; + taskUpdate: TaskUpdate; +} + +/** + * + */ +export class TaskApi extends runtime.BaseAPI { + + /** + * Creates request options for createTask without sending the request + */ + async createTaskRequestOpts(requestParameters: CreateTaskRequest): Promise { + if (requestParameters['taskCreate'] == null) { + throw new runtime.RequiredError( + 'taskCreate', + 'Required parameter "taskCreate" was null or undefined when calling createTask().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks`; + + return { + path: urlPath, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: TaskCreateToJSON(requestParameters['taskCreate']), + }; + } + + /** + * Creates a Task from the data in the request body. + * Create a Task + */ + async createTaskRaw(requestParameters: CreateTaskRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createTaskRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskFromJSON(jsonValue)); + } + + /** + * Creates a Task from the data in the request body. + * Create a Task + */ + async createTask(requestParameters: CreateTaskRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createTaskRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchTasks without sending the request + */ + async fetchTasksRequestOpts(requestParameters: FetchTasksRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['parentTaskId'] != null) { + queryParameters['parent_task_id'] = requestParameters['parentTaskId']; + } + + if (requestParameters['traverseTaskTree'] != null) { + queryParameters['traverse_task_tree'] = requestParameters['traverseTaskTree']; + } + + if (requestParameters['name'] != null) { + queryParameters['name'] = requestParameters['name']; + } + + if (requestParameters['bookable'] != null) { + queryParameters['bookable'] = requestParameters['bookable']; + } + + if (requestParameters['billable'] != null) { + queryParameters['billable'] = requestParameters['billable']; + } + + if (requestParameters['activeAt'] != null) { + queryParameters['active_at'] = requestParameters['activeAt']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Tasks the authenticated user or API token can access. + * List Tasks + */ + async fetchTasksRaw(requestParameters: FetchTasksRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchTasksRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TasksPageFromJSON(jsonValue)); + } + + /** + * Lists the Tasks the authenticated user or API token can access. + * List Tasks + */ + async fetchTasks(requestParameters: FetchTasksRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchTasksRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchUserTasks without sending the request + */ + async fetchUserTasksRequestOpts(requestParameters: FetchUserTasksRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling fetchUserTasks().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['parentTaskId'] != null) { + queryParameters['parent_task_id'] = requestParameters['parentTaskId']; + } + + if (requestParameters['traverseTaskTree'] != null) { + queryParameters['traverse_task_tree'] = requestParameters['traverseTaskTree']; + } + + if (requestParameters['name'] != null) { + queryParameters['name'] = requestParameters['name']; + } + + if (requestParameters['bookable'] != null) { + queryParameters['bookable'] = requestParameters['bookable']; + } + + if (requestParameters['billable'] != null) { + queryParameters['billable'] = requestParameters['billable']; + } + + if (requestParameters['activeAt'] != null) { + queryParameters['active_at'] = requestParameters['activeAt']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users/{id}/tasks`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Tasks the User is assigned to and may record on. + * List a User\'s Tasks + */ + async fetchUserTasksRaw(requestParameters: FetchUserTasksRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchUserTasksRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TasksReducedPageFromJSON(jsonValue)); + } + + /** + * Lists the Tasks the User is assigned to and may record on. + * List a User\'s Tasks + */ + async fetchUserTasks(requestParameters: FetchUserTasksRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchUserTasksRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getTask without sending the request + */ + async getTaskRequestOpts(requestParameters: GetTaskRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getTask().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Task by its ID. + * Get a Task + */ + async getTaskRaw(requestParameters: GetTaskRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getTaskRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskFromJSON(jsonValue)); + } + + /** + * Returns a single Task by its ID. + * Get a Task + */ + async getTask(requestParameters: GetTaskRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getTaskRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for updateTask without sending the request + */ + async updateTaskRequestOpts(requestParameters: UpdateTaskRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling updateTask().' + ); + } + + if (requestParameters['taskUpdate'] == null) { + throw new runtime.RequiredError( + 'taskUpdate', + 'Required parameter "taskUpdate" was null or undefined when calling updateTask().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'PATCH', + headers: headerParameters, + query: queryParameters, + body: TaskUpdateToJSON(requestParameters['taskUpdate']), + }; + } + + /** + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Task + */ + async updateTaskRaw(requestParameters: UpdateTaskRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.updateTaskRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskFromJSON(jsonValue)); + } + + /** + * Updates the Task with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Task + */ + async updateTask(requestParameters: UpdateTaskRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.updateTaskRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/TaskToLeaderAssignmentApi.ts b/sdk/typescript-fetch/src/apis/TaskToLeaderAssignmentApi.ts new file mode 100644 index 0000000..0e4d06c --- /dev/null +++ b/sdk/typescript-fetch/src/apis/TaskToLeaderAssignmentApi.ts @@ -0,0 +1,332 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type TaskToLeaderAssignment, + TaskToLeaderAssignmentFromJSON, + TaskToLeaderAssignmentToJSON, +} from '../models/TaskToLeaderAssignment'; +import { + type TaskToLeaderAssignmentsPage, + TaskToLeaderAssignmentsPageFromJSON, + TaskToLeaderAssignmentsPageToJSON, +} from '../models/TaskToLeaderAssignmentsPage'; +import { + type TaskToLeaderAssignmentsSortColumn, + TaskToLeaderAssignmentsSortColumnFromJSON, + TaskToLeaderAssignmentsSortColumnToJSON, +} from '../models/TaskToLeaderAssignmentsSortColumn'; + +export interface CreateTaskToLeaderAssignmentRequest { + taskId: string; + userId: string; +} + +export interface DeleteTaskToLeaderAssignmentRequest { + taskId: string; + userId: string; +} + +export interface FetchTaskToLeaderAssignmentsRequest { + taskId: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: TaskToLeaderAssignmentsSortColumn; +} + +export interface GetTaskToLeaderAssignmentRequest { + taskId: string; + userId: string; +} + +/** + * + */ +export class TaskToLeaderAssignmentApi extends runtime.BaseAPI { + + /** + * Creates request options for createTaskToLeaderAssignment without sending the request + */ + async createTaskToLeaderAssignmentRequestOpts(requestParameters: CreateTaskToLeaderAssignmentRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling createTaskToLeaderAssignment().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling createTaskToLeaderAssignment().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/leaders/{user_id}`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + * Create a Task to Leader Assignment + */ + async createTaskToLeaderAssignmentRaw(requestParameters: CreateTaskToLeaderAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createTaskToLeaderAssignmentRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskToLeaderAssignmentFromJSON(jsonValue)); + } + + /** + * Assigns the User to the Task as a leader. Returns 201 when the assignment is created and 200 when it already existed. + * Create a Task to Leader Assignment + */ + async createTaskToLeaderAssignment(requestParameters: CreateTaskToLeaderAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createTaskToLeaderAssignmentRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for deleteTaskToLeaderAssignment without sending the request + */ + async deleteTaskToLeaderAssignmentRequestOpts(requestParameters: DeleteTaskToLeaderAssignmentRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling deleteTaskToLeaderAssignment().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling deleteTaskToLeaderAssignment().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/leaders/{user_id}`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Removes the User\'s leader assignment to the Task. + * Delete a Task to Leader Assignment + */ + async deleteTaskToLeaderAssignmentRaw(requestParameters: DeleteTaskToLeaderAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteTaskToLeaderAssignmentRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Removes the User\'s leader assignment to the Task. + * Delete a Task to Leader Assignment + */ + async deleteTaskToLeaderAssignment(requestParameters: DeleteTaskToLeaderAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteTaskToLeaderAssignmentRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchTaskToLeaderAssignments without sending the request + */ + async fetchTaskToLeaderAssignmentsRequestOpts(requestParameters: FetchTaskToLeaderAssignmentsRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling fetchTaskToLeaderAssignments().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/leaders`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Users assigned to the Task as leaders. + * List Task to Leader Assignments + */ + async fetchTaskToLeaderAssignmentsRaw(requestParameters: FetchTaskToLeaderAssignmentsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchTaskToLeaderAssignmentsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskToLeaderAssignmentsPageFromJSON(jsonValue)); + } + + /** + * Lists the Users assigned to the Task as leaders. + * List Task to Leader Assignments + */ + async fetchTaskToLeaderAssignments(requestParameters: FetchTaskToLeaderAssignmentsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchTaskToLeaderAssignmentsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getTaskToLeaderAssignment without sending the request + */ + async getTaskToLeaderAssignmentRequestOpts(requestParameters: GetTaskToLeaderAssignmentRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling getTaskToLeaderAssignment().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling getTaskToLeaderAssignment().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/leaders/{user_id}`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns the leader assignment of a single User to the Task. + * Get a Task to Leader Assignment + */ + async getTaskToLeaderAssignmentRaw(requestParameters: GetTaskToLeaderAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getTaskToLeaderAssignmentRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskToLeaderAssignmentFromJSON(jsonValue)); + } + + /** + * Returns the leader assignment of a single User to the Task. + * Get a Task to Leader Assignment + */ + async getTaskToLeaderAssignment(requestParameters: GetTaskToLeaderAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getTaskToLeaderAssignmentRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/TaskToTeamAssignmentApi.ts b/sdk/typescript-fetch/src/apis/TaskToTeamAssignmentApi.ts new file mode 100644 index 0000000..64bb090 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/TaskToTeamAssignmentApi.ts @@ -0,0 +1,332 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type TaskToTeamAssignment, + TaskToTeamAssignmentFromJSON, + TaskToTeamAssignmentToJSON, +} from '../models/TaskToTeamAssignment'; +import { + type TaskToTeamAssignmentsPage, + TaskToTeamAssignmentsPageFromJSON, + TaskToTeamAssignmentsPageToJSON, +} from '../models/TaskToTeamAssignmentsPage'; +import { + type TaskToTeamAssignmentsSortColumn, + TaskToTeamAssignmentsSortColumnFromJSON, + TaskToTeamAssignmentsSortColumnToJSON, +} from '../models/TaskToTeamAssignmentsSortColumn'; + +export interface CreateTaskToTeamAssignmentRequest { + taskId: string; + teamId: string; +} + +export interface DeleteTaskToTeamAssignmentRequest { + taskId: string; + teamId: string; +} + +export interface FetchTaskToTeamAssignmentsRequest { + taskId: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: TaskToTeamAssignmentsSortColumn; +} + +export interface GetTaskToTeamAssignmentRequest { + taskId: string; + teamId: string; +} + +/** + * + */ +export class TaskToTeamAssignmentApi extends runtime.BaseAPI { + + /** + * Creates request options for createTaskToTeamAssignment without sending the request + */ + async createTaskToTeamAssignmentRequestOpts(requestParameters: CreateTaskToTeamAssignmentRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling createTaskToTeamAssignment().' + ); + } + + if (requestParameters['teamId'] == null) { + throw new runtime.RequiredError( + 'teamId', + 'Required parameter "teamId" was null or undefined when calling createTaskToTeamAssignment().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/teams/{team_id}`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + urlPath = urlPath.replace('{team_id}', encodeURIComponent(String(requestParameters['teamId']))); + + return { + path: urlPath, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + * Create a Task to Team Assignment + */ + async createTaskToTeamAssignmentRaw(requestParameters: CreateTaskToTeamAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createTaskToTeamAssignmentRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskToTeamAssignmentFromJSON(jsonValue)); + } + + /** + * Assigns the Team to the Task. Returns 201 when the assignment is created and 200 when it already existed. + * Create a Task to Team Assignment + */ + async createTaskToTeamAssignment(requestParameters: CreateTaskToTeamAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createTaskToTeamAssignmentRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for deleteTaskToTeamAssignment without sending the request + */ + async deleteTaskToTeamAssignmentRequestOpts(requestParameters: DeleteTaskToTeamAssignmentRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling deleteTaskToTeamAssignment().' + ); + } + + if (requestParameters['teamId'] == null) { + throw new runtime.RequiredError( + 'teamId', + 'Required parameter "teamId" was null or undefined when calling deleteTaskToTeamAssignment().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/teams/{team_id}`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + urlPath = urlPath.replace('{team_id}', encodeURIComponent(String(requestParameters['teamId']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Removes the Team\'s assignment to the Task. + * Delete a Task to Team Assignment + */ + async deleteTaskToTeamAssignmentRaw(requestParameters: DeleteTaskToTeamAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteTaskToTeamAssignmentRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Removes the Team\'s assignment to the Task. + * Delete a Task to Team Assignment + */ + async deleteTaskToTeamAssignment(requestParameters: DeleteTaskToTeamAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteTaskToTeamAssignmentRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchTaskToTeamAssignments without sending the request + */ + async fetchTaskToTeamAssignmentsRequestOpts(requestParameters: FetchTaskToTeamAssignmentsRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling fetchTaskToTeamAssignments().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/teams`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Teams assigned to the Task. + * List Task to Team Assignments + */ + async fetchTaskToTeamAssignmentsRaw(requestParameters: FetchTaskToTeamAssignmentsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchTaskToTeamAssignmentsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskToTeamAssignmentsPageFromJSON(jsonValue)); + } + + /** + * Lists the Teams assigned to the Task. + * List Task to Team Assignments + */ + async fetchTaskToTeamAssignments(requestParameters: FetchTaskToTeamAssignmentsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchTaskToTeamAssignmentsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getTaskToTeamAssignment without sending the request + */ + async getTaskToTeamAssignmentRequestOpts(requestParameters: GetTaskToTeamAssignmentRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling getTaskToTeamAssignment().' + ); + } + + if (requestParameters['teamId'] == null) { + throw new runtime.RequiredError( + 'teamId', + 'Required parameter "teamId" was null or undefined when calling getTaskToTeamAssignment().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/teams/{team_id}`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + urlPath = urlPath.replace('{team_id}', encodeURIComponent(String(requestParameters['teamId']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns the assignment of a single Team to the Task. + * Get a Task to Team Assignment + */ + async getTaskToTeamAssignmentRaw(requestParameters: GetTaskToTeamAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getTaskToTeamAssignmentRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskToTeamAssignmentFromJSON(jsonValue)); + } + + /** + * Returns the assignment of a single Team to the Task. + * Get a Task to Team Assignment + */ + async getTaskToTeamAssignment(requestParameters: GetTaskToTeamAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getTaskToTeamAssignmentRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/TaskToUserAssignmentApi.ts b/sdk/typescript-fetch/src/apis/TaskToUserAssignmentApi.ts new file mode 100644 index 0000000..cf75da6 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/TaskToUserAssignmentApi.ts @@ -0,0 +1,348 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type TaskToUserAssignment, + TaskToUserAssignmentFromJSON, + TaskToUserAssignmentToJSON, +} from '../models/TaskToUserAssignment'; +import { + type TaskToUserAssignmentUpsert, + TaskToUserAssignmentUpsertFromJSON, + TaskToUserAssignmentUpsertToJSON, +} from '../models/TaskToUserAssignmentUpsert'; +import { + type TaskToUserAssignmentsPage, + TaskToUserAssignmentsPageFromJSON, + TaskToUserAssignmentsPageToJSON, +} from '../models/TaskToUserAssignmentsPage'; +import { + type TaskToUserAssignmentsSortColumn, + TaskToUserAssignmentsSortColumnFromJSON, + TaskToUserAssignmentsSortColumnToJSON, +} from '../models/TaskToUserAssignmentsSortColumn'; + +export interface DeleteTaskToUserAssignmentRequest { + taskId: string; + userId: string; +} + +export interface FetchTaskToUserAssignmentsRequest { + taskId: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: TaskToUserAssignmentsSortColumn; +} + +export interface GetTaskToUserAssignmentRequest { + taskId: string; + userId: string; +} + +export interface UpsertTaskToUserAssignmentRequest { + taskId: string; + userId: string; + taskToUserAssignmentUpsert: TaskToUserAssignmentUpsert; +} + +/** + * + */ +export class TaskToUserAssignmentApi extends runtime.BaseAPI { + + /** + * Creates request options for deleteTaskToUserAssignment without sending the request + */ + async deleteTaskToUserAssignmentRequestOpts(requestParameters: DeleteTaskToUserAssignmentRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling deleteTaskToUserAssignment().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling deleteTaskToUserAssignment().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/users/{user_id}`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Removes the User\'s assignment to the Task. + * Delete a Task to User Assignment + */ + async deleteTaskToUserAssignmentRaw(requestParameters: DeleteTaskToUserAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteTaskToUserAssignmentRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Removes the User\'s assignment to the Task. + * Delete a Task to User Assignment + */ + async deleteTaskToUserAssignment(requestParameters: DeleteTaskToUserAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteTaskToUserAssignmentRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchTaskToUserAssignments without sending the request + */ + async fetchTaskToUserAssignmentsRequestOpts(requestParameters: FetchTaskToUserAssignmentsRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling fetchTaskToUserAssignments().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/users`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + * List Task to User Assignments + */ + async fetchTaskToUserAssignmentsRaw(requestParameters: FetchTaskToUserAssignmentsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchTaskToUserAssignmentsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskToUserAssignmentsPageFromJSON(jsonValue)); + } + + /** + * Lists the Users assigned to the Task, together with the budget and recording settings of each assignment. + * List Task to User Assignments + */ + async fetchTaskToUserAssignments(requestParameters: FetchTaskToUserAssignmentsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchTaskToUserAssignmentsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getTaskToUserAssignment without sending the request + */ + async getTaskToUserAssignmentRequestOpts(requestParameters: GetTaskToUserAssignmentRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling getTaskToUserAssignment().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling getTaskToUserAssignment().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/users/{user_id}`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns the assignment of a single User to the Task. + * Get a Task to User Assignment + */ + async getTaskToUserAssignmentRaw(requestParameters: GetTaskToUserAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getTaskToUserAssignmentRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskToUserAssignmentFromJSON(jsonValue)); + } + + /** + * Returns the assignment of a single User to the Task. + * Get a Task to User Assignment + */ + async getTaskToUserAssignment(requestParameters: GetTaskToUserAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getTaskToUserAssignmentRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for upsertTaskToUserAssignment without sending the request + */ + async upsertTaskToUserAssignmentRequestOpts(requestParameters: UpsertTaskToUserAssignmentRequest): Promise { + if (requestParameters['taskId'] == null) { + throw new runtime.RequiredError( + 'taskId', + 'Required parameter "taskId" was null or undefined when calling upsertTaskToUserAssignment().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling upsertTaskToUserAssignment().' + ); + } + + if (requestParameters['taskToUserAssignmentUpsert'] == null) { + throw new runtime.RequiredError( + 'taskToUserAssignmentUpsert', + 'Required parameter "taskToUserAssignmentUpsert" was null or undefined when calling upsertTaskToUserAssignment().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{task_id}/users/{user_id}`; + urlPath = urlPath.replace('{task_id}', encodeURIComponent(String(requestParameters['taskId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: TaskToUserAssignmentUpsertToJSON(requestParameters['taskToUserAssignmentUpsert']), + }; + } + + /** + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + * Create or update a Task to User Assignment + */ + async upsertTaskToUserAssignmentRaw(requestParameters: UpsertTaskToUserAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.upsertTaskToUserAssignmentRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TaskToUserAssignmentFromJSON(jsonValue)); + } + + /** + * Assigns the User to the Task, or updates the existing assignment. Returns 201 when the assignment is created and 200 when it already existed. On update, only the properties present in the request body change. + * Create or update a Task to User Assignment + */ + async upsertTaskToUserAssignment(requestParameters: UpsertTaskToUserAssignmentRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.upsertTaskToUserAssignmentRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/TeamApi.ts b/sdk/typescript-fetch/src/apis/TeamApi.ts new file mode 100644 index 0000000..34e36db --- /dev/null +++ b/sdk/typescript-fetch/src/apis/TeamApi.ts @@ -0,0 +1,980 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type Team, + TeamFromJSON, + TeamToJSON, +} from '../models/Team'; +import { + type TeamCreate, + TeamCreateFromJSON, + TeamCreateToJSON, +} from '../models/TeamCreate'; +import { + type TeamUpdate, + TeamUpdateFromJSON, + TeamUpdateToJSON, +} from '../models/TeamUpdate'; +import { + type TeamsPage, + TeamsPageFromJSON, + TeamsPageToJSON, +} from '../models/TeamsPage'; +import { + type TeamsSortColumn, + TeamsSortColumnFromJSON, + TeamsSortColumnToJSON, +} from '../models/TeamsSortColumn'; +import { + type UserPartial, + UserPartialFromJSON, + UserPartialToJSON, +} from '../models/UserPartial'; +import { + type UsersPartialPage, + UsersPartialPageFromJSON, + UsersPartialPageToJSON, +} from '../models/UsersPartialPage'; +import { + type UsersSortColumn, + UsersSortColumnFromJSON, + UsersSortColumnToJSON, +} from '../models/UsersSortColumn'; + +export interface AddTeamLeaderRequest { + teamId: string; + userId: string; +} + +export interface AddTeamMemberRequest { + teamId: string; + userId: string; +} + +export interface CreateTeamRequest { + teamCreate: TeamCreate; +} + +export interface DeleteTeamRequest { + id: string; +} + +export interface FetchTeamLeadersRequest { + id: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: UsersSortColumn; +} + +export interface FetchTeamMembersRequest { + id: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: UsersSortColumn; +} + +export interface FetchTeamsRequest { + name?: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: TeamsSortColumn; +} + +export interface GetTeamRequest { + id: string; +} + +export interface GetTeamLeaderRequest { + teamId: string; + userId: string; +} + +export interface GetTeamMemberRequest { + teamId: string; + userId: string; +} + +export interface RemoveTeamLeaderRequest { + teamId: string; + userId: string; +} + +export interface RemoveTeamMemberRequest { + teamId: string; + userId: string; +} + +export interface UpdateTeamRequest { + id: string; + teamUpdate: TeamUpdate; +} + +/** + * + */ +export class TeamApi extends runtime.BaseAPI { + + /** + * Creates request options for addTeamLeader without sending the request + */ + async addTeamLeaderRequestOpts(requestParameters: AddTeamLeaderRequest): Promise { + if (requestParameters['teamId'] == null) { + throw new runtime.RequiredError( + 'teamId', + 'Required parameter "teamId" was null or undefined when calling addTeamLeader().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling addTeamLeader().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{team_id}/leaders/{user_id}`; + urlPath = urlPath.replace('{team_id}', encodeURIComponent(String(requestParameters['teamId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + * Add a Team Leader + */ + async addTeamLeaderRaw(requestParameters: AddTeamLeaderRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.addTeamLeaderRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UserPartialFromJSON(jsonValue)); + } + + /** + * Adds the User to the Team as a leader. Returns 201 when the leadership is created and 200 when it already existed. + * Add a Team Leader + */ + async addTeamLeader(requestParameters: AddTeamLeaderRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.addTeamLeaderRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for addTeamMember without sending the request + */ + async addTeamMemberRequestOpts(requestParameters: AddTeamMemberRequest): Promise { + if (requestParameters['teamId'] == null) { + throw new runtime.RequiredError( + 'teamId', + 'Required parameter "teamId" was null or undefined when calling addTeamMember().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling addTeamMember().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{team_id}/members/{user_id}`; + urlPath = urlPath.replace('{team_id}', encodeURIComponent(String(requestParameters['teamId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + * Add a Team Member + */ + async addTeamMemberRaw(requestParameters: AddTeamMemberRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.addTeamMemberRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UserPartialFromJSON(jsonValue)); + } + + /** + * Adds the User to the Team as a member. Returns 201 when the membership is created and 200 when it already existed. + * Add a Team Member + */ + async addTeamMember(requestParameters: AddTeamMemberRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.addTeamMemberRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for createTeam without sending the request + */ + async createTeamRequestOpts(requestParameters: CreateTeamRequest): Promise { + if (requestParameters['teamCreate'] == null) { + throw new runtime.RequiredError( + 'teamCreate', + 'Required parameter "teamCreate" was null or undefined when calling createTeam().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams`; + + return { + path: urlPath, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: TeamCreateToJSON(requestParameters['teamCreate']), + }; + } + + /** + * Creates a Team from the data in the request body. + * Create a Team + */ + async createTeamRaw(requestParameters: CreateTeamRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createTeamRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TeamFromJSON(jsonValue)); + } + + /** + * Creates a Team from the data in the request body. + * Create a Team + */ + async createTeam(requestParameters: CreateTeamRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createTeamRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for deleteTeam without sending the request + */ + async deleteTeamRequestOpts(requestParameters: DeleteTeamRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling deleteTeam().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + * Delete a Team + */ + async deleteTeamRaw(requestParameters: DeleteTeamRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteTeamRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes the Team. Members and leaders are unassigned, the Users themselves are not deleted. + * Delete a Team + */ + async deleteTeam(requestParameters: DeleteTeamRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteTeamRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchTeamLeaders without sending the request + */ + async fetchTeamLeadersRequestOpts(requestParameters: FetchTeamLeadersRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling fetchTeamLeaders().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{id}/leaders`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Users who lead the Team. + * List Team Leaders + */ + async fetchTeamLeadersRaw(requestParameters: FetchTeamLeadersRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchTeamLeadersRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UsersPartialPageFromJSON(jsonValue)); + } + + /** + * Lists the Users who lead the Team. + * List Team Leaders + */ + async fetchTeamLeaders(requestParameters: FetchTeamLeadersRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchTeamLeadersRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchTeamMembers without sending the request + */ + async fetchTeamMembersRequestOpts(requestParameters: FetchTeamMembersRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling fetchTeamMembers().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{id}/members`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Users who are members of the Team. + * List Team Members + */ + async fetchTeamMembersRaw(requestParameters: FetchTeamMembersRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchTeamMembersRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UsersPartialPageFromJSON(jsonValue)); + } + + /** + * Lists the Users who are members of the Team. + * List Team Members + */ + async fetchTeamMembers(requestParameters: FetchTeamMembersRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchTeamMembersRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchTeams without sending the request + */ + async fetchTeamsRequestOpts(requestParameters: FetchTeamsRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['name'] != null) { + queryParameters['name'] = requestParameters['name']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Teams the authenticated user or API token can access. + * List Teams + */ + async fetchTeamsRaw(requestParameters: FetchTeamsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchTeamsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TeamsPageFromJSON(jsonValue)); + } + + /** + * Lists the Teams the authenticated user or API token can access. + * List Teams + */ + async fetchTeams(requestParameters: FetchTeamsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchTeamsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getTeam without sending the request + */ + async getTeamRequestOpts(requestParameters: GetTeamRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getTeam().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Team by its ID. + * Get a Team + */ + async getTeamRaw(requestParameters: GetTeamRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getTeamRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TeamFromJSON(jsonValue)); + } + + /** + * Returns a single Team by its ID. + * Get a Team + */ + async getTeam(requestParameters: GetTeamRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getTeamRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getTeamLeader without sending the request + */ + async getTeamLeaderRequestOpts(requestParameters: GetTeamLeaderRequest): Promise { + if (requestParameters['teamId'] == null) { + throw new runtime.RequiredError( + 'teamId', + 'Required parameter "teamId" was null or undefined when calling getTeamLeader().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling getTeamLeader().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{team_id}/leaders/{user_id}`; + urlPath = urlPath.replace('{team_id}', encodeURIComponent(String(requestParameters['teamId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns the leadership of a single User in the Team. + * Get a Team Leader + */ + async getTeamLeaderRaw(requestParameters: GetTeamLeaderRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getTeamLeaderRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UserPartialFromJSON(jsonValue)); + } + + /** + * Returns the leadership of a single User in the Team. + * Get a Team Leader + */ + async getTeamLeader(requestParameters: GetTeamLeaderRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getTeamLeaderRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getTeamMember without sending the request + */ + async getTeamMemberRequestOpts(requestParameters: GetTeamMemberRequest): Promise { + if (requestParameters['teamId'] == null) { + throw new runtime.RequiredError( + 'teamId', + 'Required parameter "teamId" was null or undefined when calling getTeamMember().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling getTeamMember().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{team_id}/members/{user_id}`; + urlPath = urlPath.replace('{team_id}', encodeURIComponent(String(requestParameters['teamId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns the membership of a single User in the Team. + * Get a Team Member + */ + async getTeamMemberRaw(requestParameters: GetTeamMemberRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getTeamMemberRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UserPartialFromJSON(jsonValue)); + } + + /** + * Returns the membership of a single User in the Team. + * Get a Team Member + */ + async getTeamMember(requestParameters: GetTeamMemberRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getTeamMemberRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for removeTeamLeader without sending the request + */ + async removeTeamLeaderRequestOpts(requestParameters: RemoveTeamLeaderRequest): Promise { + if (requestParameters['teamId'] == null) { + throw new runtime.RequiredError( + 'teamId', + 'Required parameter "teamId" was null or undefined when calling removeTeamLeader().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling removeTeamLeader().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{team_id}/leaders/{user_id}`; + urlPath = urlPath.replace('{team_id}', encodeURIComponent(String(requestParameters['teamId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Removes the User\'s leadership of the Team. The User itself is not deleted. + * Remove a Team Leader + */ + async removeTeamLeaderRaw(requestParameters: RemoveTeamLeaderRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.removeTeamLeaderRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Removes the User\'s leadership of the Team. The User itself is not deleted. + * Remove a Team Leader + */ + async removeTeamLeader(requestParameters: RemoveTeamLeaderRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.removeTeamLeaderRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for removeTeamMember without sending the request + */ + async removeTeamMemberRequestOpts(requestParameters: RemoveTeamMemberRequest): Promise { + if (requestParameters['teamId'] == null) { + throw new runtime.RequiredError( + 'teamId', + 'Required parameter "teamId" was null or undefined when calling removeTeamMember().' + ); + } + + if (requestParameters['userId'] == null) { + throw new runtime.RequiredError( + 'userId', + 'Required parameter "userId" was null or undefined when calling removeTeamMember().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{team_id}/members/{user_id}`; + urlPath = urlPath.replace('{team_id}', encodeURIComponent(String(requestParameters['teamId']))); + urlPath = urlPath.replace('{user_id}', encodeURIComponent(String(requestParameters['userId']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Removes the User\'s membership in the Team. The User itself is not deleted. + * Remove a Team Member + */ + async removeTeamMemberRaw(requestParameters: RemoveTeamMemberRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.removeTeamMemberRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Removes the User\'s membership in the Team. The User itself is not deleted. + * Remove a Team Member + */ + async removeTeamMember(requestParameters: RemoveTeamMemberRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.removeTeamMemberRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for updateTeam without sending the request + */ + async updateTeamRequestOpts(requestParameters: UpdateTeamRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling updateTeam().' + ); + } + + if (requestParameters['teamUpdate'] == null) { + throw new runtime.RequiredError( + 'teamUpdate', + 'Required parameter "teamUpdate" was null or undefined when calling updateTeam().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/teams/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'PATCH', + headers: headerParameters, + query: queryParameters, + body: TeamUpdateToJSON(requestParameters['teamUpdate']), + }; + } + + /** + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Team + */ + async updateTeamRaw(requestParameters: UpdateTeamRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.updateTeamRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TeamFromJSON(jsonValue)); + } + + /** + * Updates the Team with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Team + */ + async updateTeam(requestParameters: UpdateTeamRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.updateTeamRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/TimeAccountApi.ts b/sdk/typescript-fetch/src/apis/TimeAccountApi.ts new file mode 100644 index 0000000..952a42c --- /dev/null +++ b/sdk/typescript-fetch/src/apis/TimeAccountApi.ts @@ -0,0 +1,175 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type Accounts, + AccountsFromJSON, + AccountsToJSON, +} from '../models/Accounts'; + +export interface GetUserAccountsRequest { + id: string; + date: Date; +} + +export interface GetUserWorkingTimeAccountsRequest { + id: string; + date: Date; +} + +/** + * + */ +export class TimeAccountApi extends runtime.BaseAPI { + + /** + * Creates request options for getUserAccounts without sending the request + */ + async getUserAccountsRequestOpts(requestParameters: GetUserAccountsRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getUserAccounts().' + ); + } + + if (requestParameters['date'] == null) { + throw new runtime.RequiredError( + 'date', + 'Required parameter "date" was null or undefined when calling getUserAccounts().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users/{id}/accounts/{date}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + if (requestParameters['date'] instanceof Date) { + urlPath = urlPath.replace('{date}', encodeURIComponent(requestParameters['date'].toISOString().substring(0,10))); + } else { + urlPath = urlPath.replace('{date}', encodeURIComponent(String(requestParameters['date']))); + } + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns all of the User\'s account balances as of the given day, including overtime and surcharge accounts. + * Get a User\'s accounts + */ + async getUserAccountsRaw(requestParameters: GetUserAccountsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getUserAccountsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => AccountsFromJSON(jsonValue)); + } + + /** + * Returns all of the User\'s account balances as of the given day, including overtime and surcharge accounts. + * Get a User\'s accounts + */ + async getUserAccounts(requestParameters: GetUserAccountsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getUserAccountsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getUserWorkingTimeAccounts without sending the request + */ + async getUserWorkingTimeAccountsRequestOpts(requestParameters: GetUserWorkingTimeAccountsRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getUserWorkingTimeAccounts().' + ); + } + + if (requestParameters['date'] == null) { + throw new runtime.RequiredError( + 'date', + 'Required parameter "date" was null or undefined when calling getUserWorkingTimeAccounts().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users/{id}/working-time-accounts/{date}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + if (requestParameters['date'] instanceof Date) { + urlPath = urlPath.replace('{date}', encodeURIComponent(requestParameters['date'].toISOString().substring(0,10))); + } else { + urlPath = urlPath.replace('{date}', encodeURIComponent(String(requestParameters['date']))); + } + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns the User\'s working time account balances as of the given day. + * Get a User\'s working time accounts + */ + async getUserWorkingTimeAccountsRaw(requestParameters: GetUserWorkingTimeAccountsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getUserWorkingTimeAccountsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => AccountsFromJSON(jsonValue)); + } + + /** + * Returns the User\'s working time account balances as of the given day. + * Get a User\'s working time accounts + */ + async getUserWorkingTimeAccounts(requestParameters: GetUserWorkingTimeAccountsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getUserWorkingTimeAccountsRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/TrackApi.ts b/sdk/typescript-fetch/src/apis/TrackApi.ts new file mode 100644 index 0000000..3bb14c7 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/TrackApi.ts @@ -0,0 +1,292 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type Waypoint, + WaypointFromJSON, + WaypointToJSON, +} from '../models/Waypoint'; + +export interface CreateTrackRequest { + id: string; + waypoint: Array; +} + +export interface DeleteTrackRequest { + id: string; +} + +export interface GetTrackRequest { + id: string; +} + +export interface UpdateTrackRequest { + id: string; + waypoint: Array; +} + +/** + * + */ +export class TrackApi extends runtime.BaseAPI { + + /** + * Creates request options for createTrack without sending the request + */ + async createTrackRequestOpts(requestParameters: CreateTrackRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling createTrack().' + ); + } + + if (requestParameters['waypoint'] == null) { + throw new runtime.RequiredError( + 'waypoint', + 'Required parameter "waypoint" was null or undefined when calling createTrack().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs/{id}/track`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters['waypoint']!.map(WaypointToJSON), + }; + } + + /** + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + * Create a Drive Log\'s Track + */ + async createTrackRaw(requestParameters: CreateTrackRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { + const requestOptions = await this.createTrackRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(WaypointFromJSON)); + } + + /** + * Stores a Track for the Drive Log from the waypoints in the request body. A Drive Log holds at most one Track. + * Create a Drive Log\'s Track + */ + async createTrack(requestParameters: CreateTrackRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const response = await this.createTrackRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for deleteTrack without sending the request + */ + async deleteTrackRequestOpts(requestParameters: DeleteTrackRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling deleteTrack().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs/{id}/track`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Deletes the Drive Log\'s Track. The Drive Log itself is kept. + * Delete a Drive Log\'s Track + */ + async deleteTrackRaw(requestParameters: DeleteTrackRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteTrackRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes the Drive Log\'s Track. The Drive Log itself is kept. + * Delete a Drive Log\'s Track + */ + async deleteTrack(requestParameters: DeleteTrackRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteTrackRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for getTrack without sending the request + */ + async getTrackRequestOpts(requestParameters: GetTrackRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getTrack().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs/{id}/track`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + * Get a Drive Log\'s Track + */ + async getTrackRaw(requestParameters: GetTrackRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { + const requestOptions = await this.getTrackRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(WaypointFromJSON)); + } + + /** + * Returns the recorded Track of the Drive Log. Responds with 404 when no Track was recorded. + * Get a Drive Log\'s Track + */ + async getTrack(requestParameters: GetTrackRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const response = await this.getTrackRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for updateTrack without sending the request + */ + async updateTrackRequestOpts(requestParameters: UpdateTrackRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling updateTrack().' + ); + } + + if (requestParameters['waypoint'] == null) { + throw new runtime.RequiredError( + 'waypoint', + 'Required parameter "waypoint" was null or undefined when calling updateTrack().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/drive-logs/{id}/track`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: requestParameters['waypoint']!.map(WaypointToJSON), + }; + } + + /** + * Replaces the Drive Log\'s Track with the waypoints in the request body. + * Replace a Drive Log\'s Track + */ + async updateTrackRaw(requestParameters: UpdateTrackRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { + const requestOptions = await this.updateTrackRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(WaypointFromJSON)); + } + + /** + * Replaces the Drive Log\'s Track with the waypoints in the request body. + * Replace a Drive Log\'s Track + */ + async updateTrack(requestParameters: UpdateTrackRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const response = await this.updateTrackRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/UserApi.ts b/sdk/typescript-fetch/src/apis/UserApi.ts new file mode 100644 index 0000000..a849ccd --- /dev/null +++ b/sdk/typescript-fetch/src/apis/UserApi.ts @@ -0,0 +1,593 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type TeamsPartialPage, + TeamsPartialPageFromJSON, + TeamsPartialPageToJSON, +} from '../models/TeamsPartialPage'; +import { + type TeamsSortColumn, + TeamsSortColumnFromJSON, + TeamsSortColumnToJSON, +} from '../models/TeamsSortColumn'; +import { + type User, + UserFromJSON, + UserToJSON, +} from '../models/User'; +import { + type UserCreate, + UserCreateFromJSON, + UserCreateToJSON, +} from '../models/UserCreate'; +import { + type UserUpdate, + UserUpdateFromJSON, + UserUpdateToJSON, +} from '../models/UserUpdate'; +import { + type UsersPage, + UsersPageFromJSON, + UsersPageToJSON, +} from '../models/UsersPage'; +import { + type UsersSortColumn, + UsersSortColumnFromJSON, + UsersSortColumnToJSON, +} from '../models/UsersSortColumn'; +import { + type WorkScheduleModel, + WorkScheduleModelFromJSON, + WorkScheduleModelToJSON, +} from '../models/WorkScheduleModel'; + +export interface CreateUserRequest { + userCreate: UserCreate; +} + +export interface FetchUserTeamLeadershipsRequest { + id: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: TeamsSortColumn; +} + +export interface FetchUserTeamMembershipsRequest { + id: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: TeamsSortColumn; +} + +export interface FetchUsersRequest { + name?: string; + entryDateFrom?: Date; + entryDateTo?: Date; + resignDateFrom?: Date; + resignDateTo?: Date; + resigned?: boolean; + employeeNumber?: string; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: UsersSortColumn; +} + +export interface GetUserRequest { + id: string; +} + +export interface GetUserWorkScheduleModelRequest { + id: string; +} + +export interface UpdateUserRequest { + id: string; + userUpdate: UserUpdate; +} + +/** + * + */ +export class UserApi extends runtime.BaseAPI { + + /** + * Creates request options for createUser without sending the request + */ + async createUserRequestOpts(requestParameters: CreateUserRequest): Promise { + if (requestParameters['userCreate'] == null) { + throw new runtime.RequiredError( + 'userCreate', + 'Required parameter "userCreate" was null or undefined when calling createUser().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users`; + + return { + path: urlPath, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: UserCreateToJSON(requestParameters['userCreate']), + }; + } + + /** + * Creates a User from the data in the request body. + * Create a User + */ + async createUserRaw(requestParameters: CreateUserRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createUserRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UserFromJSON(jsonValue)); + } + + /** + * Creates a User from the data in the request body. + * Create a User + */ + async createUser(requestParameters: CreateUserRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createUserRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchUserTeamLeaderships without sending the request + */ + async fetchUserTeamLeadershipsRequestOpts(requestParameters: FetchUserTeamLeadershipsRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling fetchUserTeamLeaderships().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users/{id}/team-leaderships`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Teams the User leads. + * List a User\'s Team leaderships + */ + async fetchUserTeamLeadershipsRaw(requestParameters: FetchUserTeamLeadershipsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchUserTeamLeadershipsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TeamsPartialPageFromJSON(jsonValue)); + } + + /** + * Lists the Teams the User leads. + * List a User\'s Team leaderships + */ + async fetchUserTeamLeaderships(requestParameters: FetchUserTeamLeadershipsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchUserTeamLeadershipsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchUserTeamMemberships without sending the request + */ + async fetchUserTeamMembershipsRequestOpts(requestParameters: FetchUserTeamMembershipsRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling fetchUserTeamMemberships().' + ); + } + + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users/{id}/team-memberships`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Teams the User is a member of. + * List a User\'s Team memberships + */ + async fetchUserTeamMembershipsRaw(requestParameters: FetchUserTeamMembershipsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchUserTeamMembershipsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => TeamsPartialPageFromJSON(jsonValue)); + } + + /** + * Lists the Teams the User is a member of. + * List a User\'s Team memberships + */ + async fetchUserTeamMemberships(requestParameters: FetchUserTeamMembershipsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchUserTeamMembershipsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchUsers without sending the request + */ + async fetchUsersRequestOpts(requestParameters: FetchUsersRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['name'] != null) { + queryParameters['name'] = requestParameters['name']; + } + + if (requestParameters['entryDateFrom'] != null) { + queryParameters['entry_date_from'] = (requestParameters['entryDateFrom'] as any).toISOString().substring(0,10); + } + + if (requestParameters['entryDateTo'] != null) { + queryParameters['entry_date_to'] = (requestParameters['entryDateTo'] as any).toISOString().substring(0,10); + } + + if (requestParameters['resignDateFrom'] != null) { + queryParameters['resign_date_from'] = (requestParameters['resignDateFrom'] as any).toISOString().substring(0,10); + } + + if (requestParameters['resignDateTo'] != null) { + queryParameters['resign_date_to'] = (requestParameters['resignDateTo'] as any).toISOString().substring(0,10); + } + + if (requestParameters['resigned'] != null) { + queryParameters['resigned'] = requestParameters['resigned']; + } + + if (requestParameters['employeeNumber'] != null) { + queryParameters['employee_number'] = requestParameters['employeeNumber']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Users the authenticated user or API token can access. + * List Users + */ + async fetchUsersRaw(requestParameters: FetchUsersRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchUsersRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UsersPageFromJSON(jsonValue)); + } + + /** + * Lists the Users the authenticated user or API token can access. + * List Users + */ + async fetchUsers(requestParameters: FetchUsersRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchUsersRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getUser without sending the request + */ + async getUserRequestOpts(requestParameters: GetUserRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getUser().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single User by its ID. + * Get a User + */ + async getUserRaw(requestParameters: GetUserRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getUserRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UserFromJSON(jsonValue)); + } + + /** + * Returns a single User by its ID. + * Get a User + */ + async getUser(requestParameters: GetUserRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getUserRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getUserWorkScheduleModel without sending the request + */ + async getUserWorkScheduleModelRequestOpts(requestParameters: GetUserWorkScheduleModelRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getUserWorkScheduleModel().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users/{id}/work-schedule-model`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + * Get a User\'s Work Schedule Model + */ + async getUserWorkScheduleModelRaw(requestParameters: GetUserWorkScheduleModelRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getUserWorkScheduleModelRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkScheduleModelFromJSON(jsonValue)); + } + + /** + * Returns the Work Schedule Model assigned to the User, with all durations expressed in minutes. + * Get a User\'s Work Schedule Model + */ + async getUserWorkScheduleModel(requestParameters: GetUserWorkScheduleModelRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getUserWorkScheduleModelRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for updateUser without sending the request + */ + async updateUserRequestOpts(requestParameters: UpdateUserRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling updateUser().' + ); + } + + if (requestParameters['userUpdate'] == null) { + throw new runtime.RequiredError( + 'userUpdate', + 'Required parameter "userUpdate" was null or undefined when calling updateUser().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/users/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'PATCH', + headers: headerParameters, + query: queryParameters, + body: UserUpdateToJSON(requestParameters['userUpdate']), + }; + } + + /** + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a User + */ + async updateUserRaw(requestParameters: UpdateUserRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.updateUserRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => UserFromJSON(jsonValue)); + } + + /** + * Updates the User with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a User + */ + async updateUser(requestParameters: UpdateUserRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.updateUserRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/WorkScheduleModelApi.ts b/sdk/typescript-fetch/src/apis/WorkScheduleModelApi.ts new file mode 100644 index 0000000..bf5b003 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/WorkScheduleModelApi.ts @@ -0,0 +1,235 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type WorkScheduleModel, + WorkScheduleModelFromJSON, + WorkScheduleModelToJSON, +} from '../models/WorkScheduleModel'; +import { + type WorkScheduleModelSortColumn, + WorkScheduleModelSortColumnFromJSON, + WorkScheduleModelSortColumnToJSON, +} from '../models/WorkScheduleModelSortColumn'; +import { + type WorkScheduleModelsPage, + WorkScheduleModelsPageFromJSON, + WorkScheduleModelsPageToJSON, +} from '../models/WorkScheduleModelsPage'; + +export interface DeleteWorkScheduleModelRequest { + id: string; +} + +export interface FetchWorkScheduleModelsRequest { + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: WorkScheduleModelSortColumn; +} + +export interface GetWorkScheduleModelRequest { + id: string; +} + +/** + * + */ +export class WorkScheduleModelApi extends runtime.BaseAPI { + + /** + * Creates request options for deleteWorkScheduleModel without sending the request + */ + async deleteWorkScheduleModelRequestOpts(requestParameters: DeleteWorkScheduleModelRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling deleteWorkScheduleModel().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/work-schedule-models/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + * Delete a Work Schedule Model + */ + async deleteWorkScheduleModelRaw(requestParameters: DeleteWorkScheduleModelRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteWorkScheduleModelRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes the Work Schedule Model. It cannot be deleted while it is still assigned to a User. + * Delete a Work Schedule Model + */ + async deleteWorkScheduleModel(requestParameters: DeleteWorkScheduleModelRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteWorkScheduleModelRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchWorkScheduleModels without sending the request + */ + async fetchWorkScheduleModelsRequestOpts(requestParameters: FetchWorkScheduleModelsRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/work-schedule-models`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Work Schedule Models the authenticated user or API token can access. + * List Work Schedule Models + */ + async fetchWorkScheduleModelsRaw(requestParameters: FetchWorkScheduleModelsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchWorkScheduleModelsRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkScheduleModelsPageFromJSON(jsonValue)); + } + + /** + * Lists the Work Schedule Models the authenticated user or API token can access. + * List Work Schedule Models + */ + async fetchWorkScheduleModels(requestParameters: FetchWorkScheduleModelsRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchWorkScheduleModelsRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getWorkScheduleModel without sending the request + */ + async getWorkScheduleModelRequestOpts(requestParameters: GetWorkScheduleModelRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getWorkScheduleModel().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/work-schedule-models/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Work Schedule Model by its ID. + * Get a Work Schedule Model + */ + async getWorkScheduleModelRaw(requestParameters: GetWorkScheduleModelRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getWorkScheduleModelRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkScheduleModelFromJSON(jsonValue)); + } + + /** + * Returns a single Work Schedule Model by its ID. + * Get a Work Schedule Model + */ + async getWorkScheduleModel(requestParameters: GetWorkScheduleModelRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getWorkScheduleModelRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/WorkingTimeApi.ts b/sdk/typescript-fetch/src/apis/WorkingTimeApi.ts new file mode 100644 index 0000000..73f77b7 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/WorkingTimeApi.ts @@ -0,0 +1,522 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type DeletedEntrySortColumn, + DeletedEntrySortColumnFromJSON, + DeletedEntrySortColumnToJSON, +} from '../models/DeletedEntrySortColumn'; +import { + type DeletedEntryWithMetadataPage, + DeletedEntryWithMetadataPageFromJSON, + DeletedEntryWithMetadataPageToJSON, +} from '../models/DeletedEntryWithMetadataPage'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type WorkingTime, + WorkingTimeFromJSON, + WorkingTimeToJSON, +} from '../models/WorkingTime'; +import { + type WorkingTimeCreate, + WorkingTimeCreateFromJSON, + WorkingTimeCreateToJSON, +} from '../models/WorkingTimeCreate'; +import { + type WorkingTimeStatus, + WorkingTimeStatusFromJSON, + WorkingTimeStatusToJSON, +} from '../models/WorkingTimeStatus'; +import { + type WorkingTimeTypeCategory, + WorkingTimeTypeCategoryFromJSON, + WorkingTimeTypeCategoryToJSON, +} from '../models/WorkingTimeTypeCategory'; +import { + type WorkingTimeUpdate, + WorkingTimeUpdateFromJSON, + WorkingTimeUpdateToJSON, +} from '../models/WorkingTimeUpdate'; +import { + type WorkingTimesPage, + WorkingTimesPageFromJSON, + WorkingTimesPageToJSON, +} from '../models/WorkingTimesPage'; +import { + type WorkingTimesSortColumn, + WorkingTimesSortColumnFromJSON, + WorkingTimesSortColumnToJSON, +} from '../models/WorkingTimesSortColumn'; + +export interface CreateWorkingTimeRequest { + workingTimeCreate: WorkingTimeCreate; +} + +export interface DeleteWorkingTimeRequest { + id: string; +} + +export interface FetchDeletedWorkingTimesRequest { + lastModifiedAfter?: Date; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: DeletedEntrySortColumn; +} + +export interface FetchWorkingTimesRequest { + notes?: string; + startFrom?: Date; + startTo?: Date; + lastModifiedAfter?: Date; + workingTimeTypes?: Array; + workingTimeTypeCategories?: Array; + statuses?: Array; + users?: Array; + changed?: boolean; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: WorkingTimesSortColumn; +} + +export interface GetWorkingTimeRequest { + id: string; +} + +export interface UpdateWorkingTimeRequest { + id: string; + workingTimeUpdate: WorkingTimeUpdate; +} + +/** + * + */ +export class WorkingTimeApi extends runtime.BaseAPI { + + /** + * Creates request options for createWorkingTime without sending the request + */ + async createWorkingTimeRequestOpts(requestParameters: CreateWorkingTimeRequest): Promise { + if (requestParameters['workingTimeCreate'] == null) { + throw new runtime.RequiredError( + 'workingTimeCreate', + 'Required parameter "workingTimeCreate" was null or undefined when calling createWorkingTime().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-times`; + + return { + path: urlPath, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: WorkingTimeCreateToJSON(requestParameters['workingTimeCreate']), + }; + } + + /** + * Creates a Working Time from the data in the request body. + * Create a Working Time + */ + async createWorkingTimeRaw(requestParameters: CreateWorkingTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createWorkingTimeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimeFromJSON(jsonValue)); + } + + /** + * Creates a Working Time from the data in the request body. + * Create a Working Time + */ + async createWorkingTime(requestParameters: CreateWorkingTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createWorkingTimeRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for deleteWorkingTime without sending the request + */ + async deleteWorkingTimeRequestOpts(requestParameters: DeleteWorkingTimeRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling deleteWorkingTime().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-times/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Deletes the Working Time. + * Delete a Working Time + */ + async deleteWorkingTimeRaw(requestParameters: DeleteWorkingTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteWorkingTimeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes the Working Time. + * Delete a Working Time + */ + async deleteWorkingTime(requestParameters: DeleteWorkingTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteWorkingTimeRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchDeletedWorkingTimes without sending the request + */ + async fetchDeletedWorkingTimesRequestOpts(requestParameters: FetchDeletedWorkingTimesRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['lastModifiedAfter'] != null) { + queryParameters['last_modified_after'] = (requestParameters['lastModifiedAfter'] as any).toISOString(); + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-times:deleted`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + * List deleted Working Times + */ + async fetchDeletedWorkingTimesRaw(requestParameters: FetchDeletedWorkingTimesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchDeletedWorkingTimesRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DeletedEntryWithMetadataPageFromJSON(jsonValue)); + } + + /** + * Lists Working Times that were deleted, so a client holding a local copy can reconcile. + * List deleted Working Times + */ + async fetchDeletedWorkingTimes(requestParameters: FetchDeletedWorkingTimesRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchDeletedWorkingTimesRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchWorkingTimes without sending the request + */ + async fetchWorkingTimesRequestOpts(requestParameters: FetchWorkingTimesRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['notes'] != null) { + queryParameters['notes'] = requestParameters['notes']; + } + + if (requestParameters['startFrom'] != null) { + queryParameters['start_from'] = (requestParameters['startFrom'] as any).toISOString().substring(0,10); + } + + if (requestParameters['startTo'] != null) { + queryParameters['start_to'] = (requestParameters['startTo'] as any).toISOString().substring(0,10); + } + + if (requestParameters['lastModifiedAfter'] != null) { + queryParameters['last_modified_after'] = (requestParameters['lastModifiedAfter'] as any).toISOString(); + } + + if (requestParameters['workingTimeTypes'] != null) { + queryParameters['working_time_types'] = requestParameters['workingTimeTypes']; + } + + if (requestParameters['workingTimeTypeCategories'] != null) { + queryParameters['working_time_type_categories'] = requestParameters['workingTimeTypeCategories']; + } + + if (requestParameters['statuses'] != null) { + queryParameters['statuses'] = requestParameters['statuses']; + } + + if (requestParameters['users'] != null) { + queryParameters['users'] = requestParameters['users']; + } + + if (requestParameters['changed'] != null) { + queryParameters['changed'] = requestParameters['changed']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-times`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Working Times the authenticated user or API token can access. + * List Working Times + */ + async fetchWorkingTimesRaw(requestParameters: FetchWorkingTimesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchWorkingTimesRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimesPageFromJSON(jsonValue)); + } + + /** + * Lists the Working Times the authenticated user or API token can access. + * List Working Times + */ + async fetchWorkingTimes(requestParameters: FetchWorkingTimesRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchWorkingTimesRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getWorkingTime without sending the request + */ + async getWorkingTimeRequestOpts(requestParameters: GetWorkingTimeRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getWorkingTime().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-times/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Working Time by its ID. + * Get a Working Time + */ + async getWorkingTimeRaw(requestParameters: GetWorkingTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getWorkingTimeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimeFromJSON(jsonValue)); + } + + /** + * Returns a single Working Time by its ID. + * Get a Working Time + */ + async getWorkingTime(requestParameters: GetWorkingTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getWorkingTimeRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for updateWorkingTime without sending the request + */ + async updateWorkingTimeRequestOpts(requestParameters: UpdateWorkingTimeRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling updateWorkingTime().' + ); + } + + if (requestParameters['workingTimeUpdate'] == null) { + throw new runtime.RequiredError( + 'workingTimeUpdate', + 'Required parameter "workingTimeUpdate" was null or undefined when calling updateWorkingTime().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-times/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'PATCH', + headers: headerParameters, + query: queryParameters, + body: WorkingTimeUpdateToJSON(requestParameters['workingTimeUpdate']), + }; + } + + /** + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Working Time + */ + async updateWorkingTimeRaw(requestParameters: UpdateWorkingTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.updateWorkingTimeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimeFromJSON(jsonValue)); + } + + /** + * Updates the Working Time with the fields present in the request body. Fields that are omitted stay unchanged. + * Update a Working Time + */ + async updateWorkingTime(requestParameters: UpdateWorkingTimeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.updateWorkingTimeRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/WorkingTimeDateSpanApi.ts b/sdk/typescript-fetch/src/apis/WorkingTimeDateSpanApi.ts new file mode 100644 index 0000000..b08c41a --- /dev/null +++ b/sdk/typescript-fetch/src/apis/WorkingTimeDateSpanApi.ts @@ -0,0 +1,499 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type DeletedEntrySortColumn, + DeletedEntrySortColumnFromJSON, + DeletedEntrySortColumnToJSON, +} from '../models/DeletedEntrySortColumn'; +import { + type DeletedEntryWithMetadataPage, + DeletedEntryWithMetadataPageFromJSON, + DeletedEntryWithMetadataPageToJSON, +} from '../models/DeletedEntryWithMetadataPage'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type WorkingTimeDateSpan, + WorkingTimeDateSpanFromJSON, + WorkingTimeDateSpanToJSON, +} from '../models/WorkingTimeDateSpan'; +import { + type WorkingTimeDateSpanCreate, + WorkingTimeDateSpanCreateFromJSON, + WorkingTimeDateSpanCreateToJSON, +} from '../models/WorkingTimeDateSpanCreate'; +import { + type WorkingTimeDateSpanPage, + WorkingTimeDateSpanPageFromJSON, + WorkingTimeDateSpanPageToJSON, +} from '../models/WorkingTimeDateSpanPage'; +import { + type WorkingTimeDateSpanUpdate, + WorkingTimeDateSpanUpdateFromJSON, + WorkingTimeDateSpanUpdateToJSON, +} from '../models/WorkingTimeDateSpanUpdate'; +import { + type WorkingTimeDateSpansSortColumn, + WorkingTimeDateSpansSortColumnFromJSON, + WorkingTimeDateSpansSortColumnToJSON, +} from '../models/WorkingTimeDateSpansSortColumn'; + +export interface CreateWorkingTimeDateSpanRequest { + workingTimeDateSpanCreate: WorkingTimeDateSpanCreate; +} + +export interface DeleteWorkingTimeDateSpanRequest { + id: string; +} + +export interface FetchDeletedWorkingTimeDateSpansRequest { + lastModifiedAfter?: Date; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: DeletedEntrySortColumn; +} + +export interface FetchWorkingTimeDateSpansRequest { + from?: Date; + to?: Date; + lastModifiedAfter?: Date; + workingTimeTypes?: Array; + users?: Array; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: WorkingTimeDateSpansSortColumn; +} + +export interface GetWorkingTimeDateSpanRequest { + id: string; +} + +export interface UpdateWorkingTimeDateSpanRequest { + id: string; + workingTimeDateSpanUpdate: WorkingTimeDateSpanUpdate; +} + +/** + * + */ +export class WorkingTimeDateSpanApi extends runtime.BaseAPI { + + /** + * Creates request options for createWorkingTimeDateSpan without sending the request + */ + async createWorkingTimeDateSpanRequestOpts(requestParameters: CreateWorkingTimeDateSpanRequest): Promise { + if (requestParameters['workingTimeDateSpanCreate'] == null) { + throw new runtime.RequiredError( + 'workingTimeDateSpanCreate', + 'Required parameter "workingTimeDateSpanCreate" was null or undefined when calling createWorkingTimeDateSpan().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-time-date-spans`; + + return { + path: urlPath, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: WorkingTimeDateSpanCreateToJSON(requestParameters['workingTimeDateSpanCreate']), + }; + } + + /** + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + * Create a Working Time Date Span + */ + async createWorkingTimeDateSpanRaw(requestParameters: CreateWorkingTimeDateSpanRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.createWorkingTimeDateSpanRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimeDateSpanFromJSON(jsonValue)); + } + + /** + * Creates a Working Time Date Span from the data in the request body, and the day-based Working Times it covers. + * Create a Working Time Date Span + */ + async createWorkingTimeDateSpan(requestParameters: CreateWorkingTimeDateSpanRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.createWorkingTimeDateSpanRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for deleteWorkingTimeDateSpan without sending the request + */ + async deleteWorkingTimeDateSpanRequestOpts(requestParameters: DeleteWorkingTimeDateSpanRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling deleteWorkingTimeDateSpan().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-time-date-spans/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Deletes the Working Time Date Span together with the Working Times it covers. + * Delete a Working Time Date Span + */ + async deleteWorkingTimeDateSpanRaw(requestParameters: DeleteWorkingTimeDateSpanRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteWorkingTimeDateSpanRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes the Working Time Date Span together with the Working Times it covers. + * Delete a Working Time Date Span + */ + async deleteWorkingTimeDateSpan(requestParameters: DeleteWorkingTimeDateSpanRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteWorkingTimeDateSpanRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchDeletedWorkingTimeDateSpans without sending the request + */ + async fetchDeletedWorkingTimeDateSpansRequestOpts(requestParameters: FetchDeletedWorkingTimeDateSpansRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['lastModifiedAfter'] != null) { + queryParameters['last_modified_after'] = (requestParameters['lastModifiedAfter'] as any).toISOString(); + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-time-date-spans:deleted`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + * List deleted Working Time Date Spans + */ + async fetchDeletedWorkingTimeDateSpansRaw(requestParameters: FetchDeletedWorkingTimeDateSpansRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchDeletedWorkingTimeDateSpansRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => DeletedEntryWithMetadataPageFromJSON(jsonValue)); + } + + /** + * Lists Working Time Date Spans that were deleted, so a client holding a local copy can reconcile. + * List deleted Working Time Date Spans + */ + async fetchDeletedWorkingTimeDateSpans(requestParameters: FetchDeletedWorkingTimeDateSpansRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchDeletedWorkingTimeDateSpansRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for fetchWorkingTimeDateSpans without sending the request + */ + async fetchWorkingTimeDateSpansRequestOpts(requestParameters: FetchWorkingTimeDateSpansRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['from'] != null) { + queryParameters['from'] = (requestParameters['from'] as any).toISOString().substring(0,10); + } + + if (requestParameters['to'] != null) { + queryParameters['to'] = (requestParameters['to'] as any).toISOString().substring(0,10); + } + + if (requestParameters['lastModifiedAfter'] != null) { + queryParameters['last_modified_after'] = (requestParameters['lastModifiedAfter'] as any).toISOString(); + } + + if (requestParameters['workingTimeTypes'] != null) { + queryParameters['working_time_types'] = requestParameters['workingTimeTypes']; + } + + if (requestParameters['users'] != null) { + queryParameters['users'] = requestParameters['users']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-time-date-spans`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Working Time Date Spans the authenticated user or API token can access. + * List Working Time Date Spans + */ + async fetchWorkingTimeDateSpansRaw(requestParameters: FetchWorkingTimeDateSpansRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchWorkingTimeDateSpansRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimeDateSpanPageFromJSON(jsonValue)); + } + + /** + * Lists the Working Time Date Spans the authenticated user or API token can access. + * List Working Time Date Spans + */ + async fetchWorkingTimeDateSpans(requestParameters: FetchWorkingTimeDateSpansRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchWorkingTimeDateSpansRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getWorkingTimeDateSpan without sending the request + */ + async getWorkingTimeDateSpanRequestOpts(requestParameters: GetWorkingTimeDateSpanRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getWorkingTimeDateSpan().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-time-date-spans/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Working Time Date Span by its ID. + * Get a Working Time Date Span + */ + async getWorkingTimeDateSpanRaw(requestParameters: GetWorkingTimeDateSpanRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getWorkingTimeDateSpanRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimeDateSpanFromJSON(jsonValue)); + } + + /** + * Returns a single Working Time Date Span by its ID. + * Get a Working Time Date Span + */ + async getWorkingTimeDateSpan(requestParameters: GetWorkingTimeDateSpanRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getWorkingTimeDateSpanRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for updateWorkingTimeDateSpan without sending the request + */ + async updateWorkingTimeDateSpanRequestOpts(requestParameters: UpdateWorkingTimeDateSpanRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling updateWorkingTimeDateSpan().' + ); + } + + if (requestParameters['workingTimeDateSpanUpdate'] == null) { + throw new runtime.RequiredError( + 'workingTimeDateSpanUpdate', + 'Required parameter "workingTimeDateSpanUpdate" was null or undefined when calling updateWorkingTimeDateSpan().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-time-date-spans/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'PATCH', + headers: headerParameters, + query: queryParameters, + body: WorkingTimeDateSpanUpdateToJSON(requestParameters['workingTimeDateSpanUpdate']), + }; + } + + /** + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + * Update a Working Time Date Span + */ + async updateWorkingTimeDateSpanRaw(requestParameters: UpdateWorkingTimeDateSpanRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.updateWorkingTimeDateSpanRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimeDateSpanFromJSON(jsonValue)); + } + + /** + * Updates the Working Time Date Span with the fields present in the request body, and adjusts the Working Times it covers. Fields that are omitted stay unchanged. + * Update a Working Time Date Span + */ + async updateWorkingTimeDateSpan(requestParameters: UpdateWorkingTimeDateSpanRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.updateWorkingTimeDateSpanRaw(requestParameters, initOverrides); + switch (response.raw.status) { + case 200: + return await response.value(); + case 204: + return null; + default: + return await response.value(); + } + } + +} diff --git a/sdk/typescript-fetch/src/apis/WorkingTimeTypeApi.ts b/sdk/typescript-fetch/src/apis/WorkingTimeTypeApi.ts new file mode 100644 index 0000000..7188137 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/WorkingTimeTypeApi.ts @@ -0,0 +1,295 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import * as runtime from '../runtime'; +import { + type DurationUnit, + DurationUnitFromJSON, + DurationUnitToJSON, +} from '../models/DurationUnit'; +import { + type RecordingModeUser, + RecordingModeUserFromJSON, + RecordingModeUserToJSON, +} from '../models/RecordingModeUser'; +import { + type SortDirection, + SortDirectionFromJSON, + SortDirectionToJSON, +} from '../models/SortDirection'; +import { + type WorkingTimeType, + WorkingTimeTypeFromJSON, + WorkingTimeTypeToJSON, +} from '../models/WorkingTimeType'; +import { + type WorkingTimeTypeCategory, + WorkingTimeTypeCategoryFromJSON, + WorkingTimeTypeCategoryToJSON, +} from '../models/WorkingTimeTypeCategory'; +import { + type WorkingTimeTypeSubCategory, + WorkingTimeTypeSubCategoryFromJSON, + WorkingTimeTypeSubCategoryToJSON, +} from '../models/WorkingTimeTypeSubCategory'; +import { + type WorkingTimeTypesPage, + WorkingTimeTypesPageFromJSON, + WorkingTimeTypesPageToJSON, +} from '../models/WorkingTimeTypesPage'; +import { + type WorkingTimeTypesSortColumn, + WorkingTimeTypesSortColumnFromJSON, + WorkingTimeTypesSortColumnToJSON, +} from '../models/WorkingTimeTypesSortColumn'; + +export interface DeleteWorkingTimeTypeRequest { + id: string; +} + +export interface FetchWorkingTimeTypesRequest { + name?: string; + shortName?: string; + description?: string; + categories?: Array; + subCategories?: Array; + editUnits?: Array; + archived?: boolean; + recordingModes?: Array; + pageToken?: string; + limit?: number; + sortDirection?: SortDirection; + sortBy?: WorkingTimeTypesSortColumn; +} + +export interface GetWorkingTimeTypeRequest { + id: string; +} + +/** + * + */ +export class WorkingTimeTypeApi extends runtime.BaseAPI { + + /** + * Creates request options for deleteWorkingTimeType without sending the request + */ + async deleteWorkingTimeTypeRequestOpts(requestParameters: DeleteWorkingTimeTypeRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling deleteWorkingTimeType().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-time-types/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + * Delete a Working Time Type + */ + async deleteWorkingTimeTypeRaw(requestParameters: DeleteWorkingTimeTypeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteWorkingTimeTypeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes the Working Time Type. It cannot be deleted while Working Times still reference it. + * Delete a Working Time Type + */ + async deleteWorkingTimeType(requestParameters: DeleteWorkingTimeTypeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteWorkingTimeTypeRaw(requestParameters, initOverrides); + } + + /** + * Creates request options for fetchWorkingTimeTypes without sending the request + */ + async fetchWorkingTimeTypesRequestOpts(requestParameters: FetchWorkingTimeTypesRequest): Promise { + const queryParameters: any = {}; + + if (requestParameters['name'] != null) { + queryParameters['name'] = requestParameters['name']; + } + + if (requestParameters['shortName'] != null) { + queryParameters['short_name'] = requestParameters['shortName']; + } + + if (requestParameters['description'] != null) { + queryParameters['description'] = requestParameters['description']; + } + + if (requestParameters['categories'] != null) { + queryParameters['categories'] = requestParameters['categories']; + } + + if (requestParameters['subCategories'] != null) { + queryParameters['sub_categories'] = requestParameters['subCategories']; + } + + if (requestParameters['editUnits'] != null) { + queryParameters['edit_units'] = requestParameters['editUnits']; + } + + if (requestParameters['archived'] != null) { + queryParameters['archived'] = requestParameters['archived']; + } + + if (requestParameters['recordingModes'] != null) { + queryParameters['recording_modes'] = requestParameters['recordingModes']; + } + + if (requestParameters['pageToken'] != null) { + queryParameters['page_token'] = requestParameters['pageToken']; + } + + if (requestParameters['limit'] != null) { + queryParameters['limit'] = requestParameters['limit']; + } + + if (requestParameters['sortDirection'] != null) { + queryParameters['sort_direction'] = requestParameters['sortDirection']; + } + + if (requestParameters['sortBy'] != null) { + queryParameters['sort_by'] = requestParameters['sortBy']; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-time-types`; + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Lists the Working Time Types the authenticated user or API token can access. + * List Working Time Types + */ + async fetchWorkingTimeTypesRaw(requestParameters: FetchWorkingTimeTypesRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.fetchWorkingTimeTypesRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimeTypesPageFromJSON(jsonValue)); + } + + /** + * Lists the Working Time Types the authenticated user or API token can access. + * List Working Time Types + */ + async fetchWorkingTimeTypes(requestParameters: FetchWorkingTimeTypesRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.fetchWorkingTimeTypesRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Creates request options for getWorkingTimeType without sending the request + */ + async getWorkingTimeTypeRequestOpts(requestParameters: GetWorkingTimeTypeRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling getWorkingTimeType().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/working-time-types/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Returns a single Working Time Type by its ID. + * Get a Working Time Type + */ + async getWorkingTimeTypeRaw(requestParameters: GetWorkingTimeTypeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.getWorkingTimeTypeRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => WorkingTimeTypeFromJSON(jsonValue)); + } + + /** + * Returns a single Working Time Type by its ID. + * Get a Working Time Type + */ + async getWorkingTimeType(requestParameters: GetWorkingTimeTypeRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + const response = await this.getWorkingTimeTypeRaw(requestParameters, initOverrides); + return await response.value(); + } + +} diff --git a/sdk/typescript-fetch/src/apis/index.ts b/sdk/typescript-fetch/src/apis/index.ts new file mode 100644 index 0000000..ae21d65 --- /dev/null +++ b/sdk/typescript-fetch/src/apis/index.ts @@ -0,0 +1,19 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './CarApi'; +export * from './DriveLogApi'; +export * from './DriveLogCategoryApi'; +export * from './HolidayCalendarApi'; +export * from './ProjectTimeApi'; +export * from './TaskApi'; +export * from './TaskToLeaderAssignmentApi'; +export * from './TaskToTeamAssignmentApi'; +export * from './TaskToUserAssignmentApi'; +export * from './TeamApi'; +export * from './TimeAccountApi'; +export * from './TrackApi'; +export * from './UserApi'; +export * from './WorkScheduleModelApi'; +export * from './WorkingTimeApi'; +export * from './WorkingTimeDateSpanApi'; +export * from './WorkingTimeTypeApi'; diff --git a/sdk/typescript-fetch/src/index.ts b/sdk/typescript-fetch/src/index.ts new file mode 100644 index 0000000..bebe8bb --- /dev/null +++ b/sdk/typescript-fetch/src/index.ts @@ -0,0 +1,5 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './runtime'; +export * from './apis/index'; +export * from './models/index'; diff --git a/sdk/typescript-fetch/src/models/Accounts.ts b/sdk/typescript-fetch/src/models/Accounts.ts new file mode 100644 index 0000000..8ac0546 --- /dev/null +++ b/sdk/typescript-fetch/src/models/Accounts.ts @@ -0,0 +1,112 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TimeAccount } from './TimeAccount'; +import { + TimeAccountFromJSON, + TimeAccountFromJSONTyped, + TimeAccountToJSON, + TimeAccountToJSONTyped, +} from './TimeAccount'; +import type { VacationAccount } from './VacationAccount'; +import { + VacationAccountFromJSON, + VacationAccountFromJSONTyped, + VacationAccountToJSON, + VacationAccountToJSONTyped, +} from './VacationAccount'; +import type { OvertimeSurchargeAccounts } from './OvertimeSurchargeAccounts'; +import { + OvertimeSurchargeAccountsFromJSON, + OvertimeSurchargeAccountsFromJSONTyped, + OvertimeSurchargeAccountsToJSON, + OvertimeSurchargeAccountsToJSONTyped, +} from './OvertimeSurchargeAccounts'; + +/** + * + * @export + * @interface Accounts + */ +export interface Accounts { + /** + * date of last balance + * @type {Date} + * @memberof Accounts + */ + lastBalanceDate: Date | null; + /** + * + * @type {TimeAccount} + * @memberof Accounts + */ + timeAccount?: TimeAccount | null; + /** + * + * @type {Array} + * @memberof Accounts + */ + overtimeSurchargeAccounts?: Array | null; + /** + * + * @type {VacationAccount} + * @memberof Accounts + */ + vacationAccount?: VacationAccount | null; +} + +/** + * Check if a given object implements the Accounts interface. + */ +export function instanceOfAccounts(value: object): value is Accounts { + if (!('lastBalanceDate' in value) || value['lastBalanceDate'] === undefined) return false; + return true; +} + +export function AccountsFromJSON(json: any): Accounts { + return AccountsFromJSONTyped(json, false); +} + +export function AccountsFromJSONTyped(json: any, ignoreDiscriminator: boolean): Accounts { + if (json == null) { + return json; + } + return { + + 'lastBalanceDate': (json['last_balance_date'] == null ? null : new Date(json['last_balance_date'])), + 'timeAccount': json['time_account'] == null ? undefined : TimeAccountFromJSON(json['time_account']), + 'overtimeSurchargeAccounts': json['overtime_surcharge_accounts'] == null ? undefined : ((json['overtime_surcharge_accounts'] as Array).map(OvertimeSurchargeAccountsFromJSON)), + 'vacationAccount': json['vacation_account'] == null ? undefined : VacationAccountFromJSON(json['vacation_account']), + }; +} + +export function AccountsToJSON(json: any): Accounts { + return AccountsToJSONTyped(json, false); +} + +export function AccountsToJSONTyped(value?: Accounts | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'last_balance_date': value['lastBalanceDate'] == null ? value['lastBalanceDate'] : value['lastBalanceDate'].toISOString().substring(0,10), + 'time_account': TimeAccountToJSON(value['timeAccount']), + 'overtime_surcharge_accounts': value['overtimeSurchargeAccounts'] == null ? undefined : ((value['overtimeSurchargeAccounts'] as Array).map(OvertimeSurchargeAccountsToJSON)), + 'vacation_account': VacationAccountToJSON(value['vacationAccount']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/BreakTime.ts b/sdk/typescript-fetch/src/models/BreakTime.ts new file mode 100644 index 0000000..aee177e --- /dev/null +++ b/sdk/typescript-fetch/src/models/BreakTime.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import type { BreakTimeAutomatic } from './BreakTimeAutomatic'; +import { + instanceOfBreakTimeAutomatic, + BreakTimeAutomaticFromJSON, + BreakTimeAutomaticFromJSONTyped, + BreakTimeAutomaticToJSON, +} from './BreakTimeAutomatic'; +import type { BreakTimeManual } from './BreakTimeManual'; +import { + instanceOfBreakTimeManual, + BreakTimeManualFromJSON, + BreakTimeManualFromJSONTyped, + BreakTimeManualToJSON, +} from './BreakTimeManual'; +import type { BreakTimeOngoing } from './BreakTimeOngoing'; +import { + instanceOfBreakTimeOngoing, + BreakTimeOngoingFromJSON, + BreakTimeOngoingFromJSONTyped, + BreakTimeOngoingToJSON, +} from './BreakTimeOngoing'; + +/** + * @type BreakTime + * + * @export + */ +export type BreakTime = { type: 'automatic' } & BreakTimeAutomatic | { type: 'manual' } & BreakTimeManual | { type: 'ongoing' } & BreakTimeOngoing; + +export function BreakTimeFromJSON(json: any): BreakTime { + return BreakTimeFromJSONTyped(json, false); +} + +export function BreakTimeFromJSONTyped(json: any, ignoreDiscriminator: boolean): BreakTime { + if (json == null) { + return json; + } + switch (json['type']) { + case 'automatic': + return Object.assign({}, BreakTimeAutomaticFromJSONTyped(json, true), { type: 'automatic' } as const); + case 'manual': + return Object.assign({}, BreakTimeManualFromJSONTyped(json, true), { type: 'manual' } as const); + case 'ongoing': + return Object.assign({}, BreakTimeOngoingFromJSONTyped(json, true), { type: 'ongoing' } as const); + default: + return json; + } +} + +export function BreakTimeToJSON(json: any): any { + return BreakTimeToJSONTyped(json, false); +} + +export function BreakTimeToJSONTyped(value?: BreakTime | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + switch (value['type']) { + case 'automatic': + return Object.assign({}, BreakTimeAutomaticToJSON(value), { type: 'automatic' } as const); + case 'manual': + return Object.assign({}, BreakTimeManualToJSON(value), { type: 'manual' } as const); + case 'ongoing': + return Object.assign({}, BreakTimeOngoingToJSON(value), { type: 'ongoing' } as const); + default: + return value; + } +} + diff --git a/sdk/typescript-fetch/src/models/BreakTimeAutomatic.ts b/sdk/typescript-fetch/src/models/BreakTimeAutomatic.ts new file mode 100644 index 0000000..0b4c5b6 --- /dev/null +++ b/sdk/typescript-fetch/src/models/BreakTimeAutomatic.ts @@ -0,0 +1,103 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { BreakTimeType } from './BreakTimeType'; +import { + BreakTimeTypeFromJSON, + BreakTimeTypeFromJSONTyped, + BreakTimeTypeToJSON, + BreakTimeTypeToJSONTyped, +} from './BreakTimeType'; + +/** + * + * @export + * @interface BreakTimeAutomatic + */ +export interface BreakTimeAutomatic { + /** + * + * @type {BreakTimeType} + * @memberof BreakTimeAutomatic + */ + type: BreakTimeType; + /** + * Duration of break in minutes + * @type {number} + * @memberof BreakTimeAutomatic + */ + durationMinutes: number; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof BreakTimeAutomatic + */ + start: Date | null; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof BreakTimeAutomatic + */ + end: Date | null; +} + + + +/** + * Check if a given object implements the BreakTimeAutomatic interface. + */ +export function instanceOfBreakTimeAutomatic(value: object): value is BreakTimeAutomatic { + if (!('type' in value) || value['type'] === undefined) return false; + if (!('durationMinutes' in value) || value['durationMinutes'] === undefined) return false; + if (!('start' in value) || value['start'] === undefined) return false; + if (!('end' in value) || value['end'] === undefined) return false; + return true; +} + +export function BreakTimeAutomaticFromJSON(json: any): BreakTimeAutomatic { + return BreakTimeAutomaticFromJSONTyped(json, false); +} + +export function BreakTimeAutomaticFromJSONTyped(json: any, ignoreDiscriminator: boolean): BreakTimeAutomatic { + if (json == null) { + return json; + } + return { + + 'type': BreakTimeTypeFromJSON(json['type']), + 'durationMinutes': json['duration_minutes'], + 'start': (json['start'] == null ? null : new Date(json['start'])), + 'end': (json['end'] == null ? null : new Date(json['end'])), + }; +} + +export function BreakTimeAutomaticToJSON(json: any): BreakTimeAutomatic { + return BreakTimeAutomaticToJSONTyped(json, false); +} + +export function BreakTimeAutomaticToJSONTyped(value?: BreakTimeAutomatic | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'type': BreakTimeTypeToJSON(value['type']), + 'duration_minutes': value['durationMinutes'], + 'start': value['start'] == null ? value['start'] : value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + }; +} + diff --git a/sdk/typescript-fetch/src/models/BreakTimeBase.ts b/sdk/typescript-fetch/src/models/BreakTimeBase.ts new file mode 100644 index 0000000..8983bdf --- /dev/null +++ b/sdk/typescript-fetch/src/models/BreakTimeBase.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { BreakTimeType } from './BreakTimeType'; +import { + BreakTimeTypeFromJSON, + BreakTimeTypeFromJSONTyped, + BreakTimeTypeToJSON, + BreakTimeTypeToJSONTyped, +} from './BreakTimeType'; + +/** + * Members shared by every kind of break time, including the discriminator. + * @export + * @interface BreakTimeBase + */ +export interface BreakTimeBase { + /** + * + * @type {BreakTimeType} + * @memberof BreakTimeBase + */ + type: BreakTimeType; +} + + + +/** + * Check if a given object implements the BreakTimeBase interface. + */ +export function instanceOfBreakTimeBase(value: object): value is BreakTimeBase { + if (!('type' in value) || value['type'] === undefined) return false; + return true; +} + +export function BreakTimeBaseFromJSON(json: any): BreakTimeBase { + return BreakTimeBaseFromJSONTyped(json, false); +} + +export function BreakTimeBaseFromJSONTyped(json: any, ignoreDiscriminator: boolean): BreakTimeBase { + if (json == null) { + return json; + } + return { + + 'type': BreakTimeTypeFromJSON(json['type']), + }; +} + +export function BreakTimeBaseToJSON(json: any): BreakTimeBase { + return BreakTimeBaseToJSONTyped(json, false); +} + +export function BreakTimeBaseToJSONTyped(value?: BreakTimeBase | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'type': BreakTimeTypeToJSON(value['type']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/BreakTimeManual.ts b/sdk/typescript-fetch/src/models/BreakTimeManual.ts new file mode 100644 index 0000000..cabe30b --- /dev/null +++ b/sdk/typescript-fetch/src/models/BreakTimeManual.ts @@ -0,0 +1,101 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { BreakTimeType } from './BreakTimeType'; +import { + BreakTimeTypeFromJSON, + BreakTimeTypeFromJSONTyped, + BreakTimeTypeToJSON, + BreakTimeTypeToJSONTyped, +} from './BreakTimeType'; + +/** + * + * @export + * @interface BreakTimeManual + */ +export interface BreakTimeManual { + /** + * + * @type {BreakTimeType} + * @memberof BreakTimeManual + */ + type: BreakTimeType; + /** + * Duration of break in minutes. Please make sure it matches the duration between 'start' and 'end' if the properties are also given. + * @type {number} + * @memberof BreakTimeManual + */ + durationMinutes: number; + /** + * start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + * @type {Date} + * @memberof BreakTimeManual + */ + start?: Date | null; + /** + * start and end are optional. To avoid discrepancies in the duration given in duration_minutes and the time between start and end the preferable way is to only provide duration_minutes. + * @type {Date} + * @memberof BreakTimeManual + */ + end?: Date | null; +} + + + +/** + * Check if a given object implements the BreakTimeManual interface. + */ +export function instanceOfBreakTimeManual(value: object): value is BreakTimeManual { + if (!('type' in value) || value['type'] === undefined) return false; + if (!('durationMinutes' in value) || value['durationMinutes'] === undefined) return false; + return true; +} + +export function BreakTimeManualFromJSON(json: any): BreakTimeManual { + return BreakTimeManualFromJSONTyped(json, false); +} + +export function BreakTimeManualFromJSONTyped(json: any, ignoreDiscriminator: boolean): BreakTimeManual { + if (json == null) { + return json; + } + return { + + 'type': BreakTimeTypeFromJSON(json['type']), + 'durationMinutes': json['duration_minutes'], + 'start': json['start'] == null ? undefined : (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + }; +} + +export function BreakTimeManualToJSON(json: any): BreakTimeManual { + return BreakTimeManualToJSONTyped(json, false); +} + +export function BreakTimeManualToJSONTyped(value?: BreakTimeManual | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'type': BreakTimeTypeToJSON(value['type']), + 'duration_minutes': value['durationMinutes'], + 'start': value['start'] == null ? value['start'] : value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + }; +} + diff --git a/sdk/typescript-fetch/src/models/BreakTimeOngoing.ts b/sdk/typescript-fetch/src/models/BreakTimeOngoing.ts new file mode 100644 index 0000000..339ea9c --- /dev/null +++ b/sdk/typescript-fetch/src/models/BreakTimeOngoing.ts @@ -0,0 +1,85 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { BreakTimeType } from './BreakTimeType'; +import { + BreakTimeTypeFromJSON, + BreakTimeTypeFromJSONTyped, + BreakTimeTypeToJSON, + BreakTimeTypeToJSONTyped, +} from './BreakTimeType'; + +/** + * + * @export + * @interface BreakTimeOngoing + */ +export interface BreakTimeOngoing { + /** + * + * @type {BreakTimeType} + * @memberof BreakTimeOngoing + */ + type: BreakTimeType; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof BreakTimeOngoing + */ + start: Date; +} + + + +/** + * Check if a given object implements the BreakTimeOngoing interface. + */ +export function instanceOfBreakTimeOngoing(value: object): value is BreakTimeOngoing { + if (!('type' in value) || value['type'] === undefined) return false; + if (!('start' in value) || value['start'] === undefined) return false; + return true; +} + +export function BreakTimeOngoingFromJSON(json: any): BreakTimeOngoing { + return BreakTimeOngoingFromJSONTyped(json, false); +} + +export function BreakTimeOngoingFromJSONTyped(json: any, ignoreDiscriminator: boolean): BreakTimeOngoing { + if (json == null) { + return json; + } + return { + + 'type': BreakTimeTypeFromJSON(json['type']), + 'start': (new Date(json['start'])), + }; +} + +export function BreakTimeOngoingToJSON(json: any): BreakTimeOngoing { + return BreakTimeOngoingToJSONTyped(json, false); +} + +export function BreakTimeOngoingToJSONTyped(value?: BreakTimeOngoing | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'type': BreakTimeTypeToJSON(value['type']), + 'start': value['start'].toISOString(), + }; +} + diff --git a/sdk/typescript-fetch/src/models/BreakTimeType.ts b/sdk/typescript-fetch/src/models/BreakTimeType.ts new file mode 100644 index 0000000..811019b --- /dev/null +++ b/sdk/typescript-fetch/src/models/BreakTimeType.ts @@ -0,0 +1,54 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Kind of break. `manual` was entered by the user, `automatic` was deducted by timr, `ongoing` is a break that has started and not yet ended. + * @export + */ +export const BreakTimeType = { + Manual: 'manual', + Ongoing: 'ongoing', + Automatic: 'automatic' +} as const; +export type BreakTimeType = typeof BreakTimeType[keyof typeof BreakTimeType]; + + +export function instanceOfBreakTimeType(value: any): boolean { + for (const key in BreakTimeType) { + if (Object.prototype.hasOwnProperty.call(BreakTimeType, key)) { + if (BreakTimeType[key as keyof typeof BreakTimeType] === value) { + return true; + } + } + } + return false; +} + +export function BreakTimeTypeFromJSON(json: any): BreakTimeType { + return BreakTimeTypeFromJSONTyped(json, false); +} + +export function BreakTimeTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): BreakTimeType { + return json as BreakTimeType; +} + +export function BreakTimeTypeToJSON(value?: BreakTimeType | null): any { + return value as any; +} + +export function BreakTimeTypeToJSONTyped(value: any, ignoreDiscriminator: boolean): BreakTimeType { + return value as BreakTimeType; +} + diff --git a/sdk/typescript-fetch/src/models/BreakTimeUpdate.ts b/sdk/typescript-fetch/src/models/BreakTimeUpdate.ts new file mode 100644 index 0000000..d3113d8 --- /dev/null +++ b/sdk/typescript-fetch/src/models/BreakTimeUpdate.ts @@ -0,0 +1,72 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import type { BreakTimeManual } from './BreakTimeManual'; +import { + instanceOfBreakTimeManual, + BreakTimeManualFromJSON, + BreakTimeManualFromJSONTyped, + BreakTimeManualToJSON, +} from './BreakTimeManual'; +import type { BreakTimeOngoing } from './BreakTimeOngoing'; +import { + instanceOfBreakTimeOngoing, + BreakTimeOngoingFromJSON, + BreakTimeOngoingFromJSONTyped, + BreakTimeOngoingToJSON, +} from './BreakTimeOngoing'; + +/** + * @type BreakTimeUpdate + * + * @export + */ +export type BreakTimeUpdate = { type: 'manual' } & BreakTimeManual | { type: 'ongoing' } & BreakTimeOngoing; + +export function BreakTimeUpdateFromJSON(json: any): BreakTimeUpdate { + return BreakTimeUpdateFromJSONTyped(json, false); +} + +export function BreakTimeUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): BreakTimeUpdate { + if (json == null) { + return json; + } + switch (json['type']) { + case 'manual': + return Object.assign({}, BreakTimeManualFromJSONTyped(json, true), { type: 'manual' } as const); + case 'ongoing': + return Object.assign({}, BreakTimeOngoingFromJSONTyped(json, true), { type: 'ongoing' } as const); + default: + return json; + } +} + +export function BreakTimeUpdateToJSON(json: any): any { + return BreakTimeUpdateToJSONTyped(json, false); +} + +export function BreakTimeUpdateToJSONTyped(value?: BreakTimeUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + switch (value['type']) { + case 'manual': + return Object.assign({}, BreakTimeManualToJSON(value), { type: 'manual' } as const); + case 'ongoing': + return Object.assign({}, BreakTimeOngoingToJSON(value), { type: 'ongoing' } as const); + default: + return value; + } +} + diff --git a/sdk/typescript-fetch/src/models/BudgetPlanningType.ts b/sdk/typescript-fetch/src/models/BudgetPlanningType.ts new file mode 100644 index 0000000..89c8d18 --- /dev/null +++ b/sdk/typescript-fetch/src/models/BudgetPlanningType.ts @@ -0,0 +1,60 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * corresponding to the chosen planning type some properties cannot be set: + * * none: no further budget properties can be set + * * user_hourly_rate: budget_hourly_rate cannot be set + * + * for the remaining two types all budget properties are supported + * + * @export + */ +export const BudgetPlanningType = { + None: 'none', + TaskHourlyRate: 'task_hourly_rate', + UserHourlyRate: 'user_hourly_rate', + FixedPrice: 'fixed_price' +} as const; +export type BudgetPlanningType = typeof BudgetPlanningType[keyof typeof BudgetPlanningType]; + + +export function instanceOfBudgetPlanningType(value: any): boolean { + for (const key in BudgetPlanningType) { + if (Object.prototype.hasOwnProperty.call(BudgetPlanningType, key)) { + if (BudgetPlanningType[key as keyof typeof BudgetPlanningType] === value) { + return true; + } + } + } + return false; +} + +export function BudgetPlanningTypeFromJSON(json: any): BudgetPlanningType { + return BudgetPlanningTypeFromJSONTyped(json, false); +} + +export function BudgetPlanningTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): BudgetPlanningType { + return json as BudgetPlanningType; +} + +export function BudgetPlanningTypeToJSON(value?: BudgetPlanningType | null): any { + return value as any; +} + +export function BudgetPlanningTypeToJSONTyped(value: any, ignoreDiscriminator: boolean): BudgetPlanningType { + return value as BudgetPlanningType; +} + diff --git a/sdk/typescript-fetch/src/models/BudgetPlanningTypeRequest.ts b/sdk/typescript-fetch/src/models/BudgetPlanningTypeRequest.ts new file mode 100644 index 0000000..1e171a8 --- /dev/null +++ b/sdk/typescript-fetch/src/models/BudgetPlanningTypeRequest.ts @@ -0,0 +1,62 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * corresponding to the chosen planning type some properties cannot be set: + * * none: no further budget properties can be set + * * user_hourly_rate: budget_hourly_rate cannot be set + * * inherited: budget settings are inherited from the parent task + * + * for the remaining two types all budget properties are supported + * + * @export + */ +export const BudgetPlanningTypeRequest = { + None: 'none', + TaskHourlyRate: 'task_hourly_rate', + UserHourlyRate: 'user_hourly_rate', + FixedPrice: 'fixed_price', + Inherited: 'inherited' +} as const; +export type BudgetPlanningTypeRequest = typeof BudgetPlanningTypeRequest[keyof typeof BudgetPlanningTypeRequest]; + + +export function instanceOfBudgetPlanningTypeRequest(value: any): boolean { + for (const key in BudgetPlanningTypeRequest) { + if (Object.prototype.hasOwnProperty.call(BudgetPlanningTypeRequest, key)) { + if (BudgetPlanningTypeRequest[key as keyof typeof BudgetPlanningTypeRequest] === value) { + return true; + } + } + } + return false; +} + +export function BudgetPlanningTypeRequestFromJSON(json: any): BudgetPlanningTypeRequest { + return BudgetPlanningTypeRequestFromJSONTyped(json, false); +} + +export function BudgetPlanningTypeRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): BudgetPlanningTypeRequest { + return json as BudgetPlanningTypeRequest; +} + +export function BudgetPlanningTypeRequestToJSON(value?: BudgetPlanningTypeRequest | null): any { + return value as any; +} + +export function BudgetPlanningTypeRequestToJSONTyped(value: any, ignoreDiscriminator: boolean): BudgetPlanningTypeRequest { + return value as BudgetPlanningTypeRequest; +} + diff --git a/sdk/typescript-fetch/src/models/Car.ts b/sdk/typescript-fetch/src/models/Car.ts new file mode 100644 index 0000000..d8a8f48 --- /dev/null +++ b/sdk/typescript-fetch/src/models/Car.ts @@ -0,0 +1,111 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * A vehicle identified by `name` and license `plate`. `usable` says whether it can currently be selected. + * + * @export + * @interface Car + */ +export interface Car { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof Car + */ + id: string; + /** + * + * @type {string} + * @memberof Car + */ + name: string; + /** + * + * @type {string} + * @memberof Car + */ + plate: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof Car + */ + externalId: string | null; + /** + * + * @type {boolean} + * @memberof Car + */ + usable: boolean; + /** + * + * @type {{ [key: string]: any; }} + * @memberof Car + */ + metadata?: { [key: string]: any; } | null; +} + +/** + * Check if a given object implements the Car interface. + */ +export function instanceOfCar(value: object): value is Car { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('plate' in value) || value['plate'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + if (!('usable' in value) || value['usable'] === undefined) return false; + return true; +} + +export function CarFromJSON(json: any): Car { + return CarFromJSONTyped(json, false); +} + +export function CarFromJSONTyped(json: any, ignoreDiscriminator: boolean): Car { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'plate': json['plate'], + 'externalId': json['external_id'], + 'usable': json['usable'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function CarToJSON(json: any): Car { + return CarToJSONTyped(json, false); +} + +export function CarToJSONTyped(value?: Car | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'plate': value['plate'], + 'external_id': value['externalId'], + 'usable': value['usable'], + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/CarCreate.ts b/sdk/typescript-fetch/src/models/CarCreate.ts new file mode 100644 index 0000000..98a308c --- /dev/null +++ b/sdk/typescript-fetch/src/models/CarCreate.ts @@ -0,0 +1,99 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface CarCreate + */ +export interface CarCreate { + /** + * + * @type {string} + * @memberof CarCreate + */ + name: string; + /** + * + * @type {string} + * @memberof CarCreate + */ + plate: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof CarCreate + */ + externalId?: string | null; + /** + * + * @type {boolean} + * @memberof CarCreate + */ + usable?: boolean; + /** + * + * @type {{ [key: string]: any; }} + * @memberof CarCreate + */ + metadata?: { [key: string]: any; } | null; +} + +/** + * Check if a given object implements the CarCreate interface. + */ +export function instanceOfCarCreate(value: object): value is CarCreate { + if (!('name' in value) || value['name'] === undefined) return false; + if (!('plate' in value) || value['plate'] === undefined) return false; + return true; +} + +export function CarCreateFromJSON(json: any): CarCreate { + return CarCreateFromJSONTyped(json, false); +} + +export function CarCreateFromJSONTyped(json: any, ignoreDiscriminator: boolean): CarCreate { + if (json == null) { + return json; + } + return { + + 'name': json['name'], + 'plate': json['plate'], + 'externalId': json['external_id'] == null ? undefined : json['external_id'], + 'usable': json['usable'] == null ? undefined : json['usable'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function CarCreateToJSON(json: any): CarCreate { + return CarCreateToJSONTyped(json, false); +} + +export function CarCreateToJSONTyped(value?: CarCreate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'name': value['name'], + 'plate': value['plate'], + 'external_id': value['externalId'], + 'usable': value['usable'], + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/CarPartial.ts b/sdk/typescript-fetch/src/models/CarPartial.ts new file mode 100644 index 0000000..3e65ef2 --- /dev/null +++ b/sdk/typescript-fetch/src/models/CarPartial.ts @@ -0,0 +1,93 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface CarPartial + */ +export interface CarPartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof CarPartial + */ + id: string; + /** + * + * @type {string} + * @memberof CarPartial + */ + name: string; + /** + * + * @type {string} + * @memberof CarPartial + */ + plate: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof CarPartial + */ + externalId: string | null; +} + +/** + * Check if a given object implements the CarPartial interface. + */ +export function instanceOfCarPartial(value: object): value is CarPartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('plate' in value) || value['plate'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + return true; +} + +export function CarPartialFromJSON(json: any): CarPartial { + return CarPartialFromJSONTyped(json, false); +} + +export function CarPartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): CarPartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'plate': json['plate'], + 'externalId': json['external_id'], + }; +} + +export function CarPartialToJSON(json: any): CarPartial { + return CarPartialToJSONTyped(json, false); +} + +export function CarPartialToJSONTyped(value?: CarPartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'plate': value['plate'], + 'external_id': value['externalId'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/CarUpdate.ts b/sdk/typescript-fetch/src/models/CarUpdate.ts new file mode 100644 index 0000000..64c6bb3 --- /dev/null +++ b/sdk/typescript-fetch/src/models/CarUpdate.ts @@ -0,0 +1,97 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface CarUpdate + */ +export interface CarUpdate { + /** + * + * @type {string} + * @memberof CarUpdate + */ + name?: string; + /** + * + * @type {string} + * @memberof CarUpdate + */ + plate?: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof CarUpdate + */ + externalId?: string | null; + /** + * + * @type {boolean} + * @memberof CarUpdate + */ + usable?: boolean; + /** + * + * @type {{ [key: string]: any; }} + * @memberof CarUpdate + */ + metadata?: { [key: string]: any; } | null; +} + +/** + * Check if a given object implements the CarUpdate interface. + */ +export function instanceOfCarUpdate(value: object): value is CarUpdate { + return true; +} + +export function CarUpdateFromJSON(json: any): CarUpdate { + return CarUpdateFromJSONTyped(json, false); +} + +export function CarUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): CarUpdate { + if (json == null) { + return json; + } + return { + + 'name': json['name'] == null ? undefined : json['name'], + 'plate': json['plate'] == null ? undefined : json['plate'], + 'externalId': json['external_id'] == null ? undefined : json['external_id'], + 'usable': json['usable'] == null ? undefined : json['usable'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function CarUpdateToJSON(json: any): CarUpdate { + return CarUpdateToJSONTyped(json, false); +} + +export function CarUpdateToJSONTyped(value?: CarUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'name': value['name'], + 'plate': value['plate'], + 'external_id': value['externalId'], + 'usable': value['usable'], + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/CarsPage.ts b/sdk/typescript-fetch/src/models/CarsPage.ts new file mode 100644 index 0000000..920e0af --- /dev/null +++ b/sdk/typescript-fetch/src/models/CarsPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { Car } from './Car'; +import { + CarFromJSON, + CarFromJSONTyped, + CarToJSON, + CarToJSONTyped, +} from './Car'; + +/** + * + * @export + * @interface CarsPage + */ +export interface CarsPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof CarsPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof CarsPage + */ + data: Array; +} + +/** + * Check if a given object implements the CarsPage interface. + */ +export function instanceOfCarsPage(value: object): value is CarsPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function CarsPageFromJSON(json: any): CarsPage { + return CarsPageFromJSONTyped(json, false); +} + +export function CarsPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): CarsPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(CarFromJSON)), + }; +} + +export function CarsPageToJSON(json: any): CarsPage { + return CarsPageToJSONTyped(json, false); +} + +export function CarsPageToJSONTyped(value?: CarsPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(CarToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/CarsSortColumn.ts b/sdk/typescript-fetch/src/models/CarsSortColumn.ts new file mode 100644 index 0000000..0a34c4a --- /dev/null +++ b/sdk/typescript-fetch/src/models/CarsSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Cars. + * @export + */ +export const CarsSortColumn = { + Name: 'name' +} as const; +export type CarsSortColumn = typeof CarsSortColumn[keyof typeof CarsSortColumn]; + + +export function instanceOfCarsSortColumn(value: any): boolean { + for (const key in CarsSortColumn) { + if (Object.prototype.hasOwnProperty.call(CarsSortColumn, key)) { + if (CarsSortColumn[key as keyof typeof CarsSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function CarsSortColumnFromJSON(json: any): CarsSortColumn { + return CarsSortColumnFromJSONTyped(json, false); +} + +export function CarsSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): CarsSortColumn { + return json as CarsSortColumn; +} + +export function CarsSortColumnToJSON(value?: CarsSortColumn | null): any { + return value as any; +} + +export function CarsSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): CarsSortColumn { + return value as CarsSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/DailyWorkSchedule.ts b/sdk/typescript-fetch/src/models/DailyWorkSchedule.ts new file mode 100644 index 0000000..67465db --- /dev/null +++ b/sdk/typescript-fetch/src/models/DailyWorkSchedule.ts @@ -0,0 +1,82 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { NormalWorkingTimes } from './NormalWorkingTimes'; +import { + NormalWorkingTimesFromJSON, + NormalWorkingTimesFromJSONTyped, + NormalWorkingTimesToJSON, + NormalWorkingTimesToJSONTyped, +} from './NormalWorkingTimes'; + +/** + * + * @export + * @interface DailyWorkSchedule + */ +export interface DailyWorkSchedule { + /** + * value in minutes + * @type {number} + * @memberof DailyWorkSchedule + */ + targetDurationMinutes: number; + /** + * this property is always set, when the WorkScheduleModel is of type normal_working_time, in contrast when the WorkScheduleModel is of type daily_target_hours it is not set + * @type {Array} + * @memberof DailyWorkSchedule + */ + normalWorkingTimes?: Array; +} + +/** + * Check if a given object implements the DailyWorkSchedule interface. + */ +export function instanceOfDailyWorkSchedule(value: object): value is DailyWorkSchedule { + if (!('targetDurationMinutes' in value) || value['targetDurationMinutes'] === undefined) return false; + return true; +} + +export function DailyWorkScheduleFromJSON(json: any): DailyWorkSchedule { + return DailyWorkScheduleFromJSONTyped(json, false); +} + +export function DailyWorkScheduleFromJSONTyped(json: any, ignoreDiscriminator: boolean): DailyWorkSchedule { + if (json == null) { + return json; + } + return { + + 'targetDurationMinutes': json['target_duration_minutes'], + 'normalWorkingTimes': json['normal_working_times'] == null ? undefined : ((json['normal_working_times'] as Array).map(NormalWorkingTimesFromJSON)), + }; +} + +export function DailyWorkScheduleToJSON(json: any): DailyWorkSchedule { + return DailyWorkScheduleToJSONTyped(json, false); +} + +export function DailyWorkScheduleToJSONTyped(value?: DailyWorkSchedule | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'target_duration_minutes': value['targetDurationMinutes'], + 'normal_working_times': value['normalWorkingTimes'] == null ? undefined : ((value['normalWorkingTimes'] as Array).map(NormalWorkingTimesToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/DeletedEntryPage.ts b/sdk/typescript-fetch/src/models/DeletedEntryPage.ts new file mode 100644 index 0000000..3322f63 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DeletedEntryPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DeletedEntryPartial } from './DeletedEntryPartial'; +import { + DeletedEntryPartialFromJSON, + DeletedEntryPartialFromJSONTyped, + DeletedEntryPartialToJSON, + DeletedEntryPartialToJSONTyped, +} from './DeletedEntryPartial'; + +/** + * + * @export + * @interface DeletedEntryPage + */ +export interface DeletedEntryPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof DeletedEntryPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof DeletedEntryPage + */ + data: Array; +} + +/** + * Check if a given object implements the DeletedEntryPage interface. + */ +export function instanceOfDeletedEntryPage(value: object): value is DeletedEntryPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function DeletedEntryPageFromJSON(json: any): DeletedEntryPage { + return DeletedEntryPageFromJSONTyped(json, false); +} + +export function DeletedEntryPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): DeletedEntryPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(DeletedEntryPartialFromJSON)), + }; +} + +export function DeletedEntryPageToJSON(json: any): DeletedEntryPage { + return DeletedEntryPageToJSONTyped(json, false); +} + +export function DeletedEntryPageToJSONTyped(value?: DeletedEntryPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(DeletedEntryPartialToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/DeletedEntryPartial.ts b/sdk/typescript-fetch/src/models/DeletedEntryPartial.ts new file mode 100644 index 0000000..84da8e5 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DeletedEntryPartial.ts @@ -0,0 +1,94 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; + +/** + * + * @export + * @interface DeletedEntryPartial + */ +export interface DeletedEntryPartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof DeletedEntryPartial + */ + id: string; + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof DeletedEntryPartial + */ + lastModified: Date; + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * + * @type {UserPartial} + * @memberof DeletedEntryPartial + */ + lastModifiedBy: UserPartial | null; +} + +/** + * Check if a given object implements the DeletedEntryPartial interface. + */ +export function instanceOfDeletedEntryPartial(value: object): value is DeletedEntryPartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('lastModified' in value) || value['lastModified'] === undefined) return false; + if (!('lastModifiedBy' in value) || value['lastModifiedBy'] === undefined) return false; + return true; +} + +export function DeletedEntryPartialFromJSON(json: any): DeletedEntryPartial { + return DeletedEntryPartialFromJSONTyped(json, false); +} + +export function DeletedEntryPartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): DeletedEntryPartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'lastModified': (new Date(json['last_modified'])), + 'lastModifiedBy': UserPartialFromJSON(json['last_modified_by']), + }; +} + +export function DeletedEntryPartialToJSON(json: any): DeletedEntryPartial { + return DeletedEntryPartialToJSONTyped(json, false); +} + +export function DeletedEntryPartialToJSONTyped(value?: DeletedEntryPartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'last_modified': value['lastModified'].toISOString(), + 'last_modified_by': UserPartialToJSON(value['lastModifiedBy']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/DeletedEntrySortColumn.ts b/sdk/typescript-fetch/src/models/DeletedEntrySortColumn.ts new file mode 100644 index 0000000..2956aa1 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DeletedEntrySortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for deleted entries. + * @export + */ +export const DeletedEntrySortColumn = { + LastModified: 'last_modified' +} as const; +export type DeletedEntrySortColumn = typeof DeletedEntrySortColumn[keyof typeof DeletedEntrySortColumn]; + + +export function instanceOfDeletedEntrySortColumn(value: any): boolean { + for (const key in DeletedEntrySortColumn) { + if (Object.prototype.hasOwnProperty.call(DeletedEntrySortColumn, key)) { + if (DeletedEntrySortColumn[key as keyof typeof DeletedEntrySortColumn] === value) { + return true; + } + } + } + return false; +} + +export function DeletedEntrySortColumnFromJSON(json: any): DeletedEntrySortColumn { + return DeletedEntrySortColumnFromJSONTyped(json, false); +} + +export function DeletedEntrySortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): DeletedEntrySortColumn { + return json as DeletedEntrySortColumn; +} + +export function DeletedEntrySortColumnToJSON(value?: DeletedEntrySortColumn | null): any { + return value as any; +} + +export function DeletedEntrySortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): DeletedEntrySortColumn { + return value as DeletedEntrySortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/DeletedEntryWithMetadata.ts b/sdk/typescript-fetch/src/models/DeletedEntryWithMetadata.ts new file mode 100644 index 0000000..7506f9e --- /dev/null +++ b/sdk/typescript-fetch/src/models/DeletedEntryWithMetadata.ts @@ -0,0 +1,102 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; + +/** + * + * @export + * @interface DeletedEntryWithMetadata + */ +export interface DeletedEntryWithMetadata { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof DeletedEntryWithMetadata + */ + id: string; + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof DeletedEntryWithMetadata + */ + lastModified: Date; + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * + * @type {UserPartial} + * @memberof DeletedEntryWithMetadata + */ + lastModifiedBy: UserPartial | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof DeletedEntryWithMetadata + */ + metadata?: { [key: string]: any; } | null; +} + +/** + * Check if a given object implements the DeletedEntryWithMetadata interface. + */ +export function instanceOfDeletedEntryWithMetadata(value: object): value is DeletedEntryWithMetadata { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('lastModified' in value) || value['lastModified'] === undefined) return false; + if (!('lastModifiedBy' in value) || value['lastModifiedBy'] === undefined) return false; + return true; +} + +export function DeletedEntryWithMetadataFromJSON(json: any): DeletedEntryWithMetadata { + return DeletedEntryWithMetadataFromJSONTyped(json, false); +} + +export function DeletedEntryWithMetadataFromJSONTyped(json: any, ignoreDiscriminator: boolean): DeletedEntryWithMetadata { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'lastModified': (new Date(json['last_modified'])), + 'lastModifiedBy': UserPartialFromJSON(json['last_modified_by']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function DeletedEntryWithMetadataToJSON(json: any): DeletedEntryWithMetadata { + return DeletedEntryWithMetadataToJSONTyped(json, false); +} + +export function DeletedEntryWithMetadataToJSONTyped(value?: DeletedEntryWithMetadata | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'last_modified': value['lastModified'].toISOString(), + 'last_modified_by': UserPartialToJSON(value['lastModifiedBy']), + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/DeletedEntryWithMetadataPage.ts b/sdk/typescript-fetch/src/models/DeletedEntryWithMetadataPage.ts new file mode 100644 index 0000000..2a0c6a2 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DeletedEntryWithMetadataPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DeletedEntryWithMetadata } from './DeletedEntryWithMetadata'; +import { + DeletedEntryWithMetadataFromJSON, + DeletedEntryWithMetadataFromJSONTyped, + DeletedEntryWithMetadataToJSON, + DeletedEntryWithMetadataToJSONTyped, +} from './DeletedEntryWithMetadata'; + +/** + * + * @export + * @interface DeletedEntryWithMetadataPage + */ +export interface DeletedEntryWithMetadataPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof DeletedEntryWithMetadataPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof DeletedEntryWithMetadataPage + */ + data: Array; +} + +/** + * Check if a given object implements the DeletedEntryWithMetadataPage interface. + */ +export function instanceOfDeletedEntryWithMetadataPage(value: object): value is DeletedEntryWithMetadataPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function DeletedEntryWithMetadataPageFromJSON(json: any): DeletedEntryWithMetadataPage { + return DeletedEntryWithMetadataPageFromJSONTyped(json, false); +} + +export function DeletedEntryWithMetadataPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): DeletedEntryWithMetadataPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(DeletedEntryWithMetadataFromJSON)), + }; +} + +export function DeletedEntryWithMetadataPageToJSON(json: any): DeletedEntryWithMetadataPage { + return DeletedEntryWithMetadataPageToJSONTyped(json, false); +} + +export function DeletedEntryWithMetadataPageToJSONTyped(value?: DeletedEntryWithMetadataPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(DeletedEntryWithMetadataToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLog.ts b/sdk/typescript-fetch/src/models/DriveLog.ts new file mode 100644 index 0000000..c61410e --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLog.ts @@ -0,0 +1,343 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { Platform } from './Platform'; +import { + PlatformFromJSON, + PlatformFromJSONTyped, + PlatformToJSON, + PlatformToJSONTyped, +} from './Platform'; +import type { DriveLogStatus } from './DriveLogStatus'; +import { + DriveLogStatusFromJSON, + DriveLogStatusFromJSONTyped, + DriveLogStatusToJSON, + DriveLogStatusToJSONTyped, +} from './DriveLogStatus'; +import type { Duration } from './Duration'; +import { + DurationFromJSON, + DurationFromJSONTyped, + DurationToJSON, + DurationToJSONTyped, +} from './Duration'; +import type { DriveLogCategoryPartial } from './DriveLogCategoryPartial'; +import { + DriveLogCategoryPartialFromJSON, + DriveLogCategoryPartialFromJSONTyped, + DriveLogCategoryPartialToJSON, + DriveLogCategoryPartialToJSONTyped, +} from './DriveLogCategoryPartial'; +import type { VenuePartial } from './VenuePartial'; +import { + VenuePartialFromJSON, + VenuePartialFromJSONTyped, + VenuePartialToJSON, + VenuePartialToJSONTyped, +} from './VenuePartial'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; +import type { CarPartial } from './CarPartial'; +import { + CarPartialFromJSON, + CarPartialFromJSONTyped, + CarPartialToJSON, + CarPartialToJSONTyped, +} from './CarPartial'; +import type { Location } from './Location'; +import { + LocationFromJSON, + LocationFromJSONTyped, + LocationToJSON, + LocationToJSONTyped, +} from './Location'; + +/** + * One trip in a `car`: `start` and `end`, `start_mileage` and `end_mileage` with the resulting `distance`, the `purpose`, the places `visited`, and its `drive_log_category`. May include a recorded GPS `route`. + * + * @export + * @interface DriveLog + */ +export interface DriveLog { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof DriveLog + */ + id: string; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof DriveLog + */ + start: Date; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof DriveLog + */ + end: Date | null; + /** + * + * @type {Duration} + * @memberof DriveLog + */ + duration: Duration | null; + /** + * + * @type {boolean} + * @memberof DriveLog + */ + changed: boolean; + /** + * + * @type {number} + * @memberof DriveLog + */ + startMileage: number; + /** + * + * @type {number} + * @memberof DriveLog + */ + endMileage: number | null; + /** + * Driven distance in kilometers + * @type {number} + * @memberof DriveLog + */ + distance: number | null; + /** + * + * @type {string} + * @memberof DriveLog + */ + route: string | null; + /** + * + * @type {string} + * @memberof DriveLog + */ + purpose: string | null; + /** + * + * @type {string} + * @memberof DriveLog + */ + visited: string | null; + /** + * + * @type {UserPartial} + * @memberof DriveLog + */ + user: UserPartial; + /** + * + * @type {CarPartial} + * @memberof DriveLog + */ + car: CarPartial; + /** + * + * @type {DriveLogCategoryPartial} + * @memberof DriveLog + */ + driveLogCategory: DriveLogCategoryPartial; + /** + * + * @type {VenuePartial} + * @memberof DriveLog + */ + startVenue: VenuePartial | null; + /** + * + * @type {VenuePartial} + * @memberof DriveLog + */ + endVenue: VenuePartial | null; + /** + * + * @type {boolean} + * @memberof DriveLog + */ + hasTrack: boolean; + /** + * + * @type {Location} + * @memberof DriveLog + */ + startLocation: Location | null; + /** + * + * @type {Location} + * @memberof DriveLog + */ + endLocation: Location | null; + /** + * + * @type {Platform} + * @memberof DriveLog + */ + startPlatform: Platform | null; + /** + * + * @type {Platform} + * @memberof DriveLog + */ + endPlatform: Platform | null; + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof DriveLog + */ + lastModified: Date; + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * + * @type {UserPartial} + * @memberof DriveLog + */ + lastModifiedBy: UserPartial | null; + /** + * + * @type {DriveLogStatus} + * @memberof DriveLog + */ + status: DriveLogStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof DriveLog + */ + metadata?: { [key: string]: any; } | null; +} + + + +/** + * Check if a given object implements the DriveLog interface. + */ +export function instanceOfDriveLog(value: object): value is DriveLog { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('start' in value) || value['start'] === undefined) return false; + if (!('end' in value) || value['end'] === undefined) return false; + if (!('duration' in value) || value['duration'] === undefined) return false; + if (!('changed' in value) || value['changed'] === undefined) return false; + if (!('startMileage' in value) || value['startMileage'] === undefined) return false; + if (!('endMileage' in value) || value['endMileage'] === undefined) return false; + if (!('distance' in value) || value['distance'] === undefined) return false; + if (!('route' in value) || value['route'] === undefined) return false; + if (!('purpose' in value) || value['purpose'] === undefined) return false; + if (!('visited' in value) || value['visited'] === undefined) return false; + if (!('user' in value) || value['user'] === undefined) return false; + if (!('car' in value) || value['car'] === undefined) return false; + if (!('driveLogCategory' in value) || value['driveLogCategory'] === undefined) return false; + if (!('startVenue' in value) || value['startVenue'] === undefined) return false; + if (!('endVenue' in value) || value['endVenue'] === undefined) return false; + if (!('hasTrack' in value) || value['hasTrack'] === undefined) return false; + if (!('startLocation' in value) || value['startLocation'] === undefined) return false; + if (!('endLocation' in value) || value['endLocation'] === undefined) return false; + if (!('startPlatform' in value) || value['startPlatform'] === undefined) return false; + if (!('endPlatform' in value) || value['endPlatform'] === undefined) return false; + if (!('lastModified' in value) || value['lastModified'] === undefined) return false; + if (!('lastModifiedBy' in value) || value['lastModifiedBy'] === undefined) return false; + if (!('status' in value) || value['status'] === undefined) return false; + return true; +} + +export function DriveLogFromJSON(json: any): DriveLog { + return DriveLogFromJSONTyped(json, false); +} + +export function DriveLogFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLog { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'start': (new Date(json['start'])), + 'end': (json['end'] == null ? null : new Date(json['end'])), + 'duration': DurationFromJSON(json['duration']), + 'changed': json['changed'], + 'startMileage': json['start_mileage'], + 'endMileage': json['end_mileage'], + 'distance': json['distance'], + 'route': json['route'], + 'purpose': json['purpose'], + 'visited': json['visited'], + 'user': UserPartialFromJSON(json['user']), + 'car': CarPartialFromJSON(json['car']), + 'driveLogCategory': DriveLogCategoryPartialFromJSON(json['drive_log_category']), + 'startVenue': VenuePartialFromJSON(json['start_venue']), + 'endVenue': VenuePartialFromJSON(json['end_venue']), + 'hasTrack': json['has_track'], + 'startLocation': LocationFromJSON(json['start_location']), + 'endLocation': LocationFromJSON(json['end_location']), + 'startPlatform': PlatformFromJSON(json['start_platform']), + 'endPlatform': PlatformFromJSON(json['end_platform']), + 'lastModified': (new Date(json['last_modified'])), + 'lastModifiedBy': UserPartialFromJSON(json['last_modified_by']), + 'status': DriveLogStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function DriveLogToJSON(json: any): DriveLog { + return DriveLogToJSONTyped(json, false); +} + +export function DriveLogToJSONTyped(value?: DriveLog | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'start': value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'duration': DurationToJSON(value['duration']), + 'changed': value['changed'], + 'start_mileage': value['startMileage'], + 'end_mileage': value['endMileage'], + 'distance': value['distance'], + 'route': value['route'], + 'purpose': value['purpose'], + 'visited': value['visited'], + 'user': UserPartialToJSON(value['user']), + 'car': CarPartialToJSON(value['car']), + 'drive_log_category': DriveLogCategoryPartialToJSON(value['driveLogCategory']), + 'start_venue': VenuePartialToJSON(value['startVenue']), + 'end_venue': VenuePartialToJSON(value['endVenue']), + 'has_track': value['hasTrack'], + 'start_location': LocationToJSON(value['startLocation']), + 'end_location': LocationToJSON(value['endLocation']), + 'start_platform': PlatformToJSON(value['startPlatform']), + 'end_platform': PlatformToJSON(value['endPlatform']), + 'last_modified': value['lastModified'].toISOString(), + 'last_modified_by': UserPartialToJSON(value['lastModifiedBy']), + 'status': DriveLogStatusToJSON(value['status']), + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogCategoriesPage.ts b/sdk/typescript-fetch/src/models/DriveLogCategoriesPage.ts new file mode 100644 index 0000000..e39c9bd --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogCategoriesPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DriveLogCategory } from './DriveLogCategory'; +import { + DriveLogCategoryFromJSON, + DriveLogCategoryFromJSONTyped, + DriveLogCategoryToJSON, + DriveLogCategoryToJSONTyped, +} from './DriveLogCategory'; + +/** + * + * @export + * @interface DriveLogCategoriesPage + */ +export interface DriveLogCategoriesPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof DriveLogCategoriesPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof DriveLogCategoriesPage + */ + data: Array; +} + +/** + * Check if a given object implements the DriveLogCategoriesPage interface. + */ +export function instanceOfDriveLogCategoriesPage(value: object): value is DriveLogCategoriesPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function DriveLogCategoriesPageFromJSON(json: any): DriveLogCategoriesPage { + return DriveLogCategoriesPageFromJSONTyped(json, false); +} + +export function DriveLogCategoriesPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogCategoriesPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(DriveLogCategoryFromJSON)), + }; +} + +export function DriveLogCategoriesPageToJSON(json: any): DriveLogCategoriesPage { + return DriveLogCategoriesPageToJSONTyped(json, false); +} + +export function DriveLogCategoriesPageToJSONTyped(value?: DriveLogCategoriesPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(DriveLogCategoryToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogCategoriesSortColumn.ts b/sdk/typescript-fetch/src/models/DriveLogCategoriesSortColumn.ts new file mode 100644 index 0000000..1fd5d26 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogCategoriesSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Drive Log Categories. + * @export + */ +export const DriveLogCategoriesSortColumn = { + Name: 'name' +} as const; +export type DriveLogCategoriesSortColumn = typeof DriveLogCategoriesSortColumn[keyof typeof DriveLogCategoriesSortColumn]; + + +export function instanceOfDriveLogCategoriesSortColumn(value: any): boolean { + for (const key in DriveLogCategoriesSortColumn) { + if (Object.prototype.hasOwnProperty.call(DriveLogCategoriesSortColumn, key)) { + if (DriveLogCategoriesSortColumn[key as keyof typeof DriveLogCategoriesSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function DriveLogCategoriesSortColumnFromJSON(json: any): DriveLogCategoriesSortColumn { + return DriveLogCategoriesSortColumnFromJSONTyped(json, false); +} + +export function DriveLogCategoriesSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogCategoriesSortColumn { + return json as DriveLogCategoriesSortColumn; +} + +export function DriveLogCategoriesSortColumnToJSON(value?: DriveLogCategoriesSortColumn | null): any { + return value as any; +} + +export function DriveLogCategoriesSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): DriveLogCategoriesSortColumn { + return value as DriveLogCategoriesSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogCategory.ts b/sdk/typescript-fetch/src/models/DriveLogCategory.ts new file mode 100644 index 0000000..599e596 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogCategory.ts @@ -0,0 +1,122 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; + +/** + * A drive log category with a `name` and a display `color`; `business` marks it as business travel. + * + * @export + * @interface DriveLogCategory + */ +export interface DriveLogCategory { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof DriveLogCategory + */ + id: string; + /** + * + * @type {string} + * @memberof DriveLogCategory + */ + name: string; + /** + * + * @type {boolean} + * @memberof DriveLogCategory + */ + business: boolean; + /** + * + * @type {string} + * @memberof DriveLogCategory + */ + color: string; + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof DriveLogCategory + */ + lastModified: Date; + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * + * @type {UserPartial} + * @memberof DriveLogCategory + */ + lastModifiedBy: UserPartial | null; +} + +/** + * Check if a given object implements the DriveLogCategory interface. + */ +export function instanceOfDriveLogCategory(value: object): value is DriveLogCategory { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('business' in value) || value['business'] === undefined) return false; + if (!('color' in value) || value['color'] === undefined) return false; + if (!('lastModified' in value) || value['lastModified'] === undefined) return false; + if (!('lastModifiedBy' in value) || value['lastModifiedBy'] === undefined) return false; + return true; +} + +export function DriveLogCategoryFromJSON(json: any): DriveLogCategory { + return DriveLogCategoryFromJSONTyped(json, false); +} + +export function DriveLogCategoryFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogCategory { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'business': json['business'], + 'color': json['color'], + 'lastModified': (new Date(json['last_modified'])), + 'lastModifiedBy': UserPartialFromJSON(json['last_modified_by']), + }; +} + +export function DriveLogCategoryToJSON(json: any): DriveLogCategory { + return DriveLogCategoryToJSONTyped(json, false); +} + +export function DriveLogCategoryToJSONTyped(value?: DriveLogCategory | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'business': value['business'], + 'color': value['color'], + 'last_modified': value['lastModified'].toISOString(), + 'last_modified_by': UserPartialToJSON(value['lastModifiedBy']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogCategoryPartial.ts b/sdk/typescript-fetch/src/models/DriveLogCategoryPartial.ts new file mode 100644 index 0000000..7ae5fda --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogCategoryPartial.ts @@ -0,0 +1,93 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface DriveLogCategoryPartial + */ +export interface DriveLogCategoryPartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof DriveLogCategoryPartial + */ + id: string; + /** + * + * @type {string} + * @memberof DriveLogCategoryPartial + */ + name: string; + /** + * + * @type {boolean} + * @memberof DriveLogCategoryPartial + */ + business: boolean; + /** + * + * @type {string} + * @memberof DriveLogCategoryPartial + */ + color: string; +} + +/** + * Check if a given object implements the DriveLogCategoryPartial interface. + */ +export function instanceOfDriveLogCategoryPartial(value: object): value is DriveLogCategoryPartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('business' in value) || value['business'] === undefined) return false; + if (!('color' in value) || value['color'] === undefined) return false; + return true; +} + +export function DriveLogCategoryPartialFromJSON(json: any): DriveLogCategoryPartial { + return DriveLogCategoryPartialFromJSONTyped(json, false); +} + +export function DriveLogCategoryPartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogCategoryPartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'business': json['business'], + 'color': json['color'], + }; +} + +export function DriveLogCategoryPartialToJSON(json: any): DriveLogCategoryPartial { + return DriveLogCategoryPartialToJSONTyped(json, false); +} + +export function DriveLogCategoryPartialToJSONTyped(value?: DriveLogCategoryPartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'business': value['business'], + 'color': value['color'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogCreate.ts b/sdk/typescript-fetch/src/models/DriveLogCreate.ts new file mode 100644 index 0000000..4a6b01a --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogCreate.ts @@ -0,0 +1,201 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { LocationCreate } from './LocationCreate'; +import { + LocationCreateFromJSON, + LocationCreateFromJSONTyped, + LocationCreateToJSON, + LocationCreateToJSONTyped, +} from './LocationCreate'; +import type { DriveLogStatus } from './DriveLogStatus'; +import { + DriveLogStatusFromJSON, + DriveLogStatusFromJSONTyped, + DriveLogStatusToJSON, + DriveLogStatusToJSONTyped, +} from './DriveLogStatus'; + +/** + * + * @export + * @interface DriveLogCreate + */ +export interface DriveLogCreate { + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof DriveLogCreate + */ + start: Date; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof DriveLogCreate + */ + end?: Date | null; + /** + * + * @type {boolean} + * @memberof DriveLogCreate + */ + changed: boolean; + /** + * + * @type {number} + * @memberof DriveLogCreate + */ + startMileage: number; + /** + * + * @type {number} + * @memberof DriveLogCreate + */ + endMileage?: number | null; + /** + * + * @type {string} + * @memberof DriveLogCreate + */ + route?: string | null; + /** + * + * @type {string} + * @memberof DriveLogCreate + */ + purpose?: string | null; + /** + * + * @type {string} + * @memberof DriveLogCreate + */ + visited?: string | null; + /** + * + * @type {string} + * @memberof DriveLogCreate + */ + driveLogCategoryId: string; + /** + * + * @type {DriveLogStatus} + * @memberof DriveLogCreate + */ + status: DriveLogStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof DriveLogCreate + */ + metadata?: { [key: string]: any; } | null; + /** + * + * @type {string} + * @memberof DriveLogCreate + */ + userId: string; + /** + * + * @type {string} + * @memberof DriveLogCreate + */ + carId: string; + /** + * + * @type {LocationCreate} + * @memberof DriveLogCreate + */ + startLocation?: LocationCreate | null; + /** + * + * @type {LocationCreate} + * @memberof DriveLogCreate + */ + endLocation?: LocationCreate | null; +} + + + +/** + * Check if a given object implements the DriveLogCreate interface. + */ +export function instanceOfDriveLogCreate(value: object): value is DriveLogCreate { + if (!('start' in value) || value['start'] === undefined) return false; + if (!('changed' in value) || value['changed'] === undefined) return false; + if (!('startMileage' in value) || value['startMileage'] === undefined) return false; + if (!('driveLogCategoryId' in value) || value['driveLogCategoryId'] === undefined) return false; + if (!('status' in value) || value['status'] === undefined) return false; + if (!('userId' in value) || value['userId'] === undefined) return false; + if (!('carId' in value) || value['carId'] === undefined) return false; + return true; +} + +export function DriveLogCreateFromJSON(json: any): DriveLogCreate { + return DriveLogCreateFromJSONTyped(json, false); +} + +export function DriveLogCreateFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogCreate { + if (json == null) { + return json; + } + return { + + 'start': (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'changed': json['changed'], + 'startMileage': json['start_mileage'], + 'endMileage': json['end_mileage'] == null ? undefined : json['end_mileage'], + 'route': json['route'] == null ? undefined : json['route'], + 'purpose': json['purpose'] == null ? undefined : json['purpose'], + 'visited': json['visited'] == null ? undefined : json['visited'], + 'driveLogCategoryId': json['drive_log_category_id'], + 'status': DriveLogStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + 'userId': json['user_id'], + 'carId': json['car_id'], + 'startLocation': json['start_location'] == null ? undefined : LocationCreateFromJSON(json['start_location']), + 'endLocation': json['end_location'] == null ? undefined : LocationCreateFromJSON(json['end_location']), + }; +} + +export function DriveLogCreateToJSON(json: any): DriveLogCreate { + return DriveLogCreateToJSONTyped(json, false); +} + +export function DriveLogCreateToJSONTyped(value?: DriveLogCreate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'changed': value['changed'], + 'start_mileage': value['startMileage'], + 'end_mileage': value['endMileage'], + 'route': value['route'], + 'purpose': value['purpose'], + 'visited': value['visited'], + 'drive_log_category_id': value['driveLogCategoryId'], + 'status': DriveLogStatusToJSON(value['status']), + 'metadata': value['metadata'], + 'user_id': value['userId'], + 'car_id': value['carId'], + 'start_location': LocationCreateToJSON(value['startLocation']), + 'end_location': LocationCreateToJSON(value['endLocation']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogStatus.ts b/sdk/typescript-fetch/src/models/DriveLogStatus.ts new file mode 100644 index 0000000..2f78e08 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogStatus.ts @@ -0,0 +1,58 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Processing state of a Drive Log. `running` means the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + * @export + */ +export const DriveLogStatus = { + Changeable: 'changeable', + Locked: 'locked', + Approved: 'approved', + Cleared: 'cleared', + Closed: 'closed', + Archived: 'archived', + Running: 'running' +} as const; +export type DriveLogStatus = typeof DriveLogStatus[keyof typeof DriveLogStatus]; + + +export function instanceOfDriveLogStatus(value: any): boolean { + for (const key in DriveLogStatus) { + if (Object.prototype.hasOwnProperty.call(DriveLogStatus, key)) { + if (DriveLogStatus[key as keyof typeof DriveLogStatus] === value) { + return true; + } + } + } + return false; +} + +export function DriveLogStatusFromJSON(json: any): DriveLogStatus { + return DriveLogStatusFromJSONTyped(json, false); +} + +export function DriveLogStatusFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogStatus { + return json as DriveLogStatus; +} + +export function DriveLogStatusToJSON(value?: DriveLogStatus | null): any { + return value as any; +} + +export function DriveLogStatusToJSONTyped(value: any, ignoreDiscriminator: boolean): DriveLogStatus { + return value as DriveLogStatus; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogUpdate.ts b/sdk/typescript-fetch/src/models/DriveLogUpdate.ts new file mode 100644 index 0000000..f199855 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogUpdate.ts @@ -0,0 +1,178 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DriveLogStatus } from './DriveLogStatus'; +import { + DriveLogStatusFromJSON, + DriveLogStatusFromJSONTyped, + DriveLogStatusToJSON, + DriveLogStatusToJSONTyped, +} from './DriveLogStatus'; +import type { LocationUpdate } from './LocationUpdate'; +import { + LocationUpdateFromJSON, + LocationUpdateFromJSONTyped, + LocationUpdateToJSON, + LocationUpdateToJSONTyped, +} from './LocationUpdate'; + +/** + * + * @export + * @interface DriveLogUpdate + */ +export interface DriveLogUpdate { + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof DriveLogUpdate + */ + start?: Date; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof DriveLogUpdate + */ + end?: Date | null; + /** + * + * @type {boolean} + * @memberof DriveLogUpdate + */ + changed?: boolean; + /** + * + * @type {number} + * @memberof DriveLogUpdate + */ + startMileage?: number; + /** + * + * @type {number} + * @memberof DriveLogUpdate + */ + endMileage?: number | null; + /** + * + * @type {string} + * @memberof DriveLogUpdate + */ + route?: string | null; + /** + * + * @type {string} + * @memberof DriveLogUpdate + */ + purpose?: string | null; + /** + * + * @type {string} + * @memberof DriveLogUpdate + */ + visited?: string | null; + /** + * + * @type {string} + * @memberof DriveLogUpdate + */ + driveLogCategoryId?: string; + /** + * + * @type {DriveLogStatus} + * @memberof DriveLogUpdate + */ + status?: DriveLogStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof DriveLogUpdate + */ + metadata?: { [key: string]: any; } | null; + /** + * + * @type {LocationUpdate} + * @memberof DriveLogUpdate + */ + startLocation?: LocationUpdate | null; + /** + * + * @type {LocationUpdate} + * @memberof DriveLogUpdate + */ + endLocation?: LocationUpdate | null; +} + + + +/** + * Check if a given object implements the DriveLogUpdate interface. + */ +export function instanceOfDriveLogUpdate(value: object): value is DriveLogUpdate { + return true; +} + +export function DriveLogUpdateFromJSON(json: any): DriveLogUpdate { + return DriveLogUpdateFromJSONTyped(json, false); +} + +export function DriveLogUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogUpdate { + if (json == null) { + return json; + } + return { + + 'start': json['start'] == null ? undefined : (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'changed': json['changed'] == null ? undefined : json['changed'], + 'startMileage': json['start_mileage'] == null ? undefined : json['start_mileage'], + 'endMileage': json['end_mileage'] == null ? undefined : json['end_mileage'], + 'route': json['route'] == null ? undefined : json['route'], + 'purpose': json['purpose'] == null ? undefined : json['purpose'], + 'visited': json['visited'] == null ? undefined : json['visited'], + 'driveLogCategoryId': json['drive_log_category_id'] == null ? undefined : json['drive_log_category_id'], + 'status': json['status'] == null ? undefined : DriveLogStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + 'startLocation': json['start_location'] == null ? undefined : LocationUpdateFromJSON(json['start_location']), + 'endLocation': json['end_location'] == null ? undefined : LocationUpdateFromJSON(json['end_location']), + }; +} + +export function DriveLogUpdateToJSON(json: any): DriveLogUpdate { + return DriveLogUpdateToJSONTyped(json, false); +} + +export function DriveLogUpdateToJSONTyped(value?: DriveLogUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'] == null ? value['start'] : value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'changed': value['changed'], + 'start_mileage': value['startMileage'], + 'end_mileage': value['endMileage'], + 'route': value['route'], + 'purpose': value['purpose'], + 'visited': value['visited'], + 'drive_log_category_id': value['driveLogCategoryId'], + 'status': DriveLogStatusToJSON(value['status']), + 'metadata': value['metadata'], + 'start_location': LocationUpdateToJSON(value['startLocation']), + 'end_location': LocationUpdateToJSON(value['endLocation']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogUpsert.ts b/sdk/typescript-fetch/src/models/DriveLogUpsert.ts new file mode 100644 index 0000000..772bef8 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogUpsert.ts @@ -0,0 +1,155 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DriveLogStatus } from './DriveLogStatus'; +import { + DriveLogStatusFromJSON, + DriveLogStatusFromJSONTyped, + DriveLogStatusToJSON, + DriveLogStatusToJSONTyped, +} from './DriveLogStatus'; + +/** + * + * @export + * @interface DriveLogUpsert + */ +export interface DriveLogUpsert { + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof DriveLogUpsert + */ + start?: Date; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof DriveLogUpsert + */ + end?: Date | null; + /** + * + * @type {boolean} + * @memberof DriveLogUpsert + */ + changed?: boolean; + /** + * + * @type {number} + * @memberof DriveLogUpsert + */ + startMileage?: number; + /** + * + * @type {number} + * @memberof DriveLogUpsert + */ + endMileage?: number | null; + /** + * + * @type {string} + * @memberof DriveLogUpsert + */ + route?: string | null; + /** + * + * @type {string} + * @memberof DriveLogUpsert + */ + purpose?: string | null; + /** + * + * @type {string} + * @memberof DriveLogUpsert + */ + visited?: string | null; + /** + * + * @type {string} + * @memberof DriveLogUpsert + */ + driveLogCategoryId?: string; + /** + * + * @type {DriveLogStatus} + * @memberof DriveLogUpsert + */ + status?: DriveLogStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof DriveLogUpsert + */ + metadata?: { [key: string]: any; } | null; +} + + + +/** + * Check if a given object implements the DriveLogUpsert interface. + */ +export function instanceOfDriveLogUpsert(value: object): value is DriveLogUpsert { + return true; +} + +export function DriveLogUpsertFromJSON(json: any): DriveLogUpsert { + return DriveLogUpsertFromJSONTyped(json, false); +} + +export function DriveLogUpsertFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogUpsert { + if (json == null) { + return json; + } + return { + + 'start': json['start'] == null ? undefined : (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'changed': json['changed'] == null ? undefined : json['changed'], + 'startMileage': json['start_mileage'] == null ? undefined : json['start_mileage'], + 'endMileage': json['end_mileage'] == null ? undefined : json['end_mileage'], + 'route': json['route'] == null ? undefined : json['route'], + 'purpose': json['purpose'] == null ? undefined : json['purpose'], + 'visited': json['visited'] == null ? undefined : json['visited'], + 'driveLogCategoryId': json['drive_log_category_id'] == null ? undefined : json['drive_log_category_id'], + 'status': json['status'] == null ? undefined : DriveLogStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function DriveLogUpsertToJSON(json: any): DriveLogUpsert { + return DriveLogUpsertToJSONTyped(json, false); +} + +export function DriveLogUpsertToJSONTyped(value?: DriveLogUpsert | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'] == null ? value['start'] : value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'changed': value['changed'], + 'start_mileage': value['startMileage'], + 'end_mileage': value['endMileage'], + 'route': value['route'], + 'purpose': value['purpose'], + 'visited': value['visited'], + 'drive_log_category_id': value['driveLogCategoryId'], + 'status': DriveLogStatusToJSON(value['status']), + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogsPage.ts b/sdk/typescript-fetch/src/models/DriveLogsPage.ts new file mode 100644 index 0000000..a4f6d5c --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogsPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DriveLog } from './DriveLog'; +import { + DriveLogFromJSON, + DriveLogFromJSONTyped, + DriveLogToJSON, + DriveLogToJSONTyped, +} from './DriveLog'; + +/** + * + * @export + * @interface DriveLogsPage + */ +export interface DriveLogsPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof DriveLogsPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof DriveLogsPage + */ + data: Array; +} + +/** + * Check if a given object implements the DriveLogsPage interface. + */ +export function instanceOfDriveLogsPage(value: object): value is DriveLogsPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function DriveLogsPageFromJSON(json: any): DriveLogsPage { + return DriveLogsPageFromJSONTyped(json, false); +} + +export function DriveLogsPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogsPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(DriveLogFromJSON)), + }; +} + +export function DriveLogsPageToJSON(json: any): DriveLogsPage { + return DriveLogsPageToJSONTyped(json, false); +} + +export function DriveLogsPageToJSONTyped(value?: DriveLogsPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(DriveLogToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/DriveLogsSortColumn.ts b/sdk/typescript-fetch/src/models/DriveLogsSortColumn.ts new file mode 100644 index 0000000..aa7c010 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DriveLogsSortColumn.ts @@ -0,0 +1,53 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Drive Logs. + * @export + */ +export const DriveLogsSortColumn = { + Start: 'start', + LastModified: 'last_modified' +} as const; +export type DriveLogsSortColumn = typeof DriveLogsSortColumn[keyof typeof DriveLogsSortColumn]; + + +export function instanceOfDriveLogsSortColumn(value: any): boolean { + for (const key in DriveLogsSortColumn) { + if (Object.prototype.hasOwnProperty.call(DriveLogsSortColumn, key)) { + if (DriveLogsSortColumn[key as keyof typeof DriveLogsSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function DriveLogsSortColumnFromJSON(json: any): DriveLogsSortColumn { + return DriveLogsSortColumnFromJSONTyped(json, false); +} + +export function DriveLogsSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): DriveLogsSortColumn { + return json as DriveLogsSortColumn; +} + +export function DriveLogsSortColumnToJSON(value?: DriveLogsSortColumn | null): any { + return value as any; +} + +export function DriveLogsSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): DriveLogsSortColumn { + return value as DriveLogsSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/Duration.ts b/sdk/typescript-fetch/src/models/Duration.ts new file mode 100644 index 0000000..9b2a640 --- /dev/null +++ b/sdk/typescript-fetch/src/models/Duration.ts @@ -0,0 +1,96 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DurationType } from './DurationType'; +import { + DurationTypeFromJSON, + DurationTypeFromJSONTyped, + DurationTypeToJSON, + DurationTypeToJSONTyped, +} from './DurationType'; + +/** + * + * @export + * @interface Duration + */ +export interface Duration { + /** + * + * @type {DurationType} + * @memberof Duration + */ + type: DurationType; + /** + * Net minutes of the recording. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + * + * @type {number} + * @memberof Duration + */ + minutes: number; + /** + * Net minutes rounded to the default setting configured. In case of type 'half_day' or 'full_day' these get calculated automatically, based on WorkTimeSchedule configured for User + * + * @type {number} + * @memberof Duration + */ + minutesRounded: number; +} + + + +/** + * Check if a given object implements the Duration interface. + */ +export function instanceOfDuration(value: object): value is Duration { + if (!('type' in value) || value['type'] === undefined) return false; + if (!('minutes' in value) || value['minutes'] === undefined) return false; + if (!('minutesRounded' in value) || value['minutesRounded'] === undefined) return false; + return true; +} + +export function DurationFromJSON(json: any): Duration { + return DurationFromJSONTyped(json, false); +} + +export function DurationFromJSONTyped(json: any, ignoreDiscriminator: boolean): Duration { + if (json == null) { + return json; + } + return { + + 'type': DurationTypeFromJSON(json['type']), + 'minutes': json['minutes'], + 'minutesRounded': json['minutes_rounded'], + }; +} + +export function DurationToJSON(json: any): Duration { + return DurationToJSONTyped(json, false); +} + +export function DurationToJSONTyped(value?: Duration | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'type': DurationTypeToJSON(value['type']), + 'minutes': value['minutes'], + 'minutes_rounded': value['minutesRounded'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/DurationType.ts b/sdk/typescript-fetch/src/models/DurationType.ts new file mode 100644 index 0000000..9719420 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DurationType.ts @@ -0,0 +1,54 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * How the duration of a single recording is expressed. Not to be confused with `DurationUnit`, which states the unit a Working Time Type is recorded in. + * @export + */ +export const DurationType = { + Minutes: 'minutes', + FullDay: 'full_day', + HalfDay: 'half_day' +} as const; +export type DurationType = typeof DurationType[keyof typeof DurationType]; + + +export function instanceOfDurationType(value: any): boolean { + for (const key in DurationType) { + if (Object.prototype.hasOwnProperty.call(DurationType, key)) { + if (DurationType[key as keyof typeof DurationType] === value) { + return true; + } + } + } + return false; +} + +export function DurationTypeFromJSON(json: any): DurationType { + return DurationTypeFromJSONTyped(json, false); +} + +export function DurationTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): DurationType { + return json as DurationType; +} + +export function DurationTypeToJSON(value?: DurationType | null): any { + return value as any; +} + +export function DurationTypeToJSONTyped(value: any, ignoreDiscriminator: boolean): DurationType { + return value as DurationType; +} + diff --git a/sdk/typescript-fetch/src/models/DurationUnit.ts b/sdk/typescript-fetch/src/models/DurationUnit.ts new file mode 100644 index 0000000..9a461c0 --- /dev/null +++ b/sdk/typescript-fetch/src/models/DurationUnit.ts @@ -0,0 +1,54 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Unit a Working Time Type is recorded in. Not to be confused with `DurationType`, which states how an individual recording's duration is expressed. + * @export + */ +export const DurationUnit = { + Minutes: 'minutes', + HalfDays: 'half_days', + Days: 'days' +} as const; +export type DurationUnit = typeof DurationUnit[keyof typeof DurationUnit]; + + +export function instanceOfDurationUnit(value: any): boolean { + for (const key in DurationUnit) { + if (Object.prototype.hasOwnProperty.call(DurationUnit, key)) { + if (DurationUnit[key as keyof typeof DurationUnit] === value) { + return true; + } + } + } + return false; +} + +export function DurationUnitFromJSON(json: any): DurationUnit { + return DurationUnitFromJSONTyped(json, false); +} + +export function DurationUnitFromJSONTyped(json: any, ignoreDiscriminator: boolean): DurationUnit { + return json as DurationUnit; +} + +export function DurationUnitToJSON(value?: DurationUnit | null): any { + return value as any; +} + +export function DurationUnitToJSONTyped(value: any, ignoreDiscriminator: boolean): DurationUnit { + return value as DurationUnit; +} + diff --git a/sdk/typescript-fetch/src/models/ErrorEntry.ts b/sdk/typescript-fetch/src/models/ErrorEntry.ts new file mode 100644 index 0000000..cc38d1d --- /dev/null +++ b/sdk/typescript-fetch/src/models/ErrorEntry.ts @@ -0,0 +1,84 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * Field-level or sub-error entry, shaped like a sub-ProblemDetail. The `type` URI identifies the specific constraint or sub-error category (e.g. `validation/not-null` for a Bean Validation `@NotNull`, `validation/paused-working-time` for a TIMR custom validator code, `validation/type-mismatch` for a value that does not fit its target type, `validation/unknown-property` for a property the resource does not declare, `reference-not-found/user` for a `MappingException`). `field` is the JSONPath of the offending property in the request body, rooted at `$` — array elements included. An error about a query parameter names it plainly instead, without the `$.` prefix. + * + * @export + * @interface ErrorEntry + */ +export interface ErrorEntry { + /** + * + * @type {string} + * @memberof ErrorEntry + */ + type: string; + /** + * + * @type {string} + * @memberof ErrorEntry + */ + field?: string | null; + /** + * + * @type {string} + * @memberof ErrorEntry + */ + detail: string; +} + +/** + * Check if a given object implements the ErrorEntry interface. + */ +export function instanceOfErrorEntry(value: object): value is ErrorEntry { + if (!('type' in value) || value['type'] === undefined) return false; + if (!('detail' in value) || value['detail'] === undefined) return false; + return true; +} + +export function ErrorEntryFromJSON(json: any): ErrorEntry { + return ErrorEntryFromJSONTyped(json, false); +} + +export function ErrorEntryFromJSONTyped(json: any, ignoreDiscriminator: boolean): ErrorEntry { + if (json == null) { + return json; + } + return { + + 'type': json['type'], + 'field': json['field'] == null ? undefined : json['field'], + 'detail': json['detail'], + }; +} + +export function ErrorEntryToJSON(json: any): ErrorEntry { + return ErrorEntryToJSONTyped(json, false); +} + +export function ErrorEntryToJSONTyped(value?: ErrorEntry | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'type': value['type'], + 'field': value['field'], + 'detail': value['detail'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/FlexTimeIndicator.ts b/sdk/typescript-fetch/src/models/FlexTimeIndicator.ts new file mode 100644 index 0000000..51e095a --- /dev/null +++ b/sdk/typescript-fetch/src/models/FlexTimeIndicator.ts @@ -0,0 +1,54 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Traffic-light rating of the flex time balance. The thresholds are an account setting and are not part of this contract. + * @export + */ +export const FlexTimeIndicator = { + Green: 'green', + Yellow: 'yellow', + Red: 'red' +} as const; +export type FlexTimeIndicator = typeof FlexTimeIndicator[keyof typeof FlexTimeIndicator]; + + +export function instanceOfFlexTimeIndicator(value: any): boolean { + for (const key in FlexTimeIndicator) { + if (Object.prototype.hasOwnProperty.call(FlexTimeIndicator, key)) { + if (FlexTimeIndicator[key as keyof typeof FlexTimeIndicator] === value) { + return true; + } + } + } + return false; +} + +export function FlexTimeIndicatorFromJSON(json: any): FlexTimeIndicator { + return FlexTimeIndicatorFromJSONTyped(json, false); +} + +export function FlexTimeIndicatorFromJSONTyped(json: any, ignoreDiscriminator: boolean): FlexTimeIndicator { + return json as FlexTimeIndicator; +} + +export function FlexTimeIndicatorToJSON(value?: FlexTimeIndicator | null): any { + return value as any; +} + +export function FlexTimeIndicatorToJSONTyped(value: any, ignoreDiscriminator: boolean): FlexTimeIndicator { + return value as FlexTimeIndicator; +} + diff --git a/sdk/typescript-fetch/src/models/Holiday.ts b/sdk/typescript-fetch/src/models/Holiday.ts new file mode 100644 index 0000000..0583b94 --- /dev/null +++ b/sdk/typescript-fetch/src/models/Holiday.ts @@ -0,0 +1,84 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface Holiday + */ +export interface Holiday { + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof Holiday + */ + date: Date; + /** + * + * @type {string} + * @memberof Holiday + */ + description: string; + /** + * + * @type {boolean} + * @memberof Holiday + */ + halfDay: boolean; +} + +/** + * Check if a given object implements the Holiday interface. + */ +export function instanceOfHoliday(value: object): value is Holiday { + if (!('date' in value) || value['date'] === undefined) return false; + if (!('description' in value) || value['description'] === undefined) return false; + if (!('halfDay' in value) || value['halfDay'] === undefined) return false; + return true; +} + +export function HolidayFromJSON(json: any): Holiday { + return HolidayFromJSONTyped(json, false); +} + +export function HolidayFromJSONTyped(json: any, ignoreDiscriminator: boolean): Holiday { + if (json == null) { + return json; + } + return { + + 'date': (new Date(json['date'])), + 'description': json['description'], + 'halfDay': json['half_day'], + }; +} + +export function HolidayToJSON(json: any): Holiday { + return HolidayToJSONTyped(json, false); +} + +export function HolidayToJSONTyped(value?: Holiday | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'date': value['date'].toISOString().substring(0,10), + 'description': value['description'], + 'half_day': value['halfDay'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/HolidayCalendarPartial.ts b/sdk/typescript-fetch/src/models/HolidayCalendarPartial.ts new file mode 100644 index 0000000..d48009a --- /dev/null +++ b/sdk/typescript-fetch/src/models/HolidayCalendarPartial.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * A holiday calendar. Its holidays are either generated automatically or maintained manually. + * + * @export + * @interface HolidayCalendarPartial + */ +export interface HolidayCalendarPartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof HolidayCalendarPartial + */ + id: string; + /** + * + * @type {string} + * @memberof HolidayCalendarPartial + */ + description: string; +} + +/** + * Check if a given object implements the HolidayCalendarPartial interface. + */ +export function instanceOfHolidayCalendarPartial(value: object): value is HolidayCalendarPartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('description' in value) || value['description'] === undefined) return false; + return true; +} + +export function HolidayCalendarPartialFromJSON(json: any): HolidayCalendarPartial { + return HolidayCalendarPartialFromJSONTyped(json, false); +} + +export function HolidayCalendarPartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): HolidayCalendarPartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'description': json['description'], + }; +} + +export function HolidayCalendarPartialToJSON(json: any): HolidayCalendarPartial { + return HolidayCalendarPartialToJSONTyped(json, false); +} + +export function HolidayCalendarPartialToJSONTyped(value?: HolidayCalendarPartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'description': value['description'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/HolidayCalendarsPage.ts b/sdk/typescript-fetch/src/models/HolidayCalendarsPage.ts new file mode 100644 index 0000000..299c058 --- /dev/null +++ b/sdk/typescript-fetch/src/models/HolidayCalendarsPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { HolidayCalendarPartial } from './HolidayCalendarPartial'; +import { + HolidayCalendarPartialFromJSON, + HolidayCalendarPartialFromJSONTyped, + HolidayCalendarPartialToJSON, + HolidayCalendarPartialToJSONTyped, +} from './HolidayCalendarPartial'; + +/** + * + * @export + * @interface HolidayCalendarsPage + */ +export interface HolidayCalendarsPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof HolidayCalendarsPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof HolidayCalendarsPage + */ + data: Array; +} + +/** + * Check if a given object implements the HolidayCalendarsPage interface. + */ +export function instanceOfHolidayCalendarsPage(value: object): value is HolidayCalendarsPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function HolidayCalendarsPageFromJSON(json: any): HolidayCalendarsPage { + return HolidayCalendarsPageFromJSONTyped(json, false); +} + +export function HolidayCalendarsPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): HolidayCalendarsPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(HolidayCalendarPartialFromJSON)), + }; +} + +export function HolidayCalendarsPageToJSON(json: any): HolidayCalendarsPage { + return HolidayCalendarsPageToJSONTyped(json, false); +} + +export function HolidayCalendarsPageToJSONTyped(value?: HolidayCalendarsPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(HolidayCalendarPartialToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/HolidayCalendarsSortColumn.ts b/sdk/typescript-fetch/src/models/HolidayCalendarsSortColumn.ts new file mode 100644 index 0000000..8d49f19 --- /dev/null +++ b/sdk/typescript-fetch/src/models/HolidayCalendarsSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Holiday Calendars. + * @export + */ +export const HolidayCalendarsSortColumn = { + Description: 'description' +} as const; +export type HolidayCalendarsSortColumn = typeof HolidayCalendarsSortColumn[keyof typeof HolidayCalendarsSortColumn]; + + +export function instanceOfHolidayCalendarsSortColumn(value: any): boolean { + for (const key in HolidayCalendarsSortColumn) { + if (Object.prototype.hasOwnProperty.call(HolidayCalendarsSortColumn, key)) { + if (HolidayCalendarsSortColumn[key as keyof typeof HolidayCalendarsSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function HolidayCalendarsSortColumnFromJSON(json: any): HolidayCalendarsSortColumn { + return HolidayCalendarsSortColumnFromJSONTyped(json, false); +} + +export function HolidayCalendarsSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): HolidayCalendarsSortColumn { + return json as HolidayCalendarsSortColumn; +} + +export function HolidayCalendarsSortColumnToJSON(value?: HolidayCalendarsSortColumn | null): any { + return value as any; +} + +export function HolidayCalendarsSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): HolidayCalendarsSortColumn { + return value as HolidayCalendarsSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/HolidaysPage.ts b/sdk/typescript-fetch/src/models/HolidaysPage.ts new file mode 100644 index 0000000..52f99f8 --- /dev/null +++ b/sdk/typescript-fetch/src/models/HolidaysPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { Holiday } from './Holiday'; +import { + HolidayFromJSON, + HolidayFromJSONTyped, + HolidayToJSON, + HolidayToJSONTyped, +} from './Holiday'; + +/** + * + * @export + * @interface HolidaysPage + */ +export interface HolidaysPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof HolidaysPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof HolidaysPage + */ + data: Array; +} + +/** + * Check if a given object implements the HolidaysPage interface. + */ +export function instanceOfHolidaysPage(value: object): value is HolidaysPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function HolidaysPageFromJSON(json: any): HolidaysPage { + return HolidaysPageFromJSONTyped(json, false); +} + +export function HolidaysPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): HolidaysPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(HolidayFromJSON)), + }; +} + +export function HolidaysPageToJSON(json: any): HolidaysPage { + return HolidaysPageToJSONTyped(json, false); +} + +export function HolidaysPageToJSONTyped(value?: HolidaysPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(HolidayToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/HolidaysSortColumn.ts b/sdk/typescript-fetch/src/models/HolidaysSortColumn.ts new file mode 100644 index 0000000..ebfa68f --- /dev/null +++ b/sdk/typescript-fetch/src/models/HolidaysSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Holidays. + * @export + */ +export const HolidaysSortColumn = { + Date: 'date' +} as const; +export type HolidaysSortColumn = typeof HolidaysSortColumn[keyof typeof HolidaysSortColumn]; + + +export function instanceOfHolidaysSortColumn(value: any): boolean { + for (const key in HolidaysSortColumn) { + if (Object.prototype.hasOwnProperty.call(HolidaysSortColumn, key)) { + if (HolidaysSortColumn[key as keyof typeof HolidaysSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function HolidaysSortColumnFromJSON(json: any): HolidaysSortColumn { + return HolidaysSortColumnFromJSONTyped(json, false); +} + +export function HolidaysSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): HolidaysSortColumn { + return json as HolidaysSortColumn; +} + +export function HolidaysSortColumnToJSON(value?: HolidaysSortColumn | null): any { + return value as any; +} + +export function HolidaysSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): HolidaysSortColumn { + return value as HolidaysSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/Location.ts b/sdk/typescript-fetch/src/models/Location.ts new file mode 100644 index 0000000..aee0cad --- /dev/null +++ b/sdk/typescript-fetch/src/models/Location.ts @@ -0,0 +1,100 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface Location + */ +export interface Location { + /** + * Latitude in decimal degrees. + * @type {number} + * @memberof Location + */ + lat: number | null; + /** + * Longitude in decimal degrees. + * @type {number} + * @memberof Location + */ + lon: number | null; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof Location + */ + timestamp?: Date | null; + /** + * + * @type {string} + * @memberof Location + */ + formattedAddress?: string | null; + /** + * Horizontal GPS accuracy in meters. + * @type {number} + * @memberof Location + */ + accuracy: number | null; +} + +/** + * Check if a given object implements the Location interface. + */ +export function instanceOfLocation(value: object): value is Location { + if (!('lat' in value) || value['lat'] === undefined) return false; + if (!('lon' in value) || value['lon'] === undefined) return false; + if (!('accuracy' in value) || value['accuracy'] === undefined) return false; + return true; +} + +export function LocationFromJSON(json: any): Location { + return LocationFromJSONTyped(json, false); +} + +export function LocationFromJSONTyped(json: any, ignoreDiscriminator: boolean): Location { + if (json == null) { + return json; + } + return { + + 'lat': json['lat'], + 'lon': json['lon'], + 'timestamp': json['timestamp'] == null ? undefined : (new Date(json['timestamp'])), + 'formattedAddress': json['formatted_address'] == null ? undefined : json['formatted_address'], + 'accuracy': json['accuracy'], + }; +} + +export function LocationToJSON(json: any): Location { + return LocationToJSONTyped(json, false); +} + +export function LocationToJSONTyped(value?: Location | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'lat': value['lat'], + 'lon': value['lon'], + 'timestamp': value['timestamp'] == null ? value['timestamp'] : value['timestamp'].toISOString(), + 'formatted_address': value['formattedAddress'], + 'accuracy': value['accuracy'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/LocationCreate.ts b/sdk/typescript-fetch/src/models/LocationCreate.ts new file mode 100644 index 0000000..e710d68 --- /dev/null +++ b/sdk/typescript-fetch/src/models/LocationCreate.ts @@ -0,0 +1,99 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface LocationCreate + */ +export interface LocationCreate { + /** + * Latitude in decimal degrees. + * @type {number} + * @memberof LocationCreate + */ + lat: number; + /** + * Longitude in decimal degrees. + * @type {number} + * @memberof LocationCreate + */ + lon: number; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof LocationCreate + */ + timestamp?: Date | null; + /** + * + * @type {string} + * @memberof LocationCreate + */ + formattedAddress?: string | null; + /** + * Horizontal GPS accuracy in meters. + * @type {number} + * @memberof LocationCreate + */ + accuracy?: number | null; +} + +/** + * Check if a given object implements the LocationCreate interface. + */ +export function instanceOfLocationCreate(value: object): value is LocationCreate { + if (!('lat' in value) || value['lat'] === undefined) return false; + if (!('lon' in value) || value['lon'] === undefined) return false; + return true; +} + +export function LocationCreateFromJSON(json: any): LocationCreate { + return LocationCreateFromJSONTyped(json, false); +} + +export function LocationCreateFromJSONTyped(json: any, ignoreDiscriminator: boolean): LocationCreate { + if (json == null) { + return json; + } + return { + + 'lat': json['lat'], + 'lon': json['lon'], + 'timestamp': json['timestamp'] == null ? undefined : (new Date(json['timestamp'])), + 'formattedAddress': json['formatted_address'] == null ? undefined : json['formatted_address'], + 'accuracy': json['accuracy'] == null ? undefined : json['accuracy'], + }; +} + +export function LocationCreateToJSON(json: any): LocationCreate { + return LocationCreateToJSONTyped(json, false); +} + +export function LocationCreateToJSONTyped(value?: LocationCreate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'lat': value['lat'], + 'lon': value['lon'], + 'timestamp': value['timestamp'] == null ? value['timestamp'] : value['timestamp'].toISOString(), + 'formatted_address': value['formattedAddress'], + 'accuracy': value['accuracy'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/LocationUpdate.ts b/sdk/typescript-fetch/src/models/LocationUpdate.ts new file mode 100644 index 0000000..a9b0f5f --- /dev/null +++ b/sdk/typescript-fetch/src/models/LocationUpdate.ts @@ -0,0 +1,97 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface LocationUpdate + */ +export interface LocationUpdate { + /** + * Latitude in decimal degrees. + * @type {number} + * @memberof LocationUpdate + */ + lat?: number; + /** + * Longitude in decimal degrees. + * @type {number} + * @memberof LocationUpdate + */ + lon?: number; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof LocationUpdate + */ + timestamp?: Date | null; + /** + * + * @type {string} + * @memberof LocationUpdate + */ + formattedAddress?: string | null; + /** + * Horizontal GPS accuracy in meters. + * @type {number} + * @memberof LocationUpdate + */ + accuracy?: number | null; +} + +/** + * Check if a given object implements the LocationUpdate interface. + */ +export function instanceOfLocationUpdate(value: object): value is LocationUpdate { + return true; +} + +export function LocationUpdateFromJSON(json: any): LocationUpdate { + return LocationUpdateFromJSONTyped(json, false); +} + +export function LocationUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): LocationUpdate { + if (json == null) { + return json; + } + return { + + 'lat': json['lat'] == null ? undefined : json['lat'], + 'lon': json['lon'] == null ? undefined : json['lon'], + 'timestamp': json['timestamp'] == null ? undefined : (new Date(json['timestamp'])), + 'formattedAddress': json['formatted_address'] == null ? undefined : json['formatted_address'], + 'accuracy': json['accuracy'] == null ? undefined : json['accuracy'], + }; +} + +export function LocationUpdateToJSON(json: any): LocationUpdate { + return LocationUpdateToJSONTyped(json, false); +} + +export function LocationUpdateToJSONTyped(value?: LocationUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'lat': value['lat'], + 'lon': value['lon'], + 'timestamp': value['timestamp'] == null ? value['timestamp'] : value['timestamp'].toISOString(), + 'formatted_address': value['formattedAddress'], + 'accuracy': value['accuracy'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/ModelError.ts b/sdk/typescript-fetch/src/models/ModelError.ts new file mode 100644 index 0000000..3b0af77 --- /dev/null +++ b/sdk/typescript-fetch/src/models/ModelError.ts @@ -0,0 +1,136 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { ErrorEntry } from './ErrorEntry'; +import { + ErrorEntryFromJSON, + ErrorEntryFromJSONTyped, + ErrorEntryToJSON, + ErrorEntryToJSONTyped, +} from './ErrorEntry'; + +/** + * TIMR error response body, extending the Problem Details base with `timestamp`, `trace_id` and per-field `errors[]` for validation, binding, constraint, request-body deserialization, and reference-not-found errors. The semantic identifier is encoded in the `type` URI (e.g. `https://errors.timr.com/conflict/resource-outdated`). + * + * Slugs in the `type` URI are lowercase kebab-case: a top-level category (`validation`, `reference-not-found`, `conflict`, `forbidden`, `internal`) optionally followed by a specific sub-slug (`conflict/resource-outdated`, `validation/end-time-required`, `reference-not-found/user`). + * + * @export + * @interface ModelError + */ +export interface ModelError { + /** + * + * @type {string} + * @memberof ModelError + */ + type: string; + /** + * + * @type {string} + * @memberof ModelError + */ + title: string; + /** + * + * @type {number} + * @memberof ModelError + */ + status: number; + /** + * + * @type {string} + * @memberof ModelError + */ + detail?: string; + /** + * + * @type {string} + * @memberof ModelError + */ + instance?: string; + /** + * + * @type {Date} + * @memberof ModelError + */ + timestamp: Date; + /** + * + * @type {string} + * @memberof ModelError + */ + traceId?: string | null; + /** + * + * @type {Array} + * @memberof ModelError + */ + errors?: Array | null; +} + +/** + * Check if a given object implements the ModelError interface. + */ +export function instanceOfModelError(value: object): value is ModelError { + if (!('type' in value) || value['type'] === undefined) return false; + if (!('title' in value) || value['title'] === undefined) return false; + if (!('status' in value) || value['status'] === undefined) return false; + if (!('timestamp' in value) || value['timestamp'] === undefined) return false; + return true; +} + +export function ModelErrorFromJSON(json: any): ModelError { + return ModelErrorFromJSONTyped(json, false); +} + +export function ModelErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelError { + if (json == null) { + return json; + } + return { + + 'type': json['type'], + 'title': json['title'], + 'status': json['status'], + 'detail': json['detail'] == null ? undefined : json['detail'], + 'instance': json['instance'] == null ? undefined : json['instance'], + 'timestamp': (new Date(json['timestamp'])), + 'traceId': json['trace_id'] == null ? undefined : json['trace_id'], + 'errors': json['errors'] == null ? undefined : ((json['errors'] as Array).map(ErrorEntryFromJSON)), + }; +} + +export function ModelErrorToJSON(json: any): ModelError { + return ModelErrorToJSONTyped(json, false); +} + +export function ModelErrorToJSONTyped(value?: ModelError | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'type': value['type'], + 'title': value['title'], + 'status': value['status'], + 'detail': value['detail'], + 'instance': value['instance'], + 'timestamp': value['timestamp'].toISOString(), + 'trace_id': value['traceId'], + 'errors': value['errors'] == null ? undefined : ((value['errors'] as Array).map(ErrorEntryToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/NormalWorkingTimes.ts b/sdk/typescript-fetch/src/models/NormalWorkingTimes.ts new file mode 100644 index 0000000..ceaab30 --- /dev/null +++ b/sdk/typescript-fetch/src/models/NormalWorkingTimes.ts @@ -0,0 +1,73 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface NormalWorkingTimes + */ +export interface NormalWorkingTimes { + /** + * + * @type {string} + * @memberof NormalWorkingTimes + */ + start?: string | null; + /** + * + * @type {string} + * @memberof NormalWorkingTimes + */ + end?: string | null; +} + +/** + * Check if a given object implements the NormalWorkingTimes interface. + */ +export function instanceOfNormalWorkingTimes(value: object): value is NormalWorkingTimes { + return true; +} + +export function NormalWorkingTimesFromJSON(json: any): NormalWorkingTimes { + return NormalWorkingTimesFromJSONTyped(json, false); +} + +export function NormalWorkingTimesFromJSONTyped(json: any, ignoreDiscriminator: boolean): NormalWorkingTimes { + if (json == null) { + return json; + } + return { + + 'start': json['start'] == null ? undefined : json['start'], + 'end': json['end'] == null ? undefined : json['end'], + }; +} + +export function NormalWorkingTimesToJSON(json: any): NormalWorkingTimes { + return NormalWorkingTimesToJSONTyped(json, false); +} + +export function NormalWorkingTimesToJSONTyped(value?: NormalWorkingTimes | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'], + 'end': value['end'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/OvertimeSurchargeAccount.ts b/sdk/typescript-fetch/src/models/OvertimeSurchargeAccount.ts new file mode 100644 index 0000000..f69b71f --- /dev/null +++ b/sdk/typescript-fetch/src/models/OvertimeSurchargeAccount.ts @@ -0,0 +1,84 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface OvertimeSurchargeAccount + */ +export interface OvertimeSurchargeAccount { + /** + * + * @type {number} + * @memberof OvertimeSurchargeAccount + */ + balanceLastPeriodMinutes: number | null; + /** + * + * @type {number} + * @memberof OvertimeSurchargeAccount + */ + newMinutes: number | null; + /** + * + * @type {number} + * @memberof OvertimeSurchargeAccount + */ + balanceTotalMinutes: number | null; +} + +/** + * Check if a given object implements the OvertimeSurchargeAccount interface. + */ +export function instanceOfOvertimeSurchargeAccount(value: object): value is OvertimeSurchargeAccount { + if (!('balanceLastPeriodMinutes' in value) || value['balanceLastPeriodMinutes'] === undefined) return false; + if (!('newMinutes' in value) || value['newMinutes'] === undefined) return false; + if (!('balanceTotalMinutes' in value) || value['balanceTotalMinutes'] === undefined) return false; + return true; +} + +export function OvertimeSurchargeAccountFromJSON(json: any): OvertimeSurchargeAccount { + return OvertimeSurchargeAccountFromJSONTyped(json, false); +} + +export function OvertimeSurchargeAccountFromJSONTyped(json: any, ignoreDiscriminator: boolean): OvertimeSurchargeAccount { + if (json == null) { + return json; + } + return { + + 'balanceLastPeriodMinutes': json['balance_last_period_minutes'], + 'newMinutes': json['new_minutes'], + 'balanceTotalMinutes': json['balance_total_minutes'], + }; +} + +export function OvertimeSurchargeAccountToJSON(json: any): OvertimeSurchargeAccount { + return OvertimeSurchargeAccountToJSONTyped(json, false); +} + +export function OvertimeSurchargeAccountToJSONTyped(value?: OvertimeSurchargeAccount | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'balance_last_period_minutes': value['balanceLastPeriodMinutes'], + 'new_minutes': value['newMinutes'], + 'balance_total_minutes': value['balanceTotalMinutes'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/OvertimeSurchargeAccounts.ts b/sdk/typescript-fetch/src/models/OvertimeSurchargeAccounts.ts new file mode 100644 index 0000000..8612c6d --- /dev/null +++ b/sdk/typescript-fetch/src/models/OvertimeSurchargeAccounts.ts @@ -0,0 +1,108 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { OvertimeSurchargeRule } from './OvertimeSurchargeRule'; +import { + OvertimeSurchargeRuleFromJSON, + OvertimeSurchargeRuleFromJSONTyped, + OvertimeSurchargeRuleToJSON, + OvertimeSurchargeRuleToJSONTyped, +} from './OvertimeSurchargeRule'; +import type { OvertimeSurchargeAccount } from './OvertimeSurchargeAccount'; +import { + OvertimeSurchargeAccountFromJSON, + OvertimeSurchargeAccountFromJSONTyped, + OvertimeSurchargeAccountToJSON, + OvertimeSurchargeAccountToJSONTyped, +} from './OvertimeSurchargeAccount'; + +/** + * + * @export + * @interface OvertimeSurchargeAccounts + */ +export interface OvertimeSurchargeAccounts { + /** + * + * @type {OvertimeSurchargeRule} + * @memberof OvertimeSurchargeAccounts + */ + rule: OvertimeSurchargeRule; + /** + * + * @type {number} + * @memberof OvertimeSurchargeAccounts + */ + percentage: number | null; + /** + * + * @type {OvertimeSurchargeAccount} + * @memberof OvertimeSurchargeAccounts + */ + overtime: OvertimeSurchargeAccount; + /** + * + * @type {OvertimeSurchargeAccount} + * @memberof OvertimeSurchargeAccounts + */ + surcharge: OvertimeSurchargeAccount; +} + +/** + * Check if a given object implements the OvertimeSurchargeAccounts interface. + */ +export function instanceOfOvertimeSurchargeAccounts(value: object): value is OvertimeSurchargeAccounts { + if (!('rule' in value) || value['rule'] === undefined) return false; + if (!('percentage' in value) || value['percentage'] === undefined) return false; + if (!('overtime' in value) || value['overtime'] === undefined) return false; + if (!('surcharge' in value) || value['surcharge'] === undefined) return false; + return true; +} + +export function OvertimeSurchargeAccountsFromJSON(json: any): OvertimeSurchargeAccounts { + return OvertimeSurchargeAccountsFromJSONTyped(json, false); +} + +export function OvertimeSurchargeAccountsFromJSONTyped(json: any, ignoreDiscriminator: boolean): OvertimeSurchargeAccounts { + if (json == null) { + return json; + } + return { + + 'rule': OvertimeSurchargeRuleFromJSON(json['rule']), + 'percentage': json['percentage'], + 'overtime': OvertimeSurchargeAccountFromJSON(json['overtime']), + 'surcharge': OvertimeSurchargeAccountFromJSON(json['surcharge']), + }; +} + +export function OvertimeSurchargeAccountsToJSON(json: any): OvertimeSurchargeAccounts { + return OvertimeSurchargeAccountsToJSONTyped(json, false); +} + +export function OvertimeSurchargeAccountsToJSONTyped(value?: OvertimeSurchargeAccounts | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'rule': OvertimeSurchargeRuleToJSON(value['rule']), + 'percentage': value['percentage'], + 'overtime': OvertimeSurchargeAccountToJSON(value['overtime']), + 'surcharge': OvertimeSurchargeAccountToJSON(value['surcharge']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/OvertimeSurchargeRule.ts b/sdk/typescript-fetch/src/models/OvertimeSurchargeRule.ts new file mode 100644 index 0000000..fae307e --- /dev/null +++ b/sdk/typescript-fetch/src/models/OvertimeSurchargeRule.ts @@ -0,0 +1,84 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface OvertimeSurchargeRule + */ +export interface OvertimeSurchargeRule { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof OvertimeSurchargeRule + */ + id: string; + /** + * + * @type {string} + * @memberof OvertimeSurchargeRule + */ + name: string; + /** + * + * @type {string} + * @memberof OvertimeSurchargeRule + */ + shortName: string; +} + +/** + * Check if a given object implements the OvertimeSurchargeRule interface. + */ +export function instanceOfOvertimeSurchargeRule(value: object): value is OvertimeSurchargeRule { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('shortName' in value) || value['shortName'] === undefined) return false; + return true; +} + +export function OvertimeSurchargeRuleFromJSON(json: any): OvertimeSurchargeRule { + return OvertimeSurchargeRuleFromJSONTyped(json, false); +} + +export function OvertimeSurchargeRuleFromJSONTyped(json: any, ignoreDiscriminator: boolean): OvertimeSurchargeRule { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'shortName': json['short_name'], + }; +} + +export function OvertimeSurchargeRuleToJSON(json: any): OvertimeSurchargeRule { + return OvertimeSurchargeRuleToJSONTyped(json, false); +} + +export function OvertimeSurchargeRuleToJSONTyped(value?: OvertimeSurchargeRule | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'short_name': value['shortName'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/PagingInformation.ts b/sdk/typescript-fetch/src/models/PagingInformation.ts new file mode 100644 index 0000000..43ea9b4 --- /dev/null +++ b/sdk/typescript-fetch/src/models/PagingInformation.ts @@ -0,0 +1,66 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface PagingInformation + */ +export interface PagingInformation { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof PagingInformation + */ + nextPageToken: string | null; +} + +/** + * Check if a given object implements the PagingInformation interface. + */ +export function instanceOfPagingInformation(value: object): value is PagingInformation { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + return true; +} + +export function PagingInformationFromJSON(json: any): PagingInformation { + return PagingInformationFromJSONTyped(json, false); +} + +export function PagingInformationFromJSONTyped(json: any, ignoreDiscriminator: boolean): PagingInformation { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + }; +} + +export function PagingInformationToJSON(json: any): PagingInformation { + return PagingInformationToJSONTyped(json, false); +} + +export function PagingInformationToJSONTyped(value?: PagingInformation | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/Platform.ts b/sdk/typescript-fetch/src/models/Platform.ts new file mode 100644 index 0000000..28869b1 --- /dev/null +++ b/sdk/typescript-fetch/src/models/Platform.ts @@ -0,0 +1,57 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Platform the entry was recorded on. + * @export + */ +export const Platform = { + TimrWeb: 'timr_web', + TimrMobile: 'timr_mobile', + TourMobile: 'tour_mobile', + TimrTerminal: 'timr_terminal', + SyncApi: 'sync_api', + TimrApi: 'timr_api' +} as const; +export type Platform = typeof Platform[keyof typeof Platform]; + + +export function instanceOfPlatform(value: any): boolean { + for (const key in Platform) { + if (Object.prototype.hasOwnProperty.call(Platform, key)) { + if (Platform[key as keyof typeof Platform] === value) { + return true; + } + } + } + return false; +} + +export function PlatformFromJSON(json: any): Platform { + return PlatformFromJSONTyped(json, false); +} + +export function PlatformFromJSONTyped(json: any, ignoreDiscriminator: boolean): Platform { + return json as Platform; +} + +export function PlatformToJSON(value?: Platform | null): any { + return value as any; +} + +export function PlatformToJSONTyped(value: any, ignoreDiscriminator: boolean): Platform { + return value as Platform; +} + diff --git a/sdk/typescript-fetch/src/models/ProblemDetail.ts b/sdk/typescript-fetch/src/models/ProblemDetail.ts new file mode 100644 index 0000000..4c035ea --- /dev/null +++ b/sdk/typescript-fetch/src/models/ProblemDetail.ts @@ -0,0 +1,101 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * RFC 9457 Problem Details base members (`type`, `title`, `status`, `detail`, `instance`) — the common shape of all error response bodies. + * + * @export + * @interface ProblemDetail + */ +export interface ProblemDetail { + /** + * + * @type {string} + * @memberof ProblemDetail + */ + type: string; + /** + * + * @type {string} + * @memberof ProblemDetail + */ + title: string; + /** + * + * @type {number} + * @memberof ProblemDetail + */ + status: number; + /** + * + * @type {string} + * @memberof ProblemDetail + */ + detail?: string; + /** + * + * @type {string} + * @memberof ProblemDetail + */ + instance?: string; +} + +/** + * Check if a given object implements the ProblemDetail interface. + */ +export function instanceOfProblemDetail(value: object): value is ProblemDetail { + if (!('type' in value) || value['type'] === undefined) return false; + if (!('title' in value) || value['title'] === undefined) return false; + if (!('status' in value) || value['status'] === undefined) return false; + return true; +} + +export function ProblemDetailFromJSON(json: any): ProblemDetail { + return ProblemDetailFromJSONTyped(json, false); +} + +export function ProblemDetailFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProblemDetail { + if (json == null) { + return json; + } + return { + + 'type': json['type'], + 'title': json['title'], + 'status': json['status'], + 'detail': json['detail'] == null ? undefined : json['detail'], + 'instance': json['instance'] == null ? undefined : json['instance'], + }; +} + +export function ProblemDetailToJSON(json: any): ProblemDetail { + return ProblemDetailToJSONTyped(json, false); +} + +export function ProblemDetailToJSONTyped(value?: ProblemDetail | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'type': value['type'], + 'title': value['title'], + 'status': value['status'], + 'detail': value['detail'], + 'instance': value['instance'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/ProjectTime.ts b/sdk/typescript-fetch/src/models/ProjectTime.ts new file mode 100644 index 0000000..31d2722 --- /dev/null +++ b/sdk/typescript-fetch/src/models/ProjectTime.ts @@ -0,0 +1,282 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { ProjectTimeStatus } from './ProjectTimeStatus'; +import { + ProjectTimeStatusFromJSON, + ProjectTimeStatusFromJSONTyped, + ProjectTimeStatusToJSON, + ProjectTimeStatusToJSONTyped, +} from './ProjectTimeStatus'; +import type { TaskPartial } from './TaskPartial'; +import { + TaskPartialFromJSON, + TaskPartialFromJSONTyped, + TaskPartialToJSON, + TaskPartialToJSONTyped, +} from './TaskPartial'; +import type { Platform } from './Platform'; +import { + PlatformFromJSON, + PlatformFromJSONTyped, + PlatformToJSON, + PlatformToJSONTyped, +} from './Platform'; +import type { Duration } from './Duration'; +import { + DurationFromJSON, + DurationFromJSONTyped, + DurationToJSON, + DurationToJSONTyped, +} from './Duration'; +import type { BreakTime } from './BreakTime'; +import { + BreakTimeFromJSON, + BreakTimeFromJSONTyped, + BreakTimeToJSON, + BreakTimeToJSONTyped, +} from './BreakTime'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; +import type { Location } from './Location'; +import { + LocationFromJSON, + LocationFromJSONTyped, + LocationToJSON, + LocationToJSONTyped, +} from './Location'; + +/** + * One booking on a `task`, from `start` to `end`, optionally `billable`, with `break_times`, notes and locations. + * + * @export + * @interface ProjectTime + */ +export interface ProjectTime { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof ProjectTime + */ + id: string; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof ProjectTime + */ + start: Date; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof ProjectTime + */ + end: Date | null; + /** + * Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + * @type {number} + * @memberof ProjectTime + */ + breakTimeTotalMinutes: number; + /** + * + * @type {Array} + * @memberof ProjectTime + */ + breakTimes: Array; + /** + * + * @type {Duration} + * @memberof ProjectTime + */ + duration: Duration | null; + /** + * + * @type {boolean} + * @memberof ProjectTime + */ + changed: boolean; + /** + * + * @type {string} + * @memberof ProjectTime + */ + notes: string | null; + /** + * + * @type {UserPartial} + * @memberof ProjectTime + */ + user: UserPartial; + /** + * + * @type {TaskPartial} + * @memberof ProjectTime + */ + task: TaskPartial; + /** + * + * @type {boolean} + * @memberof ProjectTime + */ + billable: boolean; + /** + * + * @type {Location} + * @memberof ProjectTime + */ + startLocation: Location | null; + /** + * + * @type {Location} + * @memberof ProjectTime + */ + endLocation: Location | null; + /** + * + * @type {Platform} + * @memberof ProjectTime + */ + startPlatform: Platform | null; + /** + * + * @type {Platform} + * @memberof ProjectTime + */ + endPlatform: Platform | null; + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof ProjectTime + */ + lastModified: Date; + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * + * @type {UserPartial} + * @memberof ProjectTime + */ + lastModifiedBy: UserPartial | null; + /** + * + * @type {ProjectTimeStatus} + * @memberof ProjectTime + */ + status: ProjectTimeStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof ProjectTime + */ + metadata?: { [key: string]: any; } | null; +} + + + +/** + * Check if a given object implements the ProjectTime interface. + */ +export function instanceOfProjectTime(value: object): value is ProjectTime { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('start' in value) || value['start'] === undefined) return false; + if (!('end' in value) || value['end'] === undefined) return false; + if (!('breakTimeTotalMinutes' in value) || value['breakTimeTotalMinutes'] === undefined) return false; + if (!('breakTimes' in value) || value['breakTimes'] === undefined) return false; + if (!('duration' in value) || value['duration'] === undefined) return false; + if (!('changed' in value) || value['changed'] === undefined) return false; + if (!('notes' in value) || value['notes'] === undefined) return false; + if (!('user' in value) || value['user'] === undefined) return false; + if (!('task' in value) || value['task'] === undefined) return false; + if (!('billable' in value) || value['billable'] === undefined) return false; + if (!('startLocation' in value) || value['startLocation'] === undefined) return false; + if (!('endLocation' in value) || value['endLocation'] === undefined) return false; + if (!('startPlatform' in value) || value['startPlatform'] === undefined) return false; + if (!('endPlatform' in value) || value['endPlatform'] === undefined) return false; + if (!('lastModified' in value) || value['lastModified'] === undefined) return false; + if (!('lastModifiedBy' in value) || value['lastModifiedBy'] === undefined) return false; + if (!('status' in value) || value['status'] === undefined) return false; + return true; +} + +export function ProjectTimeFromJSON(json: any): ProjectTime { + return ProjectTimeFromJSONTyped(json, false); +} + +export function ProjectTimeFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProjectTime { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'start': (new Date(json['start'])), + 'end': (json['end'] == null ? null : new Date(json['end'])), + 'breakTimeTotalMinutes': json['break_time_total_minutes'], + 'breakTimes': ((json['break_times'] as Array).map(BreakTimeFromJSON)), + 'duration': DurationFromJSON(json['duration']), + 'changed': json['changed'], + 'notes': json['notes'], + 'user': UserPartialFromJSON(json['user']), + 'task': TaskPartialFromJSON(json['task']), + 'billable': json['billable'], + 'startLocation': LocationFromJSON(json['start_location']), + 'endLocation': LocationFromJSON(json['end_location']), + 'startPlatform': PlatformFromJSON(json['start_platform']), + 'endPlatform': PlatformFromJSON(json['end_platform']), + 'lastModified': (new Date(json['last_modified'])), + 'lastModifiedBy': UserPartialFromJSON(json['last_modified_by']), + 'status': ProjectTimeStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function ProjectTimeToJSON(json: any): ProjectTime { + return ProjectTimeToJSONTyped(json, false); +} + +export function ProjectTimeToJSONTyped(value?: ProjectTime | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'start': value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'break_time_total_minutes': value['breakTimeTotalMinutes'], + 'break_times': ((value['breakTimes'] as Array).map(BreakTimeToJSON)), + 'duration': DurationToJSON(value['duration']), + 'changed': value['changed'], + 'notes': value['notes'], + 'user': UserPartialToJSON(value['user']), + 'task': TaskPartialToJSON(value['task']), + 'billable': value['billable'], + 'start_location': LocationToJSON(value['startLocation']), + 'end_location': LocationToJSON(value['endLocation']), + 'start_platform': PlatformToJSON(value['startPlatform']), + 'end_platform': PlatformToJSON(value['endPlatform']), + 'last_modified': value['lastModified'].toISOString(), + 'last_modified_by': UserPartialToJSON(value['lastModifiedBy']), + 'status': ProjectTimeStatusToJSON(value['status']), + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/ProjectTimeCreate.ts b/sdk/typescript-fetch/src/models/ProjectTimeCreate.ts new file mode 100644 index 0000000..4637b6a --- /dev/null +++ b/sdk/typescript-fetch/src/models/ProjectTimeCreate.ts @@ -0,0 +1,182 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { ProjectTimeStatus } from './ProjectTimeStatus'; +import { + ProjectTimeStatusFromJSON, + ProjectTimeStatusFromJSONTyped, + ProjectTimeStatusToJSON, + ProjectTimeStatusToJSONTyped, +} from './ProjectTimeStatus'; +import type { LocationCreate } from './LocationCreate'; +import { + LocationCreateFromJSON, + LocationCreateFromJSONTyped, + LocationCreateToJSON, + LocationCreateToJSONTyped, +} from './LocationCreate'; +import type { BreakTimeUpdate } from './BreakTimeUpdate'; +import { + BreakTimeUpdateFromJSON, + BreakTimeUpdateFromJSONTyped, + BreakTimeUpdateToJSON, + BreakTimeUpdateToJSONTyped, +} from './BreakTimeUpdate'; + +/** + * + * @export + * @interface ProjectTimeCreate + */ +export interface ProjectTimeCreate { + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof ProjectTimeCreate + */ + start: Date; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof ProjectTimeCreate + */ + end?: Date | null; + /** + * + * @type {Array} + * @memberof ProjectTimeCreate + */ + breakTimes?: Array; + /** + * + * @type {boolean} + * @memberof ProjectTimeCreate + */ + changed: boolean; + /** + * + * @type {string} + * @memberof ProjectTimeCreate + */ + notes?: string | null; + /** + * + * @type {string} + * @memberof ProjectTimeCreate + */ + taskId: string; + /** + * + * @type {boolean} + * @memberof ProjectTimeCreate + */ + billable?: boolean; + /** + * + * @type {ProjectTimeStatus} + * @memberof ProjectTimeCreate + */ + status: ProjectTimeStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof ProjectTimeCreate + */ + metadata?: { [key: string]: any; } | null; + /** + * + * @type {string} + * @memberof ProjectTimeCreate + */ + userId: string; + /** + * + * @type {LocationCreate} + * @memberof ProjectTimeCreate + */ + startLocation?: LocationCreate | null; + /** + * + * @type {LocationCreate} + * @memberof ProjectTimeCreate + */ + endLocation?: LocationCreate | null; +} + + + +/** + * Check if a given object implements the ProjectTimeCreate interface. + */ +export function instanceOfProjectTimeCreate(value: object): value is ProjectTimeCreate { + if (!('start' in value) || value['start'] === undefined) return false; + if (!('changed' in value) || value['changed'] === undefined) return false; + if (!('taskId' in value) || value['taskId'] === undefined) return false; + if (!('status' in value) || value['status'] === undefined) return false; + if (!('userId' in value) || value['userId'] === undefined) return false; + return true; +} + +export function ProjectTimeCreateFromJSON(json: any): ProjectTimeCreate { + return ProjectTimeCreateFromJSONTyped(json, false); +} + +export function ProjectTimeCreateFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProjectTimeCreate { + if (json == null) { + return json; + } + return { + + 'start': (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'breakTimes': json['break_times'] == null ? undefined : ((json['break_times'] as Array).map(BreakTimeUpdateFromJSON)), + 'changed': json['changed'], + 'notes': json['notes'] == null ? undefined : json['notes'], + 'taskId': json['task_id'], + 'billable': json['billable'] == null ? undefined : json['billable'], + 'status': ProjectTimeStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + 'userId': json['user_id'], + 'startLocation': json['start_location'] == null ? undefined : LocationCreateFromJSON(json['start_location']), + 'endLocation': json['end_location'] == null ? undefined : LocationCreateFromJSON(json['end_location']), + }; +} + +export function ProjectTimeCreateToJSON(json: any): ProjectTimeCreate { + return ProjectTimeCreateToJSONTyped(json, false); +} + +export function ProjectTimeCreateToJSONTyped(value?: ProjectTimeCreate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'break_times': value['breakTimes'] == null ? undefined : ((value['breakTimes'] as Array).map(BreakTimeUpdateToJSON)), + 'changed': value['changed'], + 'notes': value['notes'], + 'task_id': value['taskId'], + 'billable': value['billable'], + 'status': ProjectTimeStatusToJSON(value['status']), + 'metadata': value['metadata'], + 'user_id': value['userId'], + 'start_location': LocationCreateToJSON(value['startLocation']), + 'end_location': LocationCreateToJSON(value['endLocation']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/ProjectTimeStatus.ts b/sdk/typescript-fetch/src/models/ProjectTimeStatus.ts new file mode 100644 index 0000000..b0bf294 --- /dev/null +++ b/sdk/typescript-fetch/src/models/ProjectTimeStatus.ts @@ -0,0 +1,59 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Processing state of a Project Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, cleared, closed and archived. + * @export + */ +export const ProjectTimeStatus = { + Running: 'running', + Paused: 'paused', + Changeable: 'changeable', + Locked: 'locked', + Approved: 'approved', + Cleared: 'cleared', + Closed: 'closed', + Archived: 'archived' +} as const; +export type ProjectTimeStatus = typeof ProjectTimeStatus[keyof typeof ProjectTimeStatus]; + + +export function instanceOfProjectTimeStatus(value: any): boolean { + for (const key in ProjectTimeStatus) { + if (Object.prototype.hasOwnProperty.call(ProjectTimeStatus, key)) { + if (ProjectTimeStatus[key as keyof typeof ProjectTimeStatus] === value) { + return true; + } + } + } + return false; +} + +export function ProjectTimeStatusFromJSON(json: any): ProjectTimeStatus { + return ProjectTimeStatusFromJSONTyped(json, false); +} + +export function ProjectTimeStatusFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProjectTimeStatus { + return json as ProjectTimeStatus; +} + +export function ProjectTimeStatusToJSON(value?: ProjectTimeStatus | null): any { + return value as any; +} + +export function ProjectTimeStatusToJSONTyped(value: any, ignoreDiscriminator: boolean): ProjectTimeStatus { + return value as ProjectTimeStatus; +} + diff --git a/sdk/typescript-fetch/src/models/ProjectTimeUpdate.ts b/sdk/typescript-fetch/src/models/ProjectTimeUpdate.ts new file mode 100644 index 0000000..89b4476 --- /dev/null +++ b/sdk/typescript-fetch/src/models/ProjectTimeUpdate.ts @@ -0,0 +1,169 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { ProjectTimeStatus } from './ProjectTimeStatus'; +import { + ProjectTimeStatusFromJSON, + ProjectTimeStatusFromJSONTyped, + ProjectTimeStatusToJSON, + ProjectTimeStatusToJSONTyped, +} from './ProjectTimeStatus'; +import type { BreakTimeUpdate } from './BreakTimeUpdate'; +import { + BreakTimeUpdateFromJSON, + BreakTimeUpdateFromJSONTyped, + BreakTimeUpdateToJSON, + BreakTimeUpdateToJSONTyped, +} from './BreakTimeUpdate'; +import type { LocationUpdate } from './LocationUpdate'; +import { + LocationUpdateFromJSON, + LocationUpdateFromJSONTyped, + LocationUpdateToJSON, + LocationUpdateToJSONTyped, +} from './LocationUpdate'; + +/** + * + * @export + * @interface ProjectTimeUpdate + */ +export interface ProjectTimeUpdate { + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof ProjectTimeUpdate + */ + start?: Date; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof ProjectTimeUpdate + */ + end?: Date | null; + /** + * + * @type {Array} + * @memberof ProjectTimeUpdate + */ + breakTimes?: Array; + /** + * + * @type {boolean} + * @memberof ProjectTimeUpdate + */ + changed?: boolean; + /** + * + * @type {string} + * @memberof ProjectTimeUpdate + */ + notes?: string | null; + /** + * + * @type {string} + * @memberof ProjectTimeUpdate + */ + taskId?: string; + /** + * + * @type {boolean} + * @memberof ProjectTimeUpdate + */ + billable?: boolean; + /** + * + * @type {ProjectTimeStatus} + * @memberof ProjectTimeUpdate + */ + status?: ProjectTimeStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof ProjectTimeUpdate + */ + metadata?: { [key: string]: any; } | null; + /** + * + * @type {LocationUpdate} + * @memberof ProjectTimeUpdate + */ + startLocation?: LocationUpdate | null; + /** + * + * @type {LocationUpdate} + * @memberof ProjectTimeUpdate + */ + endLocation?: LocationUpdate | null; +} + + + +/** + * Check if a given object implements the ProjectTimeUpdate interface. + */ +export function instanceOfProjectTimeUpdate(value: object): value is ProjectTimeUpdate { + return true; +} + +export function ProjectTimeUpdateFromJSON(json: any): ProjectTimeUpdate { + return ProjectTimeUpdateFromJSONTyped(json, false); +} + +export function ProjectTimeUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProjectTimeUpdate { + if (json == null) { + return json; + } + return { + + 'start': json['start'] == null ? undefined : (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'breakTimes': json['break_times'] == null ? undefined : ((json['break_times'] as Array).map(BreakTimeUpdateFromJSON)), + 'changed': json['changed'] == null ? undefined : json['changed'], + 'notes': json['notes'] == null ? undefined : json['notes'], + 'taskId': json['task_id'] == null ? undefined : json['task_id'], + 'billable': json['billable'] == null ? undefined : json['billable'], + 'status': json['status'] == null ? undefined : ProjectTimeStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + 'startLocation': json['start_location'] == null ? undefined : LocationUpdateFromJSON(json['start_location']), + 'endLocation': json['end_location'] == null ? undefined : LocationUpdateFromJSON(json['end_location']), + }; +} + +export function ProjectTimeUpdateToJSON(json: any): ProjectTimeUpdate { + return ProjectTimeUpdateToJSONTyped(json, false); +} + +export function ProjectTimeUpdateToJSONTyped(value?: ProjectTimeUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'] == null ? value['start'] : value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'break_times': value['breakTimes'] == null ? undefined : ((value['breakTimes'] as Array).map(BreakTimeUpdateToJSON)), + 'changed': value['changed'], + 'notes': value['notes'], + 'task_id': value['taskId'], + 'billable': value['billable'], + 'status': ProjectTimeStatusToJSON(value['status']), + 'metadata': value['metadata'], + 'start_location': LocationUpdateToJSON(value['startLocation']), + 'end_location': LocationUpdateToJSON(value['endLocation']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/ProjectTimeUpsert.ts b/sdk/typescript-fetch/src/models/ProjectTimeUpsert.ts new file mode 100644 index 0000000..222927a --- /dev/null +++ b/sdk/typescript-fetch/src/models/ProjectTimeUpsert.ts @@ -0,0 +1,146 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { ProjectTimeStatus } from './ProjectTimeStatus'; +import { + ProjectTimeStatusFromJSON, + ProjectTimeStatusFromJSONTyped, + ProjectTimeStatusToJSON, + ProjectTimeStatusToJSONTyped, +} from './ProjectTimeStatus'; +import type { BreakTimeUpdate } from './BreakTimeUpdate'; +import { + BreakTimeUpdateFromJSON, + BreakTimeUpdateFromJSONTyped, + BreakTimeUpdateToJSON, + BreakTimeUpdateToJSONTyped, +} from './BreakTimeUpdate'; + +/** + * + * @export + * @interface ProjectTimeUpsert + */ +export interface ProjectTimeUpsert { + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof ProjectTimeUpsert + */ + start?: Date; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof ProjectTimeUpsert + */ + end?: Date | null; + /** + * + * @type {Array} + * @memberof ProjectTimeUpsert + */ + breakTimes?: Array; + /** + * + * @type {boolean} + * @memberof ProjectTimeUpsert + */ + changed?: boolean; + /** + * + * @type {string} + * @memberof ProjectTimeUpsert + */ + notes?: string | null; + /** + * + * @type {string} + * @memberof ProjectTimeUpsert + */ + taskId?: string; + /** + * + * @type {boolean} + * @memberof ProjectTimeUpsert + */ + billable?: boolean; + /** + * + * @type {ProjectTimeStatus} + * @memberof ProjectTimeUpsert + */ + status?: ProjectTimeStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof ProjectTimeUpsert + */ + metadata?: { [key: string]: any; } | null; +} + + + +/** + * Check if a given object implements the ProjectTimeUpsert interface. + */ +export function instanceOfProjectTimeUpsert(value: object): value is ProjectTimeUpsert { + return true; +} + +export function ProjectTimeUpsertFromJSON(json: any): ProjectTimeUpsert { + return ProjectTimeUpsertFromJSONTyped(json, false); +} + +export function ProjectTimeUpsertFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProjectTimeUpsert { + if (json == null) { + return json; + } + return { + + 'start': json['start'] == null ? undefined : (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'breakTimes': json['break_times'] == null ? undefined : ((json['break_times'] as Array).map(BreakTimeUpdateFromJSON)), + 'changed': json['changed'] == null ? undefined : json['changed'], + 'notes': json['notes'] == null ? undefined : json['notes'], + 'taskId': json['task_id'] == null ? undefined : json['task_id'], + 'billable': json['billable'] == null ? undefined : json['billable'], + 'status': json['status'] == null ? undefined : ProjectTimeStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function ProjectTimeUpsertToJSON(json: any): ProjectTimeUpsert { + return ProjectTimeUpsertToJSONTyped(json, false); +} + +export function ProjectTimeUpsertToJSONTyped(value?: ProjectTimeUpsert | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'] == null ? value['start'] : value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'break_times': value['breakTimes'] == null ? undefined : ((value['breakTimes'] as Array).map(BreakTimeUpdateToJSON)), + 'changed': value['changed'], + 'notes': value['notes'], + 'task_id': value['taskId'], + 'billable': value['billable'], + 'status': ProjectTimeStatusToJSON(value['status']), + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/ProjectTimesPage.ts b/sdk/typescript-fetch/src/models/ProjectTimesPage.ts new file mode 100644 index 0000000..68e2a33 --- /dev/null +++ b/sdk/typescript-fetch/src/models/ProjectTimesPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { ProjectTime } from './ProjectTime'; +import { + ProjectTimeFromJSON, + ProjectTimeFromJSONTyped, + ProjectTimeToJSON, + ProjectTimeToJSONTyped, +} from './ProjectTime'; + +/** + * + * @export + * @interface ProjectTimesPage + */ +export interface ProjectTimesPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof ProjectTimesPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof ProjectTimesPage + */ + data: Array; +} + +/** + * Check if a given object implements the ProjectTimesPage interface. + */ +export function instanceOfProjectTimesPage(value: object): value is ProjectTimesPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function ProjectTimesPageFromJSON(json: any): ProjectTimesPage { + return ProjectTimesPageFromJSONTyped(json, false); +} + +export function ProjectTimesPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProjectTimesPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(ProjectTimeFromJSON)), + }; +} + +export function ProjectTimesPageToJSON(json: any): ProjectTimesPage { + return ProjectTimesPageToJSONTyped(json, false); +} + +export function ProjectTimesPageToJSONTyped(value?: ProjectTimesPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(ProjectTimeToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/ProjectTimesSortColumn.ts b/sdk/typescript-fetch/src/models/ProjectTimesSortColumn.ts new file mode 100644 index 0000000..6334b5e --- /dev/null +++ b/sdk/typescript-fetch/src/models/ProjectTimesSortColumn.ts @@ -0,0 +1,53 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Project Times. + * @export + */ +export const ProjectTimesSortColumn = { + Start: 'start', + LastModified: 'last_modified' +} as const; +export type ProjectTimesSortColumn = typeof ProjectTimesSortColumn[keyof typeof ProjectTimesSortColumn]; + + +export function instanceOfProjectTimesSortColumn(value: any): boolean { + for (const key in ProjectTimesSortColumn) { + if (Object.prototype.hasOwnProperty.call(ProjectTimesSortColumn, key)) { + if (ProjectTimesSortColumn[key as keyof typeof ProjectTimesSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function ProjectTimesSortColumnFromJSON(json: any): ProjectTimesSortColumn { + return ProjectTimesSortColumnFromJSONTyped(json, false); +} + +export function ProjectTimesSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): ProjectTimesSortColumn { + return json as ProjectTimesSortColumn; +} + +export function ProjectTimesSortColumnToJSON(value?: ProjectTimesSortColumn | null): any { + return value as any; +} + +export function ProjectTimesSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): ProjectTimesSortColumn { + return value as ProjectTimesSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/RecordingLockType.ts b/sdk/typescript-fetch/src/models/RecordingLockType.ts new file mode 100644 index 0000000..d04a4a3 --- /dev/null +++ b/sdk/typescript-fetch/src/models/RecordingLockType.ts @@ -0,0 +1,55 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Whether the assigned User may record on the Task, and where the lock comes from. `recordable` allows recording; `locked_automatically` follows the Task's lock date; `locked_manually` and `unlocked_manually` are explicit overrides for this assignment. + * @export + */ +export const RecordingLockType = { + Recordable: 'recordable', + LockedAutomatically: 'locked_automatically', + LockedManually: 'locked_manually', + UnlockedManually: 'unlocked_manually' +} as const; +export type RecordingLockType = typeof RecordingLockType[keyof typeof RecordingLockType]; + + +export function instanceOfRecordingLockType(value: any): boolean { + for (const key in RecordingLockType) { + if (Object.prototype.hasOwnProperty.call(RecordingLockType, key)) { + if (RecordingLockType[key as keyof typeof RecordingLockType] === value) { + return true; + } + } + } + return false; +} + +export function RecordingLockTypeFromJSON(json: any): RecordingLockType { + return RecordingLockTypeFromJSONTyped(json, false); +} + +export function RecordingLockTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): RecordingLockType { + return json as RecordingLockType; +} + +export function RecordingLockTypeToJSON(value?: RecordingLockType | null): any { + return value as any; +} + +export function RecordingLockTypeToJSONTyped(value: any, ignoreDiscriminator: boolean): RecordingLockType { + return value as RecordingLockType; +} + diff --git a/sdk/typescript-fetch/src/models/RecordingModeUser.ts b/sdk/typescript-fetch/src/models/RecordingModeUser.ts new file mode 100644 index 0000000..dc9fdc5 --- /dev/null +++ b/sdk/typescript-fetch/src/models/RecordingModeUser.ts @@ -0,0 +1,54 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Whether a User may record this Working Time Type themselves. Only meaningful for day-based types. + * @export + */ +export const RecordingModeUser = { + NotAllowed: 'not_allowed', + Allowed: 'allowed', + ByRequest: 'by_request' +} as const; +export type RecordingModeUser = typeof RecordingModeUser[keyof typeof RecordingModeUser]; + + +export function instanceOfRecordingModeUser(value: any): boolean { + for (const key in RecordingModeUser) { + if (Object.prototype.hasOwnProperty.call(RecordingModeUser, key)) { + if (RecordingModeUser[key as keyof typeof RecordingModeUser] === value) { + return true; + } + } + } + return false; +} + +export function RecordingModeUserFromJSON(json: any): RecordingModeUser { + return RecordingModeUserFromJSONTyped(json, false); +} + +export function RecordingModeUserFromJSONTyped(json: any, ignoreDiscriminator: boolean): RecordingModeUser { + return json as RecordingModeUser; +} + +export function RecordingModeUserToJSON(value?: RecordingModeUser | null): any { + return value as any; +} + +export function RecordingModeUserToJSONTyped(value: any, ignoreDiscriminator: boolean): RecordingModeUser { + return value as RecordingModeUser; +} + diff --git a/sdk/typescript-fetch/src/models/SortDirection.ts b/sdk/typescript-fetch/src/models/SortDirection.ts new file mode 100644 index 0000000..87668fe --- /dev/null +++ b/sdk/typescript-fetch/src/models/SortDirection.ts @@ -0,0 +1,53 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort direction — `asc` for ascending, `dsc` for descending. + * @export + */ +export const SortDirection = { + Asc: 'asc', + Dsc: 'dsc' +} as const; +export type SortDirection = typeof SortDirection[keyof typeof SortDirection]; + + +export function instanceOfSortDirection(value: any): boolean { + for (const key in SortDirection) { + if (Object.prototype.hasOwnProperty.call(SortDirection, key)) { + if (SortDirection[key as keyof typeof SortDirection] === value) { + return true; + } + } + } + return false; +} + +export function SortDirectionFromJSON(json: any): SortDirection { + return SortDirectionFromJSONTyped(json, false); +} + +export function SortDirectionFromJSONTyped(json: any, ignoreDiscriminator: boolean): SortDirection { + return json as SortDirection; +} + +export function SortDirectionToJSON(value?: SortDirection | null): any { + return value as any; +} + +export function SortDirectionToJSONTyped(value: any, ignoreDiscriminator: boolean): SortDirection { + return value as SortDirection; +} + diff --git a/sdk/typescript-fetch/src/models/Task.ts b/sdk/typescript-fetch/src/models/Task.ts new file mode 100644 index 0000000..c3ca5e1 --- /dev/null +++ b/sdk/typescript-fetch/src/models/Task.ts @@ -0,0 +1,339 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TaskPartial } from './TaskPartial'; +import { + TaskPartialFromJSON, + TaskPartialFromJSONTyped, + TaskPartialToJSON, + TaskPartialToJSONTyped, +} from './TaskPartial'; +import type { TaskLocation } from './TaskLocation'; +import { + TaskLocationFromJSON, + TaskLocationFromJSONTyped, + TaskLocationToJSON, + TaskLocationToJSONTyped, +} from './TaskLocation'; +import type { BudgetPlanningType } from './BudgetPlanningType'; +import { + BudgetPlanningTypeFromJSON, + BudgetPlanningTypeFromJSONTyped, + BudgetPlanningTypeToJSON, + BudgetPlanningTypeToJSONTyped, +} from './BudgetPlanningType'; + +/** + * A task, placed in the tree by `parent_task`, with the full path from the root in `breadcrumbs`. `bookable` and `billable` control recording and invoicing; `lock_date`, time windows and location constrain what may be recorded. + * + * @export + * @interface Task + */ +export interface Task { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof Task + */ + id: string; + /** + * + * @type {string} + * @memberof Task + */ + name: string; + /** + * Full path of the entry within its hierarchy, including its own name. + * @type {string} + * @memberof Task + */ + breadcrumbs: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof Task + */ + externalId: string | null; + /** + * + * @type {TaskPartial} + * @memberof Task + */ + parentTask: TaskPartial | null; + /** + * + * @type {string} + * @memberof Task + */ + description: string | null; + /** + * + * @type {string} + * @memberof Task + */ + descriptionExternal: string | null; + /** + * + * @type {boolean} + * @memberof Task + */ + bookable: boolean; + /** + * + * @type {boolean} + * @memberof Task + */ + billable: boolean; + /** + * + * @type {boolean} + * @memberof Task + */ + projectTimeNotesRequired: boolean; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof Task + */ + startDate: Date | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof Task + */ + endDate: Date | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof Task + */ + lockDate?: Date | null; + /** + * time of day (ISO-8601) + * @type {string} + * @memberof Task + */ + earliestStartTime?: string | null; + /** + * time of day (ISO-8601) + * @type {string} + * @memberof Task + */ + latestEndTime?: string | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof Task + */ + activeFrom: Date | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof Task + */ + activeTo: Date | null; + /** + * + * @type {boolean} + * @memberof Task + */ + budgetInherited?: boolean; + /** + * + * @type {BudgetPlanningType} + * @memberof Task + */ + budgetPlanningType?: BudgetPlanningType; + /** + * + * @type {number} + * @memberof Task + */ + budgetHoursPlanned?: number | null; + /** + * + * @type {number} + * @memberof Task + */ + budgetHourlyRate?: number | null; + /** + * + * @type {number} + * @memberof Task + */ + budgetPlanned?: number | null; + /** + * + * @type {boolean} + * @memberof Task + */ + budgetIncludeNonBillableProjectTimes?: boolean; + /** + * + * @type {boolean} + * @memberof Task + */ + locationInherited?: boolean; + /** + * + * @type {TaskLocation} + * @memberof Task + */ + location?: TaskLocation | null; + /** + * + * @type {number} + * @memberof Task + */ + locationRestrictionRadiusMeters?: number | null; + /** + * + * @type {string} + * @memberof Task + */ + customField1: string | null; + /** + * + * @type {string} + * @memberof Task + */ + customField2: string | null; + /** + * + * @type {string} + * @memberof Task + */ + customField3: string | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof Task + */ + metadata?: { [key: string]: any; } | null; +} + + + +/** + * Check if a given object implements the Task interface. + */ +export function instanceOfTask(value: object): value is Task { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('breadcrumbs' in value) || value['breadcrumbs'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + if (!('parentTask' in value) || value['parentTask'] === undefined) return false; + if (!('description' in value) || value['description'] === undefined) return false; + if (!('descriptionExternal' in value) || value['descriptionExternal'] === undefined) return false; + if (!('bookable' in value) || value['bookable'] === undefined) return false; + if (!('billable' in value) || value['billable'] === undefined) return false; + if (!('projectTimeNotesRequired' in value) || value['projectTimeNotesRequired'] === undefined) return false; + if (!('startDate' in value) || value['startDate'] === undefined) return false; + if (!('endDate' in value) || value['endDate'] === undefined) return false; + if (!('activeFrom' in value) || value['activeFrom'] === undefined) return false; + if (!('activeTo' in value) || value['activeTo'] === undefined) return false; + if (!('customField1' in value) || value['customField1'] === undefined) return false; + if (!('customField2' in value) || value['customField2'] === undefined) return false; + if (!('customField3' in value) || value['customField3'] === undefined) return false; + return true; +} + +export function TaskFromJSON(json: any): Task { + return TaskFromJSONTyped(json, false); +} + +export function TaskFromJSONTyped(json: any, ignoreDiscriminator: boolean): Task { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'breadcrumbs': json['breadcrumbs'], + 'externalId': json['external_id'], + 'parentTask': TaskPartialFromJSON(json['parent_task']), + 'description': json['description'], + 'descriptionExternal': json['description_external'], + 'bookable': json['bookable'], + 'billable': json['billable'], + 'projectTimeNotesRequired': json['project_time_notes_required'], + 'startDate': (json['start_date'] == null ? null : new Date(json['start_date'])), + 'endDate': (json['end_date'] == null ? null : new Date(json['end_date'])), + 'lockDate': json['lock_date'] == null ? undefined : (new Date(json['lock_date'])), + 'earliestStartTime': json['earliest_start_time'] == null ? undefined : json['earliest_start_time'], + 'latestEndTime': json['latest_end_time'] == null ? undefined : json['latest_end_time'], + 'activeFrom': (json['active_from'] == null ? null : new Date(json['active_from'])), + 'activeTo': (json['active_to'] == null ? null : new Date(json['active_to'])), + 'budgetInherited': json['budget_inherited'] == null ? undefined : json['budget_inherited'], + 'budgetPlanningType': json['budget_planning_type'] == null ? undefined : BudgetPlanningTypeFromJSON(json['budget_planning_type']), + 'budgetHoursPlanned': json['budget_hours_planned'] == null ? undefined : json['budget_hours_planned'], + 'budgetHourlyRate': json['budget_hourly_rate'] == null ? undefined : json['budget_hourly_rate'], + 'budgetPlanned': json['budget_planned'] == null ? undefined : json['budget_planned'], + 'budgetIncludeNonBillableProjectTimes': json['budget_include_non_billable_project_times'] == null ? undefined : json['budget_include_non_billable_project_times'], + 'locationInherited': json['location_inherited'] == null ? undefined : json['location_inherited'], + 'location': json['location'] == null ? undefined : TaskLocationFromJSON(json['location']), + 'locationRestrictionRadiusMeters': json['location_restriction_radius_meters'] == null ? undefined : json['location_restriction_radius_meters'], + 'customField1': json['custom_field_1'], + 'customField2': json['custom_field_2'], + 'customField3': json['custom_field_3'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function TaskToJSON(json: any): Task { + return TaskToJSONTyped(json, false); +} + +export function TaskToJSONTyped(value?: Task | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'breadcrumbs': value['breadcrumbs'], + 'external_id': value['externalId'], + 'parent_task': TaskPartialToJSON(value['parentTask']), + 'description': value['description'], + 'description_external': value['descriptionExternal'], + 'bookable': value['bookable'], + 'billable': value['billable'], + 'project_time_notes_required': value['projectTimeNotesRequired'], + 'start_date': value['startDate'] == null ? value['startDate'] : value['startDate'].toISOString().substring(0,10), + 'end_date': value['endDate'] == null ? value['endDate'] : value['endDate'].toISOString().substring(0,10), + 'lock_date': value['lockDate'] == null ? value['lockDate'] : value['lockDate'].toISOString().substring(0,10), + 'earliest_start_time': value['earliestStartTime'], + 'latest_end_time': value['latestEndTime'], + 'active_from': value['activeFrom'] == null ? value['activeFrom'] : value['activeFrom'].toISOString().substring(0,10), + 'active_to': value['activeTo'] == null ? value['activeTo'] : value['activeTo'].toISOString().substring(0,10), + 'budget_inherited': value['budgetInherited'], + 'budget_planning_type': BudgetPlanningTypeToJSON(value['budgetPlanningType']), + 'budget_hours_planned': value['budgetHoursPlanned'], + 'budget_hourly_rate': value['budgetHourlyRate'], + 'budget_planned': value['budgetPlanned'], + 'budget_include_non_billable_project_times': value['budgetIncludeNonBillableProjectTimes'], + 'location_inherited': value['locationInherited'], + 'location': TaskLocationToJSON(value['location']), + 'location_restriction_radius_meters': value['locationRestrictionRadiusMeters'], + 'custom_field_1': value['customField1'], + 'custom_field_2': value['customField2'], + 'custom_field_3': value['customField3'], + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskBase.ts b/sdk/typescript-fetch/src/models/TaskBase.ts new file mode 100644 index 0000000..77f3a65 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskBase.ts @@ -0,0 +1,293 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { BudgetPlanningTypeRequest } from './BudgetPlanningTypeRequest'; +import { + BudgetPlanningTypeRequestFromJSON, + BudgetPlanningTypeRequestFromJSONTyped, + BudgetPlanningTypeRequestToJSON, + BudgetPlanningTypeRequestToJSONTyped, +} from './BudgetPlanningTypeRequest'; +import type { TaskLocation } from './TaskLocation'; +import { + TaskLocationFromJSON, + TaskLocationFromJSONTyped, + TaskLocationToJSON, + TaskLocationToJSONTyped, +} from './TaskLocation'; + +/** + * + * @export + * @interface TaskBase + */ +export interface TaskBase { + /** + * + * @type {string} + * @memberof TaskBase + */ + name?: string; + /** + * returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @type {string} + * @memberof TaskBase + */ + parentTaskId?: string | null; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof TaskBase + */ + externalId?: string | null; + /** + * + * @type {string} + * @memberof TaskBase + */ + description?: string | null; + /** + * + * @type {string} + * @memberof TaskBase + */ + descriptionExternal?: string | null; + /** + * when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @type {boolean} + * @memberof TaskBase + */ + bookable?: boolean; + /** + * + * @type {boolean} + * @memberof TaskBase + */ + billable?: boolean; + /** + * depending on this property project times booked on this task have to include notes or not + * @type {boolean} + * @memberof TaskBase + */ + projectTimeNotesRequired?: boolean; + /** + * the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @type {Date} + * @memberof TaskBase + */ + startDate?: Date | null; + /** + * the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @type {Date} + * @memberof TaskBase + */ + endDate?: Date | null; + /** + * with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that + * + * * existing entries cannot be changed or deleted + * * no entries can be added later + * + * @type {Date} + * @memberof TaskBase + */ + lockDate?: Date | null; + /** + * set this property to limit the task so that it cannot be booked before this time + * @type {string} + * @memberof TaskBase + */ + earliestStartTime?: string | null; + /** + * set this property to limit the task so that it cannot be booked after this time + * @type {string} + * @memberof TaskBase + */ + latestEndTime?: string | null; + /** + * when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * + * @type {BudgetPlanningTypeRequest} + * @memberof TaskBase + */ + budgetPlanningType?: BudgetPlanningTypeRequest; + /** + * how many hours were planned in the calculation + * set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: + * * task_hourly_rate: out of budget_hourly_rate and budget_planned + * * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned + * * fixed_price: out of budget_hourly_rate and budget_planned + * + * @type {number} + * @memberof TaskBase + */ + budgetHoursPlanned?: number | null; + /** + * depending on its budget_planning_type this property may or may not be set: + * * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** + * * **user_hourly_rate: this property cannot be set** + * * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * + * @type {number} + * @memberof TaskBase + */ + budgetHourlyRate?: number | null; + /** + * the price at which the task was sold + * set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: + * * task_hourly_rate: out of budget_hourly_rate and budget_planned + * * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned + * * fixed_price: out of budget_hourly_rate and budget_planned + * + * @type {number} + * @memberof TaskBase + */ + budgetPlanned?: number | null; + /** + * set this property to true, if you want to include not billable hours for all project times booked on this task + * @type {boolean} + * @memberof TaskBase + */ + budgetIncludeNonBillableProjectTimes?: boolean; + /** + * set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @type {boolean} + * @memberof TaskBase + */ + locationInherited?: boolean; + /** + * + * @type {TaskLocation} + * @memberof TaskBase + */ + location?: TaskLocation | null; + /** + * set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @type {number} + * @memberof TaskBase + */ + locationRestrictionRadiusMeters?: number | null; + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @type {string} + * @memberof TaskBase + */ + customField1?: string | null; + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @type {string} + * @memberof TaskBase + */ + customField2?: string | null; + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @type {string} + * @memberof TaskBase + */ + customField3?: string | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof TaskBase + */ + metadata?: { [key: string]: any; } | null; +} + + + +/** + * Check if a given object implements the TaskBase interface. + */ +export function instanceOfTaskBase(value: object): value is TaskBase { + return true; +} + +export function TaskBaseFromJSON(json: any): TaskBase { + return TaskBaseFromJSONTyped(json, false); +} + +export function TaskBaseFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskBase { + if (json == null) { + return json; + } + return { + + 'name': json['name'] == null ? undefined : json['name'], + 'parentTaskId': json['parent_task_id'] == null ? undefined : json['parent_task_id'], + 'externalId': json['external_id'] == null ? undefined : json['external_id'], + 'description': json['description'] == null ? undefined : json['description'], + 'descriptionExternal': json['description_external'] == null ? undefined : json['description_external'], + 'bookable': json['bookable'] == null ? undefined : json['bookable'], + 'billable': json['billable'] == null ? undefined : json['billable'], + 'projectTimeNotesRequired': json['project_time_notes_required'] == null ? undefined : json['project_time_notes_required'], + 'startDate': json['start_date'] == null ? undefined : (new Date(json['start_date'])), + 'endDate': json['end_date'] == null ? undefined : (new Date(json['end_date'])), + 'lockDate': json['lock_date'] == null ? undefined : (new Date(json['lock_date'])), + 'earliestStartTime': json['earliest_start_time'] == null ? undefined : json['earliest_start_time'], + 'latestEndTime': json['latest_end_time'] == null ? undefined : json['latest_end_time'], + 'budgetPlanningType': json['budget_planning_type'] == null ? undefined : BudgetPlanningTypeRequestFromJSON(json['budget_planning_type']), + 'budgetHoursPlanned': json['budget_hours_planned'] == null ? undefined : json['budget_hours_planned'], + 'budgetHourlyRate': json['budget_hourly_rate'] == null ? undefined : json['budget_hourly_rate'], + 'budgetPlanned': json['budget_planned'] == null ? undefined : json['budget_planned'], + 'budgetIncludeNonBillableProjectTimes': json['budget_include_non_billable_project_times'] == null ? undefined : json['budget_include_non_billable_project_times'], + 'locationInherited': json['location_inherited'] == null ? undefined : json['location_inherited'], + 'location': json['location'] == null ? undefined : TaskLocationFromJSON(json['location']), + 'locationRestrictionRadiusMeters': json['location_restriction_radius_meters'] == null ? undefined : json['location_restriction_radius_meters'], + 'customField1': json['custom_field_1'] == null ? undefined : json['custom_field_1'], + 'customField2': json['custom_field_2'] == null ? undefined : json['custom_field_2'], + 'customField3': json['custom_field_3'] == null ? undefined : json['custom_field_3'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function TaskBaseToJSON(json: any): TaskBase { + return TaskBaseToJSONTyped(json, false); +} + +export function TaskBaseToJSONTyped(value?: TaskBase | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'name': value['name'], + 'parent_task_id': value['parentTaskId'], + 'external_id': value['externalId'], + 'description': value['description'], + 'description_external': value['descriptionExternal'], + 'bookable': value['bookable'], + 'billable': value['billable'], + 'project_time_notes_required': value['projectTimeNotesRequired'], + 'start_date': value['startDate'] == null ? value['startDate'] : value['startDate'].toISOString().substring(0,10), + 'end_date': value['endDate'] == null ? value['endDate'] : value['endDate'].toISOString().substring(0,10), + 'lock_date': value['lockDate'] == null ? value['lockDate'] : value['lockDate'].toISOString().substring(0,10), + 'earliest_start_time': value['earliestStartTime'], + 'latest_end_time': value['latestEndTime'], + 'budget_planning_type': BudgetPlanningTypeRequestToJSON(value['budgetPlanningType']), + 'budget_hours_planned': value['budgetHoursPlanned'], + 'budget_hourly_rate': value['budgetHourlyRate'], + 'budget_planned': value['budgetPlanned'], + 'budget_include_non_billable_project_times': value['budgetIncludeNonBillableProjectTimes'], + 'location_inherited': value['locationInherited'], + 'location': TaskLocationToJSON(value['location']), + 'location_restriction_radius_meters': value['locationRestrictionRadiusMeters'], + 'custom_field_1': value['customField1'], + 'custom_field_2': value['customField2'], + 'custom_field_3': value['customField3'], + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskCreate.ts b/sdk/typescript-fetch/src/models/TaskCreate.ts new file mode 100644 index 0000000..f815986 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskCreate.ts @@ -0,0 +1,296 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { BudgetPlanningTypeRequest } from './BudgetPlanningTypeRequest'; +import { + BudgetPlanningTypeRequestFromJSON, + BudgetPlanningTypeRequestFromJSONTyped, + BudgetPlanningTypeRequestToJSON, + BudgetPlanningTypeRequestToJSONTyped, +} from './BudgetPlanningTypeRequest'; +import type { TaskLocation } from './TaskLocation'; +import { + TaskLocationFromJSON, + TaskLocationFromJSONTyped, + TaskLocationToJSON, + TaskLocationToJSONTyped, +} from './TaskLocation'; + +/** + * + * @export + * @interface TaskCreate + */ +export interface TaskCreate { + /** + * + * @type {string} + * @memberof TaskCreate + */ + name: string; + /** + * returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @type {string} + * @memberof TaskCreate + */ + parentTaskId?: string | null; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof TaskCreate + */ + externalId?: string | null; + /** + * + * @type {string} + * @memberof TaskCreate + */ + description?: string | null; + /** + * + * @type {string} + * @memberof TaskCreate + */ + descriptionExternal?: string | null; + /** + * when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @type {boolean} + * @memberof TaskCreate + */ + bookable: boolean; + /** + * + * @type {boolean} + * @memberof TaskCreate + */ + billable: boolean; + /** + * depending on this property project times booked on this task have to include notes or not + * @type {boolean} + * @memberof TaskCreate + */ + projectTimeNotesRequired?: boolean; + /** + * the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @type {Date} + * @memberof TaskCreate + */ + startDate?: Date | null; + /** + * the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @type {Date} + * @memberof TaskCreate + */ + endDate?: Date | null; + /** + * with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that + * + * * existing entries cannot be changed or deleted + * * no entries can be added later + * + * @type {Date} + * @memberof TaskCreate + */ + lockDate?: Date | null; + /** + * set this property to limit the task so that it cannot be booked before this time + * @type {string} + * @memberof TaskCreate + */ + earliestStartTime?: string | null; + /** + * set this property to limit the task so that it cannot be booked after this time + * @type {string} + * @memberof TaskCreate + */ + latestEndTime?: string | null; + /** + * when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * + * @type {BudgetPlanningTypeRequest} + * @memberof TaskCreate + */ + budgetPlanningType?: BudgetPlanningTypeRequest; + /** + * how many hours were planned in the calculation + * set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: + * * task_hourly_rate: out of budget_hourly_rate and budget_planned + * * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned + * * fixed_price: out of budget_hourly_rate and budget_planned + * + * @type {number} + * @memberof TaskCreate + */ + budgetHoursPlanned?: number | null; + /** + * depending on its budget_planning_type this property may or may not be set: + * * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** + * * **user_hourly_rate: this property cannot be set** + * * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * + * @type {number} + * @memberof TaskCreate + */ + budgetHourlyRate?: number | null; + /** + * the price at which the task was sold + * set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: + * * task_hourly_rate: out of budget_hourly_rate and budget_planned + * * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned + * * fixed_price: out of budget_hourly_rate and budget_planned + * + * @type {number} + * @memberof TaskCreate + */ + budgetPlanned?: number | null; + /** + * set this property to true, if you want to include not billable hours for all project times booked on this task + * @type {boolean} + * @memberof TaskCreate + */ + budgetIncludeNonBillableProjectTimes?: boolean; + /** + * set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @type {boolean} + * @memberof TaskCreate + */ + locationInherited?: boolean; + /** + * + * @type {TaskLocation} + * @memberof TaskCreate + */ + location?: TaskLocation | null; + /** + * set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @type {number} + * @memberof TaskCreate + */ + locationRestrictionRadiusMeters?: number | null; + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @type {string} + * @memberof TaskCreate + */ + customField1?: string | null; + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @type {string} + * @memberof TaskCreate + */ + customField2?: string | null; + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @type {string} + * @memberof TaskCreate + */ + customField3?: string | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof TaskCreate + */ + metadata?: { [key: string]: any; } | null; +} + + + +/** + * Check if a given object implements the TaskCreate interface. + */ +export function instanceOfTaskCreate(value: object): value is TaskCreate { + if (!('name' in value) || value['name'] === undefined) return false; + if (!('bookable' in value) || value['bookable'] === undefined) return false; + if (!('billable' in value) || value['billable'] === undefined) return false; + return true; +} + +export function TaskCreateFromJSON(json: any): TaskCreate { + return TaskCreateFromJSONTyped(json, false); +} + +export function TaskCreateFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskCreate { + if (json == null) { + return json; + } + return { + + 'name': json['name'], + 'parentTaskId': json['parent_task_id'] == null ? undefined : json['parent_task_id'], + 'externalId': json['external_id'] == null ? undefined : json['external_id'], + 'description': json['description'] == null ? undefined : json['description'], + 'descriptionExternal': json['description_external'] == null ? undefined : json['description_external'], + 'bookable': json['bookable'], + 'billable': json['billable'], + 'projectTimeNotesRequired': json['project_time_notes_required'] == null ? undefined : json['project_time_notes_required'], + 'startDate': json['start_date'] == null ? undefined : (new Date(json['start_date'])), + 'endDate': json['end_date'] == null ? undefined : (new Date(json['end_date'])), + 'lockDate': json['lock_date'] == null ? undefined : (new Date(json['lock_date'])), + 'earliestStartTime': json['earliest_start_time'] == null ? undefined : json['earliest_start_time'], + 'latestEndTime': json['latest_end_time'] == null ? undefined : json['latest_end_time'], + 'budgetPlanningType': json['budget_planning_type'] == null ? undefined : BudgetPlanningTypeRequestFromJSON(json['budget_planning_type']), + 'budgetHoursPlanned': json['budget_hours_planned'] == null ? undefined : json['budget_hours_planned'], + 'budgetHourlyRate': json['budget_hourly_rate'] == null ? undefined : json['budget_hourly_rate'], + 'budgetPlanned': json['budget_planned'] == null ? undefined : json['budget_planned'], + 'budgetIncludeNonBillableProjectTimes': json['budget_include_non_billable_project_times'] == null ? undefined : json['budget_include_non_billable_project_times'], + 'locationInherited': json['location_inherited'] == null ? undefined : json['location_inherited'], + 'location': json['location'] == null ? undefined : TaskLocationFromJSON(json['location']), + 'locationRestrictionRadiusMeters': json['location_restriction_radius_meters'] == null ? undefined : json['location_restriction_radius_meters'], + 'customField1': json['custom_field_1'] == null ? undefined : json['custom_field_1'], + 'customField2': json['custom_field_2'] == null ? undefined : json['custom_field_2'], + 'customField3': json['custom_field_3'] == null ? undefined : json['custom_field_3'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function TaskCreateToJSON(json: any): TaskCreate { + return TaskCreateToJSONTyped(json, false); +} + +export function TaskCreateToJSONTyped(value?: TaskCreate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'name': value['name'], + 'parent_task_id': value['parentTaskId'], + 'external_id': value['externalId'], + 'description': value['description'], + 'description_external': value['descriptionExternal'], + 'bookable': value['bookable'], + 'billable': value['billable'], + 'project_time_notes_required': value['projectTimeNotesRequired'], + 'start_date': value['startDate'] == null ? value['startDate'] : value['startDate'].toISOString().substring(0,10), + 'end_date': value['endDate'] == null ? value['endDate'] : value['endDate'].toISOString().substring(0,10), + 'lock_date': value['lockDate'] == null ? value['lockDate'] : value['lockDate'].toISOString().substring(0,10), + 'earliest_start_time': value['earliestStartTime'], + 'latest_end_time': value['latestEndTime'], + 'budget_planning_type': BudgetPlanningTypeRequestToJSON(value['budgetPlanningType']), + 'budget_hours_planned': value['budgetHoursPlanned'], + 'budget_hourly_rate': value['budgetHourlyRate'], + 'budget_planned': value['budgetPlanned'], + 'budget_include_non_billable_project_times': value['budgetIncludeNonBillableProjectTimes'], + 'location_inherited': value['locationInherited'], + 'location': TaskLocationToJSON(value['location']), + 'location_restriction_radius_meters': value['locationRestrictionRadiusMeters'], + 'custom_field_1': value['customField1'], + 'custom_field_2': value['customField2'], + 'custom_field_3': value['customField3'], + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskLocation.ts b/sdk/typescript-fetch/src/models/TaskLocation.ts new file mode 100644 index 0000000..79cc364 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskLocation.ts @@ -0,0 +1,121 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * You can define the location of a task by setting this property. If the task has a parent task, the location is inherited if nothing else is explicitly defined. If you set this property to null, the location will be deleted. + * + * @export + * @interface TaskLocation + */ +export interface TaskLocation { + /** + * Latitude in decimal degrees. + * @type {number} + * @memberof TaskLocation + */ + lat: number | null; + /** + * Longitude in decimal degrees. + * @type {number} + * @memberof TaskLocation + */ + lon: number | null; + /** + * + * @type {string} + * @memberof TaskLocation + */ + address: string | null; + /** + * + * @type {string} + * @memberof TaskLocation + */ + city: string | null; + /** + * + * @type {string} + * @memberof TaskLocation + */ + zipCode: string | null; + /** + * + * @type {string} + * @memberof TaskLocation + */ + state: string | null; + /** + * the country's international country code + * @type {string} + * @memberof TaskLocation + */ + country: string | null; +} + +/** + * Check if a given object implements the TaskLocation interface. + */ +export function instanceOfTaskLocation(value: object): value is TaskLocation { + if (!('lat' in value) || value['lat'] === undefined) return false; + if (!('lon' in value) || value['lon'] === undefined) return false; + if (!('address' in value) || value['address'] === undefined) return false; + if (!('city' in value) || value['city'] === undefined) return false; + if (!('zipCode' in value) || value['zipCode'] === undefined) return false; + if (!('state' in value) || value['state'] === undefined) return false; + if (!('country' in value) || value['country'] === undefined) return false; + return true; +} + +export function TaskLocationFromJSON(json: any): TaskLocation { + return TaskLocationFromJSONTyped(json, false); +} + +export function TaskLocationFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskLocation { + if (json == null) { + return json; + } + return { + + 'lat': json['lat'], + 'lon': json['lon'], + 'address': json['address'], + 'city': json['city'], + 'zipCode': json['zip_code'], + 'state': json['state'], + 'country': json['country'], + }; +} + +export function TaskLocationToJSON(json: any): TaskLocation { + return TaskLocationToJSONTyped(json, false); +} + +export function TaskLocationToJSONTyped(value?: TaskLocation | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'lat': value['lat'], + 'lon': value['lon'], + 'address': value['address'], + 'city': value['city'], + 'zip_code': value['zipCode'], + 'state': value['state'], + 'country': value['country'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskPartial.ts b/sdk/typescript-fetch/src/models/TaskPartial.ts new file mode 100644 index 0000000..b45ae31 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskPartial.ts @@ -0,0 +1,93 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface TaskPartial + */ +export interface TaskPartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof TaskPartial + */ + id: string; + /** + * + * @type {string} + * @memberof TaskPartial + */ + name: string; + /** + * Full path of the entry within its hierarchy, including its own name. + * @type {string} + * @memberof TaskPartial + */ + breadcrumbs: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof TaskPartial + */ + externalId: string | null; +} + +/** + * Check if a given object implements the TaskPartial interface. + */ +export function instanceOfTaskPartial(value: object): value is TaskPartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('breadcrumbs' in value) || value['breadcrumbs'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + return true; +} + +export function TaskPartialFromJSON(json: any): TaskPartial { + return TaskPartialFromJSONTyped(json, false); +} + +export function TaskPartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskPartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'breadcrumbs': json['breadcrumbs'], + 'externalId': json['external_id'], + }; +} + +export function TaskPartialToJSON(json: any): TaskPartial { + return TaskPartialToJSONTyped(json, false); +} + +export function TaskPartialToJSONTyped(value?: TaskPartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'breadcrumbs': value['breadcrumbs'], + 'external_id': value['externalId'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskReduced.ts b/sdk/typescript-fetch/src/models/TaskReduced.ts new file mode 100644 index 0000000..e9c326d --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskReduced.ts @@ -0,0 +1,263 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TaskPartial } from './TaskPartial'; +import { + TaskPartialFromJSON, + TaskPartialFromJSONTyped, + TaskPartialToJSON, + TaskPartialToJSONTyped, +} from './TaskPartial'; +import type { TaskLocation } from './TaskLocation'; +import { + TaskLocationFromJSON, + TaskLocationFromJSONTyped, + TaskLocationToJSON, + TaskLocationToJSONTyped, +} from './TaskLocation'; +import type { BudgetPlanningType } from './BudgetPlanningType'; +import { + BudgetPlanningTypeFromJSON, + BudgetPlanningTypeFromJSONTyped, + BudgetPlanningTypeToJSON, + BudgetPlanningTypeToJSONTyped, +} from './BudgetPlanningType'; + +/** + * + * @export + * @interface TaskReduced + */ +export interface TaskReduced { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof TaskReduced + */ + id: string; + /** + * + * @type {string} + * @memberof TaskReduced + */ + name: string; + /** + * Full path of the entry within its hierarchy, including its own name. + * @type {string} + * @memberof TaskReduced + */ + breadcrumbs: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof TaskReduced + */ + externalId: string | null; + /** + * + * @type {TaskPartial} + * @memberof TaskReduced + */ + parentTask: TaskPartial | null; + /** + * + * @type {string} + * @memberof TaskReduced + */ + description: string | null; + /** + * + * @type {boolean} + * @memberof TaskReduced + */ + bookable: boolean; + /** + * + * @type {boolean} + * @memberof TaskReduced + */ + billable: boolean; + /** + * + * @type {boolean} + * @memberof TaskReduced + */ + projectTimeNotesRequired: boolean; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof TaskReduced + */ + lockDate?: Date | null; + /** + * time of day (ISO-8601) + * @type {string} + * @memberof TaskReduced + */ + earliestStartTime?: string | null; + /** + * time of day (ISO-8601) + * @type {string} + * @memberof TaskReduced + */ + latestEndTime?: string | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof TaskReduced + */ + activeFrom: Date | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof TaskReduced + */ + activeTo: Date | null; + /** + * + * @type {BudgetPlanningType} + * @memberof TaskReduced + */ + budgetPlanningType?: BudgetPlanningType; + /** + * + * @type {boolean} + * @memberof TaskReduced + */ + locationInherited?: boolean; + /** + * + * @type {TaskLocation} + * @memberof TaskReduced + */ + location?: TaskLocation | null; + /** + * + * @type {number} + * @memberof TaskReduced + */ + locationRestrictionRadiusMeters?: number | null; + /** + * + * @type {string} + * @memberof TaskReduced + */ + customField1: string | null; + /** + * + * @type {string} + * @memberof TaskReduced + */ + customField2: string | null; + /** + * + * @type {string} + * @memberof TaskReduced + */ + customField3: string | null; +} + + + +/** + * Check if a given object implements the TaskReduced interface. + */ +export function instanceOfTaskReduced(value: object): value is TaskReduced { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('breadcrumbs' in value) || value['breadcrumbs'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + if (!('parentTask' in value) || value['parentTask'] === undefined) return false; + if (!('description' in value) || value['description'] === undefined) return false; + if (!('bookable' in value) || value['bookable'] === undefined) return false; + if (!('billable' in value) || value['billable'] === undefined) return false; + if (!('projectTimeNotesRequired' in value) || value['projectTimeNotesRequired'] === undefined) return false; + if (!('activeFrom' in value) || value['activeFrom'] === undefined) return false; + if (!('activeTo' in value) || value['activeTo'] === undefined) return false; + if (!('customField1' in value) || value['customField1'] === undefined) return false; + if (!('customField2' in value) || value['customField2'] === undefined) return false; + if (!('customField3' in value) || value['customField3'] === undefined) return false; + return true; +} + +export function TaskReducedFromJSON(json: any): TaskReduced { + return TaskReducedFromJSONTyped(json, false); +} + +export function TaskReducedFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskReduced { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'breadcrumbs': json['breadcrumbs'], + 'externalId': json['external_id'], + 'parentTask': TaskPartialFromJSON(json['parent_task']), + 'description': json['description'], + 'bookable': json['bookable'], + 'billable': json['billable'], + 'projectTimeNotesRequired': json['project_time_notes_required'], + 'lockDate': json['lock_date'] == null ? undefined : (new Date(json['lock_date'])), + 'earliestStartTime': json['earliest_start_time'] == null ? undefined : json['earliest_start_time'], + 'latestEndTime': json['latest_end_time'] == null ? undefined : json['latest_end_time'], + 'activeFrom': (json['active_from'] == null ? null : new Date(json['active_from'])), + 'activeTo': (json['active_to'] == null ? null : new Date(json['active_to'])), + 'budgetPlanningType': json['budget_planning_type'] == null ? undefined : BudgetPlanningTypeFromJSON(json['budget_planning_type']), + 'locationInherited': json['location_inherited'] == null ? undefined : json['location_inherited'], + 'location': json['location'] == null ? undefined : TaskLocationFromJSON(json['location']), + 'locationRestrictionRadiusMeters': json['location_restriction_radius_meters'] == null ? undefined : json['location_restriction_radius_meters'], + 'customField1': json['custom_field_1'], + 'customField2': json['custom_field_2'], + 'customField3': json['custom_field_3'], + }; +} + +export function TaskReducedToJSON(json: any): TaskReduced { + return TaskReducedToJSONTyped(json, false); +} + +export function TaskReducedToJSONTyped(value?: TaskReduced | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'breadcrumbs': value['breadcrumbs'], + 'external_id': value['externalId'], + 'parent_task': TaskPartialToJSON(value['parentTask']), + 'description': value['description'], + 'bookable': value['bookable'], + 'billable': value['billable'], + 'project_time_notes_required': value['projectTimeNotesRequired'], + 'lock_date': value['lockDate'] == null ? value['lockDate'] : value['lockDate'].toISOString().substring(0,10), + 'earliest_start_time': value['earliestStartTime'], + 'latest_end_time': value['latestEndTime'], + 'active_from': value['activeFrom'] == null ? value['activeFrom'] : value['activeFrom'].toISOString().substring(0,10), + 'active_to': value['activeTo'] == null ? value['activeTo'] : value['activeTo'].toISOString().substring(0,10), + 'budget_planning_type': BudgetPlanningTypeToJSON(value['budgetPlanningType']), + 'location_inherited': value['locationInherited'], + 'location': TaskLocationToJSON(value['location']), + 'location_restriction_radius_meters': value['locationRestrictionRadiusMeters'], + 'custom_field_1': value['customField1'], + 'custom_field_2': value['customField2'], + 'custom_field_3': value['customField3'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToLeaderAssignment.ts b/sdk/typescript-fetch/src/models/TaskToLeaderAssignment.ts new file mode 100644 index 0000000..55cc6ca --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToLeaderAssignment.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; + +/** + * + * @export + * @interface TaskToLeaderAssignment + */ +export interface TaskToLeaderAssignment { + /** + * + * @type {UserPartial} + * @memberof TaskToLeaderAssignment + */ + user: UserPartial; + /** + * + * @type {boolean} + * @memberof TaskToLeaderAssignment + */ + automaticallyAssigned: boolean; +} + +/** + * Check if a given object implements the TaskToLeaderAssignment interface. + */ +export function instanceOfTaskToLeaderAssignment(value: object): value is TaskToLeaderAssignment { + if (!('user' in value) || value['user'] === undefined) return false; + if (!('automaticallyAssigned' in value) || value['automaticallyAssigned'] === undefined) return false; + return true; +} + +export function TaskToLeaderAssignmentFromJSON(json: any): TaskToLeaderAssignment { + return TaskToLeaderAssignmentFromJSONTyped(json, false); +} + +export function TaskToLeaderAssignmentFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToLeaderAssignment { + if (json == null) { + return json; + } + return { + + 'user': UserPartialFromJSON(json['user']), + 'automaticallyAssigned': json['automatically_assigned'], + }; +} + +export function TaskToLeaderAssignmentToJSON(json: any): TaskToLeaderAssignment { + return TaskToLeaderAssignmentToJSONTyped(json, false); +} + +export function TaskToLeaderAssignmentToJSONTyped(value?: TaskToLeaderAssignment | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'user': UserPartialToJSON(value['user']), + 'automatically_assigned': value['automaticallyAssigned'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToLeaderAssignmentsPage.ts b/sdk/typescript-fetch/src/models/TaskToLeaderAssignmentsPage.ts new file mode 100644 index 0000000..f3acf80 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToLeaderAssignmentsPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TaskToLeaderAssignment } from './TaskToLeaderAssignment'; +import { + TaskToLeaderAssignmentFromJSON, + TaskToLeaderAssignmentFromJSONTyped, + TaskToLeaderAssignmentToJSON, + TaskToLeaderAssignmentToJSONTyped, +} from './TaskToLeaderAssignment'; + +/** + * + * @export + * @interface TaskToLeaderAssignmentsPage + */ +export interface TaskToLeaderAssignmentsPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof TaskToLeaderAssignmentsPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof TaskToLeaderAssignmentsPage + */ + data: Array; +} + +/** + * Check if a given object implements the TaskToLeaderAssignmentsPage interface. + */ +export function instanceOfTaskToLeaderAssignmentsPage(value: object): value is TaskToLeaderAssignmentsPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function TaskToLeaderAssignmentsPageFromJSON(json: any): TaskToLeaderAssignmentsPage { + return TaskToLeaderAssignmentsPageFromJSONTyped(json, false); +} + +export function TaskToLeaderAssignmentsPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToLeaderAssignmentsPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(TaskToLeaderAssignmentFromJSON)), + }; +} + +export function TaskToLeaderAssignmentsPageToJSON(json: any): TaskToLeaderAssignmentsPage { + return TaskToLeaderAssignmentsPageToJSONTyped(json, false); +} + +export function TaskToLeaderAssignmentsPageToJSONTyped(value?: TaskToLeaderAssignmentsPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(TaskToLeaderAssignmentToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToLeaderAssignmentsSortColumn.ts b/sdk/typescript-fetch/src/models/TaskToLeaderAssignmentsSortColumn.ts new file mode 100644 index 0000000..9e21a3e --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToLeaderAssignmentsSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Task to Leader Assignments. `user_name` orders by the assigned User's last name, then first name. + * @export + */ +export const TaskToLeaderAssignmentsSortColumn = { + UserName: 'user_name' +} as const; +export type TaskToLeaderAssignmentsSortColumn = typeof TaskToLeaderAssignmentsSortColumn[keyof typeof TaskToLeaderAssignmentsSortColumn]; + + +export function instanceOfTaskToLeaderAssignmentsSortColumn(value: any): boolean { + for (const key in TaskToLeaderAssignmentsSortColumn) { + if (Object.prototype.hasOwnProperty.call(TaskToLeaderAssignmentsSortColumn, key)) { + if (TaskToLeaderAssignmentsSortColumn[key as keyof typeof TaskToLeaderAssignmentsSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function TaskToLeaderAssignmentsSortColumnFromJSON(json: any): TaskToLeaderAssignmentsSortColumn { + return TaskToLeaderAssignmentsSortColumnFromJSONTyped(json, false); +} + +export function TaskToLeaderAssignmentsSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToLeaderAssignmentsSortColumn { + return json as TaskToLeaderAssignmentsSortColumn; +} + +export function TaskToLeaderAssignmentsSortColumnToJSON(value?: TaskToLeaderAssignmentsSortColumn | null): any { + return value as any; +} + +export function TaskToLeaderAssignmentsSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): TaskToLeaderAssignmentsSortColumn { + return value as TaskToLeaderAssignmentsSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToTeamAssignment.ts b/sdk/typescript-fetch/src/models/TaskToTeamAssignment.ts new file mode 100644 index 0000000..600f07c --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToTeamAssignment.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TeamPartial } from './TeamPartial'; +import { + TeamPartialFromJSON, + TeamPartialFromJSONTyped, + TeamPartialToJSON, + TeamPartialToJSONTyped, +} from './TeamPartial'; + +/** + * + * @export + * @interface TaskToTeamAssignment + */ +export interface TaskToTeamAssignment { + /** + * + * @type {TeamPartial} + * @memberof TaskToTeamAssignment + */ + team: TeamPartial; + /** + * + * @type {boolean} + * @memberof TaskToTeamAssignment + */ + automaticallyAssigned: boolean; +} + +/** + * Check if a given object implements the TaskToTeamAssignment interface. + */ +export function instanceOfTaskToTeamAssignment(value: object): value is TaskToTeamAssignment { + if (!('team' in value) || value['team'] === undefined) return false; + if (!('automaticallyAssigned' in value) || value['automaticallyAssigned'] === undefined) return false; + return true; +} + +export function TaskToTeamAssignmentFromJSON(json: any): TaskToTeamAssignment { + return TaskToTeamAssignmentFromJSONTyped(json, false); +} + +export function TaskToTeamAssignmentFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToTeamAssignment { + if (json == null) { + return json; + } + return { + + 'team': TeamPartialFromJSON(json['team']), + 'automaticallyAssigned': json['automatically_assigned'], + }; +} + +export function TaskToTeamAssignmentToJSON(json: any): TaskToTeamAssignment { + return TaskToTeamAssignmentToJSONTyped(json, false); +} + +export function TaskToTeamAssignmentToJSONTyped(value?: TaskToTeamAssignment | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'team': TeamPartialToJSON(value['team']), + 'automatically_assigned': value['automaticallyAssigned'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToTeamAssignmentsPage.ts b/sdk/typescript-fetch/src/models/TaskToTeamAssignmentsPage.ts new file mode 100644 index 0000000..8682558 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToTeamAssignmentsPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TaskToTeamAssignment } from './TaskToTeamAssignment'; +import { + TaskToTeamAssignmentFromJSON, + TaskToTeamAssignmentFromJSONTyped, + TaskToTeamAssignmentToJSON, + TaskToTeamAssignmentToJSONTyped, +} from './TaskToTeamAssignment'; + +/** + * + * @export + * @interface TaskToTeamAssignmentsPage + */ +export interface TaskToTeamAssignmentsPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof TaskToTeamAssignmentsPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof TaskToTeamAssignmentsPage + */ + data: Array; +} + +/** + * Check if a given object implements the TaskToTeamAssignmentsPage interface. + */ +export function instanceOfTaskToTeamAssignmentsPage(value: object): value is TaskToTeamAssignmentsPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function TaskToTeamAssignmentsPageFromJSON(json: any): TaskToTeamAssignmentsPage { + return TaskToTeamAssignmentsPageFromJSONTyped(json, false); +} + +export function TaskToTeamAssignmentsPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToTeamAssignmentsPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(TaskToTeamAssignmentFromJSON)), + }; +} + +export function TaskToTeamAssignmentsPageToJSON(json: any): TaskToTeamAssignmentsPage { + return TaskToTeamAssignmentsPageToJSONTyped(json, false); +} + +export function TaskToTeamAssignmentsPageToJSONTyped(value?: TaskToTeamAssignmentsPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(TaskToTeamAssignmentToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToTeamAssignmentsSortColumn.ts b/sdk/typescript-fetch/src/models/TaskToTeamAssignmentsSortColumn.ts new file mode 100644 index 0000000..5b7d8dc --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToTeamAssignmentsSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Task to Team Assignments. `team_name` orders by the assigned Team's name. + * @export + */ +export const TaskToTeamAssignmentsSortColumn = { + TeamName: 'team_name' +} as const; +export type TaskToTeamAssignmentsSortColumn = typeof TaskToTeamAssignmentsSortColumn[keyof typeof TaskToTeamAssignmentsSortColumn]; + + +export function instanceOfTaskToTeamAssignmentsSortColumn(value: any): boolean { + for (const key in TaskToTeamAssignmentsSortColumn) { + if (Object.prototype.hasOwnProperty.call(TaskToTeamAssignmentsSortColumn, key)) { + if (TaskToTeamAssignmentsSortColumn[key as keyof typeof TaskToTeamAssignmentsSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function TaskToTeamAssignmentsSortColumnFromJSON(json: any): TaskToTeamAssignmentsSortColumn { + return TaskToTeamAssignmentsSortColumnFromJSONTyped(json, false); +} + +export function TaskToTeamAssignmentsSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToTeamAssignmentsSortColumn { + return json as TaskToTeamAssignmentsSortColumn; +} + +export function TaskToTeamAssignmentsSortColumnToJSON(value?: TaskToTeamAssignmentsSortColumn | null): any { + return value as any; +} + +export function TaskToTeamAssignmentsSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): TaskToTeamAssignmentsSortColumn { + return value as TaskToTeamAssignmentsSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToUserAssignment.ts b/sdk/typescript-fetch/src/models/TaskToUserAssignment.ts new file mode 100644 index 0000000..33e9574 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToUserAssignment.ts @@ -0,0 +1,109 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { RecordingLockType } from './RecordingLockType'; +import { + RecordingLockTypeFromJSON, + RecordingLockTypeFromJSONTyped, + RecordingLockTypeToJSON, + RecordingLockTypeToJSONTyped, +} from './RecordingLockType'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; + +/** + * + * @export + * @interface TaskToUserAssignment + */ +export interface TaskToUserAssignment { + /** + * + * @type {UserPartial} + * @memberof TaskToUserAssignment + */ + user: UserPartial; + /** + * + * @type {number} + * @memberof TaskToUserAssignment + */ + hoursPlanned?: number | null; + /** + * + * @type {RecordingLockType} + * @memberof TaskToUserAssignment + */ + recordingLock: RecordingLockType; + /** + * + * @type {boolean} + * @memberof TaskToUserAssignment + */ + automaticallyAssigned: boolean; +} + + + +/** + * Check if a given object implements the TaskToUserAssignment interface. + */ +export function instanceOfTaskToUserAssignment(value: object): value is TaskToUserAssignment { + if (!('user' in value) || value['user'] === undefined) return false; + if (!('recordingLock' in value) || value['recordingLock'] === undefined) return false; + if (!('automaticallyAssigned' in value) || value['automaticallyAssigned'] === undefined) return false; + return true; +} + +export function TaskToUserAssignmentFromJSON(json: any): TaskToUserAssignment { + return TaskToUserAssignmentFromJSONTyped(json, false); +} + +export function TaskToUserAssignmentFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToUserAssignment { + if (json == null) { + return json; + } + return { + + 'user': UserPartialFromJSON(json['user']), + 'hoursPlanned': json['hours_planned'] == null ? undefined : json['hours_planned'], + 'recordingLock': RecordingLockTypeFromJSON(json['recording_lock']), + 'automaticallyAssigned': json['automatically_assigned'], + }; +} + +export function TaskToUserAssignmentToJSON(json: any): TaskToUserAssignment { + return TaskToUserAssignmentToJSONTyped(json, false); +} + +export function TaskToUserAssignmentToJSONTyped(value?: TaskToUserAssignment | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'user': UserPartialToJSON(value['user']), + 'hours_planned': value['hoursPlanned'], + 'recording_lock': RecordingLockTypeToJSON(value['recordingLock']), + 'automatically_assigned': value['automaticallyAssigned'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToUserAssignmentUpsert.ts b/sdk/typescript-fetch/src/models/TaskToUserAssignmentUpsert.ts new file mode 100644 index 0000000..7bcdf28 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToUserAssignmentUpsert.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { RecordingLockType } from './RecordingLockType'; +import { + RecordingLockTypeFromJSON, + RecordingLockTypeFromJSONTyped, + RecordingLockTypeToJSON, + RecordingLockTypeToJSONTyped, +} from './RecordingLockType'; + +/** + * + * @export + * @interface TaskToUserAssignmentUpsert + */ +export interface TaskToUserAssignmentUpsert { + /** + * + * @type {number} + * @memberof TaskToUserAssignmentUpsert + */ + hoursPlanned?: number | null; + /** + * + * @type {RecordingLockType} + * @memberof TaskToUserAssignmentUpsert + */ + recordingLock?: RecordingLockType | null; +} + + + +/** + * Check if a given object implements the TaskToUserAssignmentUpsert interface. + */ +export function instanceOfTaskToUserAssignmentUpsert(value: object): value is TaskToUserAssignmentUpsert { + return true; +} + +export function TaskToUserAssignmentUpsertFromJSON(json: any): TaskToUserAssignmentUpsert { + return TaskToUserAssignmentUpsertFromJSONTyped(json, false); +} + +export function TaskToUserAssignmentUpsertFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToUserAssignmentUpsert { + if (json == null) { + return json; + } + return { + + 'hoursPlanned': json['hours_planned'] == null ? undefined : json['hours_planned'], + 'recordingLock': json['recording_lock'] == null ? undefined : RecordingLockTypeFromJSON(json['recording_lock']), + }; +} + +export function TaskToUserAssignmentUpsertToJSON(json: any): TaskToUserAssignmentUpsert { + return TaskToUserAssignmentUpsertToJSONTyped(json, false); +} + +export function TaskToUserAssignmentUpsertToJSONTyped(value?: TaskToUserAssignmentUpsert | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'hours_planned': value['hoursPlanned'], + 'recording_lock': RecordingLockTypeToJSON(value['recordingLock']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToUserAssignmentsPage.ts b/sdk/typescript-fetch/src/models/TaskToUserAssignmentsPage.ts new file mode 100644 index 0000000..766f8d6 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToUserAssignmentsPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TaskToUserAssignment } from './TaskToUserAssignment'; +import { + TaskToUserAssignmentFromJSON, + TaskToUserAssignmentFromJSONTyped, + TaskToUserAssignmentToJSON, + TaskToUserAssignmentToJSONTyped, +} from './TaskToUserAssignment'; + +/** + * + * @export + * @interface TaskToUserAssignmentsPage + */ +export interface TaskToUserAssignmentsPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof TaskToUserAssignmentsPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof TaskToUserAssignmentsPage + */ + data: Array; +} + +/** + * Check if a given object implements the TaskToUserAssignmentsPage interface. + */ +export function instanceOfTaskToUserAssignmentsPage(value: object): value is TaskToUserAssignmentsPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function TaskToUserAssignmentsPageFromJSON(json: any): TaskToUserAssignmentsPage { + return TaskToUserAssignmentsPageFromJSONTyped(json, false); +} + +export function TaskToUserAssignmentsPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToUserAssignmentsPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(TaskToUserAssignmentFromJSON)), + }; +} + +export function TaskToUserAssignmentsPageToJSON(json: any): TaskToUserAssignmentsPage { + return TaskToUserAssignmentsPageToJSONTyped(json, false); +} + +export function TaskToUserAssignmentsPageToJSONTyped(value?: TaskToUserAssignmentsPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(TaskToUserAssignmentToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/TaskToUserAssignmentsSortColumn.ts b/sdk/typescript-fetch/src/models/TaskToUserAssignmentsSortColumn.ts new file mode 100644 index 0000000..3cd9dc8 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskToUserAssignmentsSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Task to User Assignments. `user_name` orders by the assigned User's last name, then first name. + * @export + */ +export const TaskToUserAssignmentsSortColumn = { + UserName: 'user_name' +} as const; +export type TaskToUserAssignmentsSortColumn = typeof TaskToUserAssignmentsSortColumn[keyof typeof TaskToUserAssignmentsSortColumn]; + + +export function instanceOfTaskToUserAssignmentsSortColumn(value: any): boolean { + for (const key in TaskToUserAssignmentsSortColumn) { + if (Object.prototype.hasOwnProperty.call(TaskToUserAssignmentsSortColumn, key)) { + if (TaskToUserAssignmentsSortColumn[key as keyof typeof TaskToUserAssignmentsSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function TaskToUserAssignmentsSortColumnFromJSON(json: any): TaskToUserAssignmentsSortColumn { + return TaskToUserAssignmentsSortColumnFromJSONTyped(json, false); +} + +export function TaskToUserAssignmentsSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskToUserAssignmentsSortColumn { + return json as TaskToUserAssignmentsSortColumn; +} + +export function TaskToUserAssignmentsSortColumnToJSON(value?: TaskToUserAssignmentsSortColumn | null): any { + return value as any; +} + +export function TaskToUserAssignmentsSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): TaskToUserAssignmentsSortColumn { + return value as TaskToUserAssignmentsSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/TaskUpdate.ts b/sdk/typescript-fetch/src/models/TaskUpdate.ts new file mode 100644 index 0000000..3804b7c --- /dev/null +++ b/sdk/typescript-fetch/src/models/TaskUpdate.ts @@ -0,0 +1,302 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { BudgetPlanningTypeRequest } from './BudgetPlanningTypeRequest'; +import { + BudgetPlanningTypeRequestFromJSON, + BudgetPlanningTypeRequestFromJSONTyped, + BudgetPlanningTypeRequestToJSON, + BudgetPlanningTypeRequestToJSONTyped, +} from './BudgetPlanningTypeRequest'; +import type { TaskLocation } from './TaskLocation'; +import { + TaskLocationFromJSON, + TaskLocationFromJSONTyped, + TaskLocationToJSON, + TaskLocationToJSONTyped, +} from './TaskLocation'; + +/** + * + * @export + * @interface TaskUpdate + */ +export interface TaskUpdate { + /** + * + * @type {string} + * @memberof TaskUpdate + */ + name?: string; + /** + * returns the id of the immediate parent task if the task has one. Use this id when creating or a updating a task in order to locate it at the right place in your task tree. + * @type {string} + * @memberof TaskUpdate + */ + parentTaskId?: string | null; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof TaskUpdate + */ + externalId?: string | null; + /** + * + * @type {string} + * @memberof TaskUpdate + */ + description?: string | null; + /** + * + * @type {string} + * @memberof TaskUpdate + */ + descriptionExternal?: string | null; + /** + * when a task is not bookable, no project times can be booked on it. You need to define child tasks, to book on tasks related to this task. + * @type {boolean} + * @memberof TaskUpdate + */ + bookable?: boolean; + /** + * + * @type {boolean} + * @memberof TaskUpdate + */ + billable?: boolean; + /** + * depending on this property project times booked on this task have to include notes or not + * @type {boolean} + * @memberof TaskUpdate + */ + projectTimeNotesRequired?: boolean; + /** + * the task is only available for selection after start_date, however, it can change if a lock_date is set and this is after the start_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @type {Date} + * @memberof TaskUpdate + */ + startDate?: Date | null; + /** + * the task is only available for selection before end_date, however, it can change if a lock_date is set and this is before the end_date. Furthermore, no booking of a project time with date < start or > end is possible. + * @type {Date} + * @memberof TaskUpdate + */ + endDate?: Date | null; + /** + * with lock_date property you define a point in time before which existing entries can no longer be changed. This way you ensure that + * + * * existing entries cannot be changed or deleted + * * no entries can be added later + * + * @type {Date} + * @memberof TaskUpdate + */ + lockDate?: Date | null; + /** + * set this property to limit the task so that it cannot be booked before this time + * @type {string} + * @memberof TaskUpdate + */ + earliestStartTime?: string | null; + /** + * set this property to limit the task so that it cannot be booked after this time + * @type {string} + * @memberof TaskUpdate + */ + latestEndTime?: string | null; + /** + * when no budget is planned, either don't set this property (on create) or set it to none. set it to inherited to inherit budget settings from parent task. + * + * @type {BudgetPlanningTypeRequest} + * @memberof TaskUpdate + */ + budgetPlanningType?: BudgetPlanningTypeRequest; + /** + * how many hours were planned in the calculation + * set budget_hours_planned to make timr calculate budget_planned depending on its budget_planning_type: + * * task_hourly_rate: out of budget_hourly_rate and budget_planned + * * user_hourly_rate: out of fixed hours budget (employee budget) and budget_hours_planned + * * fixed_price: out of budget_hourly_rate and budget_planned + * + * @type {number} + * @memberof TaskUpdate + */ + budgetHoursPlanned?: number | null; + /** + * depending on its budget_planning_type this property may or may not be set: + * * **task_hourly_rate: this property is necessary to calculate budgets, by default it will be set to 0.00** + * * **user_hourly_rate: this property cannot be set** + * * fixed_price: you can set this property if you want to make timr calculate budget_hours_planned or budget_planned based on its value + * + * @type {number} + * @memberof TaskUpdate + */ + budgetHourlyRate?: number | null; + /** + * the price at which the task was sold + * set budget_planned to make timr calculate the budget_hours_planned depending on its budget_planning_type: + * * task_hourly_rate: out of budget_hourly_rate and budget_planned + * * user_hourly_rate: out of fixed hours budget (employee budget) and budget_planned + * * fixed_price: out of budget_hourly_rate and budget_planned + * + * @type {number} + * @memberof TaskUpdate + */ + budgetPlanned?: number | null; + /** + * set this property to true, if you want to include not billable hours for all project times booked on this task + * @type {boolean} + * @memberof TaskUpdate + */ + budgetIncludeNonBillableProjectTimes?: boolean; + /** + * set this property to false if you want to set a child task's location explicitly instead of inheriting it from its parent + * @type {boolean} + * @memberof TaskUpdate + */ + locationInherited?: boolean; + /** + * + * @type {TaskLocation} + * @memberof TaskUpdate + */ + location?: TaskLocation | null; + /** + * set this property to make recording of project times for this task via the app on the smartphone only possible within this defined geofence radius + * @type {number} + * @memberof TaskUpdate + */ + locationRestrictionRadiusMeters?: number | null; + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @type {string} + * @memberof TaskUpdate + */ + customField1?: string | null; + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @type {string} + * @memberof TaskUpdate + */ + customField2?: string | null; + /** + * you can configure custom fields for tasks in the settings of timr under Administration/Settings/Tasks. To add a new custom field, simply choose a name for the field. + * @type {string} + * @memberof TaskUpdate + */ + customField3?: string | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof TaskUpdate + */ + metadata?: { [key: string]: any; } | null; + /** + * this property is used to decide whether existing project times that have been booked to this task should be updated with the changed budget. If budget_planning type or budget_hourly_rate are set, this property must also be set. Based on this, the budgets of the existing project times are then recalculated or not. + * + * @type {boolean} + * @memberof TaskUpdate + */ + budgetUpdateProjectTimes?: boolean; +} + + + +/** + * Check if a given object implements the TaskUpdate interface. + */ +export function instanceOfTaskUpdate(value: object): value is TaskUpdate { + return true; +} + +export function TaskUpdateFromJSON(json: any): TaskUpdate { + return TaskUpdateFromJSONTyped(json, false); +} + +export function TaskUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): TaskUpdate { + if (json == null) { + return json; + } + return { + + 'name': json['name'] == null ? undefined : json['name'], + 'parentTaskId': json['parent_task_id'] == null ? undefined : json['parent_task_id'], + 'externalId': json['external_id'] == null ? undefined : json['external_id'], + 'description': json['description'] == null ? undefined : json['description'], + 'descriptionExternal': json['description_external'] == null ? undefined : json['description_external'], + 'bookable': json['bookable'] == null ? undefined : json['bookable'], + 'billable': json['billable'] == null ? undefined : json['billable'], + 'projectTimeNotesRequired': json['project_time_notes_required'] == null ? undefined : json['project_time_notes_required'], + 'startDate': json['start_date'] == null ? undefined : (new Date(json['start_date'])), + 'endDate': json['end_date'] == null ? undefined : (new Date(json['end_date'])), + 'lockDate': json['lock_date'] == null ? undefined : (new Date(json['lock_date'])), + 'earliestStartTime': json['earliest_start_time'] == null ? undefined : json['earliest_start_time'], + 'latestEndTime': json['latest_end_time'] == null ? undefined : json['latest_end_time'], + 'budgetPlanningType': json['budget_planning_type'] == null ? undefined : BudgetPlanningTypeRequestFromJSON(json['budget_planning_type']), + 'budgetHoursPlanned': json['budget_hours_planned'] == null ? undefined : json['budget_hours_planned'], + 'budgetHourlyRate': json['budget_hourly_rate'] == null ? undefined : json['budget_hourly_rate'], + 'budgetPlanned': json['budget_planned'] == null ? undefined : json['budget_planned'], + 'budgetIncludeNonBillableProjectTimes': json['budget_include_non_billable_project_times'] == null ? undefined : json['budget_include_non_billable_project_times'], + 'locationInherited': json['location_inherited'] == null ? undefined : json['location_inherited'], + 'location': json['location'] == null ? undefined : TaskLocationFromJSON(json['location']), + 'locationRestrictionRadiusMeters': json['location_restriction_radius_meters'] == null ? undefined : json['location_restriction_radius_meters'], + 'customField1': json['custom_field_1'] == null ? undefined : json['custom_field_1'], + 'customField2': json['custom_field_2'] == null ? undefined : json['custom_field_2'], + 'customField3': json['custom_field_3'] == null ? undefined : json['custom_field_3'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + 'budgetUpdateProjectTimes': json['budget_update_project_times'] == null ? undefined : json['budget_update_project_times'], + }; +} + +export function TaskUpdateToJSON(json: any): TaskUpdate { + return TaskUpdateToJSONTyped(json, false); +} + +export function TaskUpdateToJSONTyped(value?: TaskUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'name': value['name'], + 'parent_task_id': value['parentTaskId'], + 'external_id': value['externalId'], + 'description': value['description'], + 'description_external': value['descriptionExternal'], + 'bookable': value['bookable'], + 'billable': value['billable'], + 'project_time_notes_required': value['projectTimeNotesRequired'], + 'start_date': value['startDate'] == null ? value['startDate'] : value['startDate'].toISOString().substring(0,10), + 'end_date': value['endDate'] == null ? value['endDate'] : value['endDate'].toISOString().substring(0,10), + 'lock_date': value['lockDate'] == null ? value['lockDate'] : value['lockDate'].toISOString().substring(0,10), + 'earliest_start_time': value['earliestStartTime'], + 'latest_end_time': value['latestEndTime'], + 'budget_planning_type': BudgetPlanningTypeRequestToJSON(value['budgetPlanningType']), + 'budget_hours_planned': value['budgetHoursPlanned'], + 'budget_hourly_rate': value['budgetHourlyRate'], + 'budget_planned': value['budgetPlanned'], + 'budget_include_non_billable_project_times': value['budgetIncludeNonBillableProjectTimes'], + 'location_inherited': value['locationInherited'], + 'location': TaskLocationToJSON(value['location']), + 'location_restriction_radius_meters': value['locationRestrictionRadiusMeters'], + 'custom_field_1': value['customField1'], + 'custom_field_2': value['customField2'], + 'custom_field_3': value['customField3'], + 'metadata': value['metadata'], + 'budget_update_project_times': value['budgetUpdateProjectTimes'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TasksPage.ts b/sdk/typescript-fetch/src/models/TasksPage.ts new file mode 100644 index 0000000..b0862a0 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TasksPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { Task } from './Task'; +import { + TaskFromJSON, + TaskFromJSONTyped, + TaskToJSON, + TaskToJSONTyped, +} from './Task'; + +/** + * + * @export + * @interface TasksPage + */ +export interface TasksPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof TasksPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof TasksPage + */ + data: Array; +} + +/** + * Check if a given object implements the TasksPage interface. + */ +export function instanceOfTasksPage(value: object): value is TasksPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function TasksPageFromJSON(json: any): TasksPage { + return TasksPageFromJSONTyped(json, false); +} + +export function TasksPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): TasksPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(TaskFromJSON)), + }; +} + +export function TasksPageToJSON(json: any): TasksPage { + return TasksPageToJSONTyped(json, false); +} + +export function TasksPageToJSONTyped(value?: TasksPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(TaskToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/TasksReducedPage.ts b/sdk/typescript-fetch/src/models/TasksReducedPage.ts new file mode 100644 index 0000000..f743552 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TasksReducedPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TaskReduced } from './TaskReduced'; +import { + TaskReducedFromJSON, + TaskReducedFromJSONTyped, + TaskReducedToJSON, + TaskReducedToJSONTyped, +} from './TaskReduced'; + +/** + * + * @export + * @interface TasksReducedPage + */ +export interface TasksReducedPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof TasksReducedPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof TasksReducedPage + */ + data: Array; +} + +/** + * Check if a given object implements the TasksReducedPage interface. + */ +export function instanceOfTasksReducedPage(value: object): value is TasksReducedPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function TasksReducedPageFromJSON(json: any): TasksReducedPage { + return TasksReducedPageFromJSONTyped(json, false); +} + +export function TasksReducedPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): TasksReducedPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(TaskReducedFromJSON)), + }; +} + +export function TasksReducedPageToJSON(json: any): TasksReducedPage { + return TasksReducedPageToJSONTyped(json, false); +} + +export function TasksReducedPageToJSONTyped(value?: TasksReducedPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(TaskReducedToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/TasksSortColumn.ts b/sdk/typescript-fetch/src/models/TasksSortColumn.ts new file mode 100644 index 0000000..f38798e --- /dev/null +++ b/sdk/typescript-fetch/src/models/TasksSortColumn.ts @@ -0,0 +1,53 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Tasks. `breadcrumbs` orders by the Task's full path, `name` by its own name only. + * @export + */ +export const TasksSortColumn = { + Breadcrumbs: 'breadcrumbs', + Name: 'name' +} as const; +export type TasksSortColumn = typeof TasksSortColumn[keyof typeof TasksSortColumn]; + + +export function instanceOfTasksSortColumn(value: any): boolean { + for (const key in TasksSortColumn) { + if (Object.prototype.hasOwnProperty.call(TasksSortColumn, key)) { + if (TasksSortColumn[key as keyof typeof TasksSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function TasksSortColumnFromJSON(json: any): TasksSortColumn { + return TasksSortColumnFromJSONTyped(json, false); +} + +export function TasksSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): TasksSortColumn { + return json as TasksSortColumn; +} + +export function TasksSortColumnToJSON(value?: TasksSortColumn | null): any { + return value as any; +} + +export function TasksSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): TasksSortColumn { + return value as TasksSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/Team.ts b/sdk/typescript-fetch/src/models/Team.ts new file mode 100644 index 0000000..8b2a771 --- /dev/null +++ b/sdk/typescript-fetch/src/models/Team.ts @@ -0,0 +1,120 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TeamPartial } from './TeamPartial'; +import { + TeamPartialFromJSON, + TeamPartialFromJSONTyped, + TeamPartialToJSON, + TeamPartialToJSONTyped, +} from './TeamPartial'; + +/** + * A team, placed in the hierarchy by `parent_team`, with the full path from the root in `breadcrumbs`. + * + * @export + * @interface Team + */ +export interface Team { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof Team + */ + id: string; + /** + * + * @type {string} + * @memberof Team + */ + name: string; + /** + * Full path of the entry within its hierarchy, including its own name. + * @type {string} + * @memberof Team + */ + breadcrumbs: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof Team + */ + externalId: string | null; + /** + * + * @type {string} + * @memberof Team + */ + description: string | null; + /** + * + * @type {TeamPartial} + * @memberof Team + */ + parentTeam: TeamPartial | null; +} + +/** + * Check if a given object implements the Team interface. + */ +export function instanceOfTeam(value: object): value is Team { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('breadcrumbs' in value) || value['breadcrumbs'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + if (!('description' in value) || value['description'] === undefined) return false; + if (!('parentTeam' in value) || value['parentTeam'] === undefined) return false; + return true; +} + +export function TeamFromJSON(json: any): Team { + return TeamFromJSONTyped(json, false); +} + +export function TeamFromJSONTyped(json: any, ignoreDiscriminator: boolean): Team { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'breadcrumbs': json['breadcrumbs'], + 'externalId': json['external_id'], + 'description': json['description'], + 'parentTeam': TeamPartialFromJSON(json['parent_team']), + }; +} + +export function TeamToJSON(json: any): Team { + return TeamToJSONTyped(json, false); +} + +export function TeamToJSONTyped(value?: Team | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'breadcrumbs': value['breadcrumbs'], + 'external_id': value['externalId'], + 'description': value['description'], + 'parent_team': TeamPartialToJSON(value['parentTeam']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/TeamCreate.ts b/sdk/typescript-fetch/src/models/TeamCreate.ts new file mode 100644 index 0000000..670f91c --- /dev/null +++ b/sdk/typescript-fetch/src/models/TeamCreate.ts @@ -0,0 +1,90 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface TeamCreate + */ +export interface TeamCreate { + /** + * + * @type {string} + * @memberof TeamCreate + */ + name: string; + /** + * + * @type {string} + * @memberof TeamCreate + */ + description?: string | null; + /** + * + * @type {string} + * @memberof TeamCreate + */ + parentTeamId?: string | null; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof TeamCreate + */ + externalId?: string | null; +} + +/** + * Check if a given object implements the TeamCreate interface. + */ +export function instanceOfTeamCreate(value: object): value is TeamCreate { + if (!('name' in value) || value['name'] === undefined) return false; + return true; +} + +export function TeamCreateFromJSON(json: any): TeamCreate { + return TeamCreateFromJSONTyped(json, false); +} + +export function TeamCreateFromJSONTyped(json: any, ignoreDiscriminator: boolean): TeamCreate { + if (json == null) { + return json; + } + return { + + 'name': json['name'], + 'description': json['description'] == null ? undefined : json['description'], + 'parentTeamId': json['parent_team_id'] == null ? undefined : json['parent_team_id'], + 'externalId': json['external_id'] == null ? undefined : json['external_id'], + }; +} + +export function TeamCreateToJSON(json: any): TeamCreate { + return TeamCreateToJSONTyped(json, false); +} + +export function TeamCreateToJSONTyped(value?: TeamCreate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'name': value['name'], + 'description': value['description'], + 'parent_team_id': value['parentTeamId'], + 'external_id': value['externalId'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TeamPartial.ts b/sdk/typescript-fetch/src/models/TeamPartial.ts new file mode 100644 index 0000000..61a8c2d --- /dev/null +++ b/sdk/typescript-fetch/src/models/TeamPartial.ts @@ -0,0 +1,93 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface TeamPartial + */ +export interface TeamPartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof TeamPartial + */ + id: string; + /** + * + * @type {string} + * @memberof TeamPartial + */ + name: string; + /** + * Full path of the entry within its hierarchy, including its own name. + * @type {string} + * @memberof TeamPartial + */ + breadcrumbs: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof TeamPartial + */ + externalId: string | null; +} + +/** + * Check if a given object implements the TeamPartial interface. + */ +export function instanceOfTeamPartial(value: object): value is TeamPartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('breadcrumbs' in value) || value['breadcrumbs'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + return true; +} + +export function TeamPartialFromJSON(json: any): TeamPartial { + return TeamPartialFromJSONTyped(json, false); +} + +export function TeamPartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): TeamPartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'breadcrumbs': json['breadcrumbs'], + 'externalId': json['external_id'], + }; +} + +export function TeamPartialToJSON(json: any): TeamPartial { + return TeamPartialToJSONTyped(json, false); +} + +export function TeamPartialToJSONTyped(value?: TeamPartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'breadcrumbs': value['breadcrumbs'], + 'external_id': value['externalId'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TeamUpdate.ts b/sdk/typescript-fetch/src/models/TeamUpdate.ts new file mode 100644 index 0000000..c5a2628 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TeamUpdate.ts @@ -0,0 +1,89 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface TeamUpdate + */ +export interface TeamUpdate { + /** + * + * @type {string} + * @memberof TeamUpdate + */ + name?: string; + /** + * + * @type {string} + * @memberof TeamUpdate + */ + description?: string | null; + /** + * + * @type {string} + * @memberof TeamUpdate + */ + parentTeamId?: string | null; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof TeamUpdate + */ + externalId?: string | null; +} + +/** + * Check if a given object implements the TeamUpdate interface. + */ +export function instanceOfTeamUpdate(value: object): value is TeamUpdate { + return true; +} + +export function TeamUpdateFromJSON(json: any): TeamUpdate { + return TeamUpdateFromJSONTyped(json, false); +} + +export function TeamUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): TeamUpdate { + if (json == null) { + return json; + } + return { + + 'name': json['name'] == null ? undefined : json['name'], + 'description': json['description'] == null ? undefined : json['description'], + 'parentTeamId': json['parent_team_id'] == null ? undefined : json['parent_team_id'], + 'externalId': json['external_id'] == null ? undefined : json['external_id'], + }; +} + +export function TeamUpdateToJSON(json: any): TeamUpdate { + return TeamUpdateToJSONTyped(json, false); +} + +export function TeamUpdateToJSONTyped(value?: TeamUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'name': value['name'], + 'description': value['description'], + 'parent_team_id': value['parentTeamId'], + 'external_id': value['externalId'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/TeamsPage.ts b/sdk/typescript-fetch/src/models/TeamsPage.ts new file mode 100644 index 0000000..4f58a78 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TeamsPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { Team } from './Team'; +import { + TeamFromJSON, + TeamFromJSONTyped, + TeamToJSON, + TeamToJSONTyped, +} from './Team'; + +/** + * + * @export + * @interface TeamsPage + */ +export interface TeamsPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof TeamsPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof TeamsPage + */ + data: Array; +} + +/** + * Check if a given object implements the TeamsPage interface. + */ +export function instanceOfTeamsPage(value: object): value is TeamsPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function TeamsPageFromJSON(json: any): TeamsPage { + return TeamsPageFromJSONTyped(json, false); +} + +export function TeamsPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): TeamsPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(TeamFromJSON)), + }; +} + +export function TeamsPageToJSON(json: any): TeamsPage { + return TeamsPageToJSONTyped(json, false); +} + +export function TeamsPageToJSONTyped(value?: TeamsPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(TeamToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/TeamsPartialPage.ts b/sdk/typescript-fetch/src/models/TeamsPartialPage.ts new file mode 100644 index 0000000..ef158ef --- /dev/null +++ b/sdk/typescript-fetch/src/models/TeamsPartialPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { TeamPartial } from './TeamPartial'; +import { + TeamPartialFromJSON, + TeamPartialFromJSONTyped, + TeamPartialToJSON, + TeamPartialToJSONTyped, +} from './TeamPartial'; + +/** + * + * @export + * @interface TeamsPartialPage + */ +export interface TeamsPartialPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof TeamsPartialPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof TeamsPartialPage + */ + data: Array; +} + +/** + * Check if a given object implements the TeamsPartialPage interface. + */ +export function instanceOfTeamsPartialPage(value: object): value is TeamsPartialPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function TeamsPartialPageFromJSON(json: any): TeamsPartialPage { + return TeamsPartialPageFromJSONTyped(json, false); +} + +export function TeamsPartialPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): TeamsPartialPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(TeamPartialFromJSON)), + }; +} + +export function TeamsPartialPageToJSON(json: any): TeamsPartialPage { + return TeamsPartialPageToJSONTyped(json, false); +} + +export function TeamsPartialPageToJSONTyped(value?: TeamsPartialPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(TeamPartialToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/TeamsSortColumn.ts b/sdk/typescript-fetch/src/models/TeamsSortColumn.ts new file mode 100644 index 0000000..2e9037e --- /dev/null +++ b/sdk/typescript-fetch/src/models/TeamsSortColumn.ts @@ -0,0 +1,53 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Teams. `breadcrumbs` orders by the Team's full path, `name` by its own name only. + * @export + */ +export const TeamsSortColumn = { + Breadcrumbs: 'breadcrumbs', + Name: 'name' +} as const; +export type TeamsSortColumn = typeof TeamsSortColumn[keyof typeof TeamsSortColumn]; + + +export function instanceOfTeamsSortColumn(value: any): boolean { + for (const key in TeamsSortColumn) { + if (Object.prototype.hasOwnProperty.call(TeamsSortColumn, key)) { + if (TeamsSortColumn[key as keyof typeof TeamsSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function TeamsSortColumnFromJSON(json: any): TeamsSortColumn { + return TeamsSortColumnFromJSONTyped(json, false); +} + +export function TeamsSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): TeamsSortColumn { + return json as TeamsSortColumn; +} + +export function TeamsSortColumnToJSON(value?: TeamsSortColumn | null): any { + return value as any; +} + +export function TeamsSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): TeamsSortColumn { + return value as TeamsSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/TimeAccount.ts b/sdk/typescript-fetch/src/models/TimeAccount.ts new file mode 100644 index 0000000..7bc86b8 --- /dev/null +++ b/sdk/typescript-fetch/src/models/TimeAccount.ts @@ -0,0 +1,138 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { FlexTimeIndicator } from './FlexTimeIndicator'; +import { + FlexTimeIndicatorFromJSON, + FlexTimeIndicatorFromJSONTyped, + FlexTimeIndicatorToJSON, + FlexTimeIndicatorToJSONTyped, +} from './FlexTimeIndicator'; + +/** + * + * @export + * @interface TimeAccount + */ +export interface TimeAccount { + /** + * + * @type {number} + * @memberof TimeAccount + */ + balanceLastPeriodMinutes: number | null; + /** + * sum of durations in current period + * @type {number} + * @memberof TimeAccount + */ + durationActualMinutes: number | null; + /** + * target duration in current period + * @type {number} + * @memberof TimeAccount + */ + durationTargetMinutes: number | null; + /** + * difference between target duration and actual duration + * @type {number} + * @memberof TimeAccount + */ + balanceCurrentPeriodMinutes: number | null; + /** + * total duration until balancing date + * @type {number} + * @memberof TimeAccount + */ + balanceTotalMinutes: number | null; + /** + * complete days worked from home in current period + * @type {number} + * @memberof TimeAccount + */ + workFromHomeDaysFull: number | null; + /** + * partial days worked from home in current period + * @type {number} + * @memberof TimeAccount + */ + workFromHomeDaysPartial: number | null; + /** + * + * @type {FlexTimeIndicator} + * @memberof TimeAccount + */ + flexTimeIndicator?: FlexTimeIndicator | null; +} + + + +/** + * Check if a given object implements the TimeAccount interface. + */ +export function instanceOfTimeAccount(value: object): value is TimeAccount { + if (!('balanceLastPeriodMinutes' in value) || value['balanceLastPeriodMinutes'] === undefined) return false; + if (!('durationActualMinutes' in value) || value['durationActualMinutes'] === undefined) return false; + if (!('durationTargetMinutes' in value) || value['durationTargetMinutes'] === undefined) return false; + if (!('balanceCurrentPeriodMinutes' in value) || value['balanceCurrentPeriodMinutes'] === undefined) return false; + if (!('balanceTotalMinutes' in value) || value['balanceTotalMinutes'] === undefined) return false; + if (!('workFromHomeDaysFull' in value) || value['workFromHomeDaysFull'] === undefined) return false; + if (!('workFromHomeDaysPartial' in value) || value['workFromHomeDaysPartial'] === undefined) return false; + return true; +} + +export function TimeAccountFromJSON(json: any): TimeAccount { + return TimeAccountFromJSONTyped(json, false); +} + +export function TimeAccountFromJSONTyped(json: any, ignoreDiscriminator: boolean): TimeAccount { + if (json == null) { + return json; + } + return { + + 'balanceLastPeriodMinutes': json['balance_last_period_minutes'], + 'durationActualMinutes': json['duration_actual_minutes'], + 'durationTargetMinutes': json['duration_target_minutes'], + 'balanceCurrentPeriodMinutes': json['balance_current_period_minutes'], + 'balanceTotalMinutes': json['balance_total_minutes'], + 'workFromHomeDaysFull': json['work_from_home_days_full'], + 'workFromHomeDaysPartial': json['work_from_home_days_partial'], + 'flexTimeIndicator': json['flex_time_indicator'] == null ? undefined : FlexTimeIndicatorFromJSON(json['flex_time_indicator']), + }; +} + +export function TimeAccountToJSON(json: any): TimeAccount { + return TimeAccountToJSONTyped(json, false); +} + +export function TimeAccountToJSONTyped(value?: TimeAccount | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'balance_last_period_minutes': value['balanceLastPeriodMinutes'], + 'duration_actual_minutes': value['durationActualMinutes'], + 'duration_target_minutes': value['durationTargetMinutes'], + 'balance_current_period_minutes': value['balanceCurrentPeriodMinutes'], + 'balance_total_minutes': value['balanceTotalMinutes'], + 'work_from_home_days_full': value['workFromHomeDaysFull'], + 'work_from_home_days_partial': value['workFromHomeDaysPartial'], + 'flex_time_indicator': FlexTimeIndicatorToJSON(value['flexTimeIndicator']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/User.ts b/sdk/typescript-fetch/src/models/User.ts new file mode 100644 index 0000000..ff5eae8 --- /dev/null +++ b/sdk/typescript-fetch/src/models/User.ts @@ -0,0 +1,192 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { WorkScheduleModelPartial } from './WorkScheduleModelPartial'; +import { + WorkScheduleModelPartialFromJSON, + WorkScheduleModelPartialFromJSONTyped, + WorkScheduleModelPartialToJSON, + WorkScheduleModelPartialToJSONTyped, +} from './WorkScheduleModelPartial'; +import type { HolidayCalendarPartial } from './HolidayCalendarPartial'; +import { + HolidayCalendarPartialFromJSON, + HolidayCalendarPartialFromJSONTyped, + HolidayCalendarPartialToJSON, + HolidayCalendarPartialToJSONTyped, +} from './HolidayCalendarPartial'; + +/** + * A user's identity (`firstname`, `lastname`, `email`), employment dates (`entry_date`, `resign_date`), and the assigned `work_schedule_model` and `holiday_calendar`. + * + * @export + * @interface User + */ +export interface User { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof User + */ + id: string; + /** + * + * @type {string} + * @memberof User + */ + firstname: string | null; + /** + * + * @type {string} + * @memberof User + */ + lastname: string | null; + /** + * + * @type {string} + * @memberof User + */ + fullname: string | null; + /** + * Email address must be either valid or null. + * @type {string} + * @memberof User + */ + email: string | null; + /** + * + * @type {string} + * @memberof User + */ + employeeNumber: string | null; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof User + */ + externalId: string | null; + /** + * + * @type {string} + * @memberof User + */ + login?: string; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof User + */ + entryDate?: Date | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof User + */ + resignDate?: Date | null; + /** + * + * @type {WorkScheduleModelPartial} + * @memberof User + */ + workScheduleModel?: WorkScheduleModelPartial | null; + /** + * + * @type {HolidayCalendarPartial} + * @memberof User + */ + holidayCalendar?: HolidayCalendarPartial; + /** + * recurring month and day on which the user's vacation year starts + * @type {string} + * @memberof User + */ + vacationYearStart?: string | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof User + */ + metadata?: { [key: string]: any; } | null; +} + +/** + * Check if a given object implements the User interface. + */ +export function instanceOfUser(value: object): value is User { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('firstname' in value) || value['firstname'] === undefined) return false; + if (!('lastname' in value) || value['lastname'] === undefined) return false; + if (!('fullname' in value) || value['fullname'] === undefined) return false; + if (!('email' in value) || value['email'] === undefined) return false; + if (!('employeeNumber' in value) || value['employeeNumber'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + return true; +} + +export function UserFromJSON(json: any): User { + return UserFromJSONTyped(json, false); +} + +export function UserFromJSONTyped(json: any, ignoreDiscriminator: boolean): User { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'firstname': json['firstname'], + 'lastname': json['lastname'], + 'fullname': json['fullname'], + 'email': json['email'], + 'employeeNumber': json['employee_number'], + 'externalId': json['external_id'], + 'login': json['login'] == null ? undefined : json['login'], + 'entryDate': json['entry_date'] == null ? undefined : (new Date(json['entry_date'])), + 'resignDate': json['resign_date'] == null ? undefined : (new Date(json['resign_date'])), + 'workScheduleModel': json['work_schedule_model'] == null ? undefined : WorkScheduleModelPartialFromJSON(json['work_schedule_model']), + 'holidayCalendar': json['holiday_calendar'] == null ? undefined : HolidayCalendarPartialFromJSON(json['holiday_calendar']), + 'vacationYearStart': json['vacation_year_start'] == null ? undefined : json['vacation_year_start'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function UserToJSON(json: any): User { + return UserToJSONTyped(json, false); +} + +export function UserToJSONTyped(value?: User | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'firstname': value['firstname'], + 'lastname': value['lastname'], + 'fullname': value['fullname'], + 'email': value['email'], + 'employee_number': value['employeeNumber'], + 'external_id': value['externalId'], + 'login': value['login'], + 'entry_date': value['entryDate'] == null ? value['entryDate'] : value['entryDate'].toISOString().substring(0,10), + 'resign_date': value['resignDate'] == null ? value['resignDate'] : value['resignDate'].toISOString().substring(0,10), + 'work_schedule_model': WorkScheduleModelPartialToJSON(value['workScheduleModel']), + 'holiday_calendar': HolidayCalendarPartialToJSON(value['holidayCalendar']), + 'vacation_year_start': value['vacationYearStart'], + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/UserCreate.ts b/sdk/typescript-fetch/src/models/UserCreate.ts new file mode 100644 index 0000000..b5df696 --- /dev/null +++ b/sdk/typescript-fetch/src/models/UserCreate.ts @@ -0,0 +1,146 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface UserCreate + */ +export interface UserCreate { + /** + * + * @type {string} + * @memberof UserCreate + */ + login: string; + /** + * + * @type {string} + * @memberof UserCreate + */ + firstname?: string | null; + /** + * + * @type {string} + * @memberof UserCreate + */ + lastname?: string | null; + /** + * + * @type {string} + * @memberof UserCreate + */ + email?: string | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof UserCreate + */ + entryDate?: Date | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof UserCreate + */ + resignDate?: Date | null; + /** + * + * @type {string} + * @memberof UserCreate + */ + employeeNumber?: string | null; + /** + * + * @type {string} + * @memberof UserCreate + */ + externalId?: string | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof UserCreate + */ + metadata?: { [key: string]: any; } | null; + /** + * + * @type {string} + * @memberof UserCreate + */ + authProvider?: string | null; + /** + * + * @type {string} + * @memberof UserCreate + */ + authIdentifier?: string | null; +} + +/** + * Check if a given object implements the UserCreate interface. + */ +export function instanceOfUserCreate(value: object): value is UserCreate { + if (!('login' in value) || value['login'] === undefined) return false; + return true; +} + +export function UserCreateFromJSON(json: any): UserCreate { + return UserCreateFromJSONTyped(json, false); +} + +export function UserCreateFromJSONTyped(json: any, ignoreDiscriminator: boolean): UserCreate { + if (json == null) { + return json; + } + return { + + 'login': json['login'], + 'firstname': json['firstname'] == null ? undefined : json['firstname'], + 'lastname': json['lastname'] == null ? undefined : json['lastname'], + 'email': json['email'] == null ? undefined : json['email'], + 'entryDate': json['entry_date'] == null ? undefined : (new Date(json['entry_date'])), + 'resignDate': json['resign_date'] == null ? undefined : (new Date(json['resign_date'])), + 'employeeNumber': json['employee_number'] == null ? undefined : json['employee_number'], + 'externalId': json['external_id'] == null ? undefined : json['external_id'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + 'authProvider': json['auth_provider'] == null ? undefined : json['auth_provider'], + 'authIdentifier': json['auth_identifier'] == null ? undefined : json['auth_identifier'], + }; +} + +export function UserCreateToJSON(json: any): UserCreate { + return UserCreateToJSONTyped(json, false); +} + +export function UserCreateToJSONTyped(value?: UserCreate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'login': value['login'], + 'firstname': value['firstname'], + 'lastname': value['lastname'], + 'email': value['email'], + 'entry_date': value['entryDate'] == null ? value['entryDate'] : value['entryDate'].toISOString().substring(0,10), + 'resign_date': value['resignDate'] == null ? value['resignDate'] : value['resignDate'].toISOString().substring(0,10), + 'employee_number': value['employeeNumber'], + 'external_id': value['externalId'], + 'metadata': value['metadata'], + 'auth_provider': value['authProvider'], + 'auth_identifier': value['authIdentifier'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/UserPartial.ts b/sdk/typescript-fetch/src/models/UserPartial.ts new file mode 100644 index 0000000..2bf892f --- /dev/null +++ b/sdk/typescript-fetch/src/models/UserPartial.ts @@ -0,0 +1,120 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface UserPartial + */ +export interface UserPartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof UserPartial + */ + id: string; + /** + * + * @type {string} + * @memberof UserPartial + */ + firstname: string | null; + /** + * + * @type {string} + * @memberof UserPartial + */ + lastname: string | null; + /** + * + * @type {string} + * @memberof UserPartial + */ + fullname: string | null; + /** + * Email address must be either valid or null. + * @type {string} + * @memberof UserPartial + */ + email: string | null; + /** + * + * @type {string} + * @memberof UserPartial + */ + employeeNumber: string | null; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof UserPartial + */ + externalId: string | null; +} + +/** + * Check if a given object implements the UserPartial interface. + */ +export function instanceOfUserPartial(value: object): value is UserPartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('firstname' in value) || value['firstname'] === undefined) return false; + if (!('lastname' in value) || value['lastname'] === undefined) return false; + if (!('fullname' in value) || value['fullname'] === undefined) return false; + if (!('email' in value) || value['email'] === undefined) return false; + if (!('employeeNumber' in value) || value['employeeNumber'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + return true; +} + +export function UserPartialFromJSON(json: any): UserPartial { + return UserPartialFromJSONTyped(json, false); +} + +export function UserPartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): UserPartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'firstname': json['firstname'], + 'lastname': json['lastname'], + 'fullname': json['fullname'], + 'email': json['email'], + 'employeeNumber': json['employee_number'], + 'externalId': json['external_id'], + }; +} + +export function UserPartialToJSON(json: any): UserPartial { + return UserPartialToJSONTyped(json, false); +} + +export function UserPartialToJSONTyped(value?: UserPartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'firstname': value['firstname'], + 'lastname': value['lastname'], + 'fullname': value['fullname'], + 'email': value['email'], + 'employee_number': value['employeeNumber'], + 'external_id': value['externalId'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/UserUpdate.ts b/sdk/typescript-fetch/src/models/UserUpdate.ts new file mode 100644 index 0000000..10b79da --- /dev/null +++ b/sdk/typescript-fetch/src/models/UserUpdate.ts @@ -0,0 +1,129 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface UserUpdate + */ +export interface UserUpdate { + /** + * + * @type {string} + * @memberof UserUpdate + */ + login?: string; + /** + * + * @type {string} + * @memberof UserUpdate + */ + firstname?: string | null; + /** + * + * @type {string} + * @memberof UserUpdate + */ + lastname?: string | null; + /** + * + * @type {string} + * @memberof UserUpdate + */ + email?: string | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof UserUpdate + */ + entryDate?: Date | null; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof UserUpdate + */ + resignDate?: Date | null; + /** + * + * @type {string} + * @memberof UserUpdate + */ + employeeNumber?: string | null; + /** + * + * @type {string} + * @memberof UserUpdate + */ + externalId?: string | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof UserUpdate + */ + metadata?: { [key: string]: any; } | null; +} + +/** + * Check if a given object implements the UserUpdate interface. + */ +export function instanceOfUserUpdate(value: object): value is UserUpdate { + return true; +} + +export function UserUpdateFromJSON(json: any): UserUpdate { + return UserUpdateFromJSONTyped(json, false); +} + +export function UserUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): UserUpdate { + if (json == null) { + return json; + } + return { + + 'login': json['login'] == null ? undefined : json['login'], + 'firstname': json['firstname'] == null ? undefined : json['firstname'], + 'lastname': json['lastname'] == null ? undefined : json['lastname'], + 'email': json['email'] == null ? undefined : json['email'], + 'entryDate': json['entry_date'] == null ? undefined : (new Date(json['entry_date'])), + 'resignDate': json['resign_date'] == null ? undefined : (new Date(json['resign_date'])), + 'employeeNumber': json['employee_number'] == null ? undefined : json['employee_number'], + 'externalId': json['external_id'] == null ? undefined : json['external_id'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function UserUpdateToJSON(json: any): UserUpdate { + return UserUpdateToJSONTyped(json, false); +} + +export function UserUpdateToJSONTyped(value?: UserUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'login': value['login'], + 'firstname': value['firstname'], + 'lastname': value['lastname'], + 'email': value['email'], + 'entry_date': value['entryDate'] == null ? value['entryDate'] : value['entryDate'].toISOString().substring(0,10), + 'resign_date': value['resignDate'] == null ? value['resignDate'] : value['resignDate'].toISOString().substring(0,10), + 'employee_number': value['employeeNumber'], + 'external_id': value['externalId'], + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/UsersPage.ts b/sdk/typescript-fetch/src/models/UsersPage.ts new file mode 100644 index 0000000..9831398 --- /dev/null +++ b/sdk/typescript-fetch/src/models/UsersPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { User } from './User'; +import { + UserFromJSON, + UserFromJSONTyped, + UserToJSON, + UserToJSONTyped, +} from './User'; + +/** + * + * @export + * @interface UsersPage + */ +export interface UsersPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof UsersPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof UsersPage + */ + data: Array; +} + +/** + * Check if a given object implements the UsersPage interface. + */ +export function instanceOfUsersPage(value: object): value is UsersPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function UsersPageFromJSON(json: any): UsersPage { + return UsersPageFromJSONTyped(json, false); +} + +export function UsersPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): UsersPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(UserFromJSON)), + }; +} + +export function UsersPageToJSON(json: any): UsersPage { + return UsersPageToJSONTyped(json, false); +} + +export function UsersPageToJSONTyped(value?: UsersPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(UserToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/UsersPartialPage.ts b/sdk/typescript-fetch/src/models/UsersPartialPage.ts new file mode 100644 index 0000000..e6f3ef1 --- /dev/null +++ b/sdk/typescript-fetch/src/models/UsersPartialPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; + +/** + * + * @export + * @interface UsersPartialPage + */ +export interface UsersPartialPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof UsersPartialPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof UsersPartialPage + */ + data: Array; +} + +/** + * Check if a given object implements the UsersPartialPage interface. + */ +export function instanceOfUsersPartialPage(value: object): value is UsersPartialPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function UsersPartialPageFromJSON(json: any): UsersPartialPage { + return UsersPartialPageFromJSONTyped(json, false); +} + +export function UsersPartialPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): UsersPartialPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(UserPartialFromJSON)), + }; +} + +export function UsersPartialPageToJSON(json: any): UsersPartialPage { + return UsersPartialPageToJSONTyped(json, false); +} + +export function UsersPartialPageToJSONTyped(value?: UsersPartialPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(UserPartialToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/UsersSortColumn.ts b/sdk/typescript-fetch/src/models/UsersSortColumn.ts new file mode 100644 index 0000000..d5d1b13 --- /dev/null +++ b/sdk/typescript-fetch/src/models/UsersSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Users. `name` orders by last name, then first name. + * @export + */ +export const UsersSortColumn = { + Name: 'name' +} as const; +export type UsersSortColumn = typeof UsersSortColumn[keyof typeof UsersSortColumn]; + + +export function instanceOfUsersSortColumn(value: any): boolean { + for (const key in UsersSortColumn) { + if (Object.prototype.hasOwnProperty.call(UsersSortColumn, key)) { + if (UsersSortColumn[key as keyof typeof UsersSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function UsersSortColumnFromJSON(json: any): UsersSortColumn { + return UsersSortColumnFromJSONTyped(json, false); +} + +export function UsersSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): UsersSortColumn { + return json as UsersSortColumn; +} + +export function UsersSortColumnToJSON(value?: UsersSortColumn | null): any { + return value as any; +} + +export function UsersSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): UsersSortColumn { + return value as UsersSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/VacationAccount.ts b/sdk/typescript-fetch/src/models/VacationAccount.ts new file mode 100644 index 0000000..7c72270 --- /dev/null +++ b/sdk/typescript-fetch/src/models/VacationAccount.ts @@ -0,0 +1,72 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import type { VacationAccountDays } from './VacationAccountDays'; +import { + instanceOfVacationAccountDays, + VacationAccountDaysFromJSON, + VacationAccountDaysFromJSONTyped, + VacationAccountDaysToJSON, +} from './VacationAccountDays'; +import type { VacationAccountMinutes } from './VacationAccountMinutes'; +import { + instanceOfVacationAccountMinutes, + VacationAccountMinutesFromJSON, + VacationAccountMinutesFromJSONTyped, + VacationAccountMinutesToJSON, +} from './VacationAccountMinutes'; + +/** + * @type VacationAccount + * + * @export + */ +export type VacationAccount = { unit: 'days' } & VacationAccountDays | { unit: 'minutes' } & VacationAccountMinutes; + +export function VacationAccountFromJSON(json: any): VacationAccount { + return VacationAccountFromJSONTyped(json, false); +} + +export function VacationAccountFromJSONTyped(json: any, ignoreDiscriminator: boolean): VacationAccount { + if (json == null) { + return json; + } + switch (json['unit']) { + case 'days': + return Object.assign({}, VacationAccountDaysFromJSONTyped(json, true), { unit: 'days' } as const); + case 'minutes': + return Object.assign({}, VacationAccountMinutesFromJSONTyped(json, true), { unit: 'minutes' } as const); + default: + return json; + } +} + +export function VacationAccountToJSON(json: any): any { + return VacationAccountToJSONTyped(json, false); +} + +export function VacationAccountToJSONTyped(value?: VacationAccount | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + switch (value['unit']) { + case 'days': + return Object.assign({}, VacationAccountDaysToJSON(value), { unit: 'days' } as const); + case 'minutes': + return Object.assign({}, VacationAccountMinutesToJSON(value), { unit: 'minutes' } as const); + default: + return value; + } +} + diff --git a/sdk/typescript-fetch/src/models/VacationAccountBase.ts b/sdk/typescript-fetch/src/models/VacationAccountBase.ts new file mode 100644 index 0000000..f8369c8 --- /dev/null +++ b/sdk/typescript-fetch/src/models/VacationAccountBase.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { VacationUnit } from './VacationUnit'; +import { + VacationUnitFromJSON, + VacationUnitFromJSONTyped, + VacationUnitToJSON, + VacationUnitToJSONTyped, +} from './VacationUnit'; + +/** + * Members shared by every kind of vacation account, including the discriminator. + * @export + * @interface VacationAccountBase + */ +export interface VacationAccountBase { + /** + * + * @type {VacationUnit} + * @memberof VacationAccountBase + */ + unit: VacationUnit; +} + + + +/** + * Check if a given object implements the VacationAccountBase interface. + */ +export function instanceOfVacationAccountBase(value: object): value is VacationAccountBase { + if (!('unit' in value) || value['unit'] === undefined) return false; + return true; +} + +export function VacationAccountBaseFromJSON(json: any): VacationAccountBase { + return VacationAccountBaseFromJSONTyped(json, false); +} + +export function VacationAccountBaseFromJSONTyped(json: any, ignoreDiscriminator: boolean): VacationAccountBase { + if (json == null) { + return json; + } + return { + + 'unit': VacationUnitFromJSON(json['unit']), + }; +} + +export function VacationAccountBaseToJSON(json: any): VacationAccountBase { + return VacationAccountBaseToJSONTyped(json, false); +} + +export function VacationAccountBaseToJSONTyped(value?: VacationAccountBase | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'unit': VacationUnitToJSON(value['unit']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/VacationAccountDays.ts b/sdk/typescript-fetch/src/models/VacationAccountDays.ts new file mode 100644 index 0000000..c25a227 --- /dev/null +++ b/sdk/typescript-fetch/src/models/VacationAccountDays.ts @@ -0,0 +1,108 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { VacationUnit } from './VacationUnit'; +import { + VacationUnitFromJSON, + VacationUnitFromJSONTyped, + VacationUnitToJSON, + VacationUnitToJSONTyped, +} from './VacationUnit'; + +/** + * + * @export + * @interface VacationAccountDays + */ +export interface VacationAccountDays { + /** + * + * @type {VacationUnit} + * @memberof VacationAccountDays + */ + unit: VacationUnit; + /** + * vacation balance carried over from the previous vacation period, in days + * @type {number} + * @memberof VacationAccountDays + */ + balanceLastPeriodDays?: number | null; + /** + * vacation consumed in the current vacation period, in days + * @type {number} + * @memberof VacationAccountDays + */ + consumedDays?: number | null; + /** + * vacation newly granted in the current vacation period, in days + * @type {number} + * @memberof VacationAccountDays + */ + newDays?: number | null; + /** + * total vacation balance for the current vacation period, in days + * @type {number} + * @memberof VacationAccountDays + */ + balanceTotalDays?: number | null; +} + + + +/** + * Check if a given object implements the VacationAccountDays interface. + */ +export function instanceOfVacationAccountDays(value: object): value is VacationAccountDays { + if (!('unit' in value) || value['unit'] === undefined) return false; + return true; +} + +export function VacationAccountDaysFromJSON(json: any): VacationAccountDays { + return VacationAccountDaysFromJSONTyped(json, false); +} + +export function VacationAccountDaysFromJSONTyped(json: any, ignoreDiscriminator: boolean): VacationAccountDays { + if (json == null) { + return json; + } + return { + + 'unit': VacationUnitFromJSON(json['unit']), + 'balanceLastPeriodDays': json['balance_last_period_days'] == null ? undefined : json['balance_last_period_days'], + 'consumedDays': json['consumed_days'] == null ? undefined : json['consumed_days'], + 'newDays': json['new_days'] == null ? undefined : json['new_days'], + 'balanceTotalDays': json['balance_total_days'] == null ? undefined : json['balance_total_days'], + }; +} + +export function VacationAccountDaysToJSON(json: any): VacationAccountDays { + return VacationAccountDaysToJSONTyped(json, false); +} + +export function VacationAccountDaysToJSONTyped(value?: VacationAccountDays | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'unit': VacationUnitToJSON(value['unit']), + 'balance_last_period_days': value['balanceLastPeriodDays'], + 'consumed_days': value['consumedDays'], + 'new_days': value['newDays'], + 'balance_total_days': value['balanceTotalDays'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/VacationAccountMinutes.ts b/sdk/typescript-fetch/src/models/VacationAccountMinutes.ts new file mode 100644 index 0000000..84b77c3 --- /dev/null +++ b/sdk/typescript-fetch/src/models/VacationAccountMinutes.ts @@ -0,0 +1,108 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { VacationUnit } from './VacationUnit'; +import { + VacationUnitFromJSON, + VacationUnitFromJSONTyped, + VacationUnitToJSON, + VacationUnitToJSONTyped, +} from './VacationUnit'; + +/** + * + * @export + * @interface VacationAccountMinutes + */ +export interface VacationAccountMinutes { + /** + * + * @type {VacationUnit} + * @memberof VacationAccountMinutes + */ + unit: VacationUnit; + /** + * vacation balance carried over from the previous vacation period, in minutes + * @type {number} + * @memberof VacationAccountMinutes + */ + balanceLastPeriodMinutes?: number | null; + /** + * vacation consumed in the current vacation period, in minutes + * @type {number} + * @memberof VacationAccountMinutes + */ + consumedMinutes?: number | null; + /** + * vacation newly granted in the current vacation period, in minutes + * @type {number} + * @memberof VacationAccountMinutes + */ + newMinutes?: number | null; + /** + * total vacation balance for the current vacation period, in minutes + * @type {number} + * @memberof VacationAccountMinutes + */ + balanceTotalMinutes?: number | null; +} + + + +/** + * Check if a given object implements the VacationAccountMinutes interface. + */ +export function instanceOfVacationAccountMinutes(value: object): value is VacationAccountMinutes { + if (!('unit' in value) || value['unit'] === undefined) return false; + return true; +} + +export function VacationAccountMinutesFromJSON(json: any): VacationAccountMinutes { + return VacationAccountMinutesFromJSONTyped(json, false); +} + +export function VacationAccountMinutesFromJSONTyped(json: any, ignoreDiscriminator: boolean): VacationAccountMinutes { + if (json == null) { + return json; + } + return { + + 'unit': VacationUnitFromJSON(json['unit']), + 'balanceLastPeriodMinutes': json['balance_last_period_minutes'] == null ? undefined : json['balance_last_period_minutes'], + 'consumedMinutes': json['consumed_minutes'] == null ? undefined : json['consumed_minutes'], + 'newMinutes': json['new_minutes'] == null ? undefined : json['new_minutes'], + 'balanceTotalMinutes': json['balance_total_minutes'] == null ? undefined : json['balance_total_minutes'], + }; +} + +export function VacationAccountMinutesToJSON(json: any): VacationAccountMinutes { + return VacationAccountMinutesToJSONTyped(json, false); +} + +export function VacationAccountMinutesToJSONTyped(value?: VacationAccountMinutes | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'unit': VacationUnitToJSON(value['unit']), + 'balance_last_period_minutes': value['balanceLastPeriodMinutes'], + 'consumed_minutes': value['consumedMinutes'], + 'new_minutes': value['newMinutes'], + 'balance_total_minutes': value['balanceTotalMinutes'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/VacationUnit.ts b/sdk/typescript-fetch/src/models/VacationUnit.ts new file mode 100644 index 0000000..7e143f5 --- /dev/null +++ b/sdk/typescript-fetch/src/models/VacationUnit.ts @@ -0,0 +1,53 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Unit a vacation entitlement is expressed in. + * @export + */ +export const VacationUnit = { + Days: 'days', + Minutes: 'minutes' +} as const; +export type VacationUnit = typeof VacationUnit[keyof typeof VacationUnit]; + + +export function instanceOfVacationUnit(value: any): boolean { + for (const key in VacationUnit) { + if (Object.prototype.hasOwnProperty.call(VacationUnit, key)) { + if (VacationUnit[key as keyof typeof VacationUnit] === value) { + return true; + } + } + } + return false; +} + +export function VacationUnitFromJSON(json: any): VacationUnit { + return VacationUnitFromJSONTyped(json, false); +} + +export function VacationUnitFromJSONTyped(json: any, ignoreDiscriminator: boolean): VacationUnit { + return json as VacationUnit; +} + +export function VacationUnitToJSON(value?: VacationUnit | null): any { + return value as any; +} + +export function VacationUnitToJSONTyped(value: any, ignoreDiscriminator: boolean): VacationUnit { + return value as VacationUnit; +} + diff --git a/sdk/typescript-fetch/src/models/VenuePartial.ts b/sdk/typescript-fetch/src/models/VenuePartial.ts new file mode 100644 index 0000000..6b913c6 --- /dev/null +++ b/sdk/typescript-fetch/src/models/VenuePartial.ts @@ -0,0 +1,136 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface VenuePartial + */ +export interface VenuePartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof VenuePartial + */ + id: string; + /** + * + * @type {string} + * @memberof VenuePartial + */ + name: string; + /** + * + * @type {string} + * @memberof VenuePartial + */ + city: string; + /** + * + * @type {string} + * @memberof VenuePartial + */ + zipCode: string; + /** + * + * @type {string} + * @memberof VenuePartial + */ + street: string; + /** + * + * @type {string} + * @memberof VenuePartial + */ + streetNumber: string; + /** + * + * @type {string} + * @memberof VenuePartial + */ + country: string; + /** + * Latitude in decimal degrees. + * @type {number} + * @memberof VenuePartial + */ + lat?: number; + /** + * Longitude in decimal degrees. + * @type {number} + * @memberof VenuePartial + */ + lon?: number; +} + +/** + * Check if a given object implements the VenuePartial interface. + */ +export function instanceOfVenuePartial(value: object): value is VenuePartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('city' in value) || value['city'] === undefined) return false; + if (!('zipCode' in value) || value['zipCode'] === undefined) return false; + if (!('street' in value) || value['street'] === undefined) return false; + if (!('streetNumber' in value) || value['streetNumber'] === undefined) return false; + if (!('country' in value) || value['country'] === undefined) return false; + return true; +} + +export function VenuePartialFromJSON(json: any): VenuePartial { + return VenuePartialFromJSONTyped(json, false); +} + +export function VenuePartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): VenuePartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'city': json['city'], + 'zipCode': json['zip_code'], + 'street': json['street'], + 'streetNumber': json['street_number'], + 'country': json['country'], + 'lat': json['lat'] == null ? undefined : json['lat'], + 'lon': json['lon'] == null ? undefined : json['lon'], + }; +} + +export function VenuePartialToJSON(json: any): VenuePartial { + return VenuePartialToJSONTyped(json, false); +} + +export function VenuePartialToJSONTyped(value?: VenuePartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'city': value['city'], + 'zip_code': value['zipCode'], + 'street': value['street'], + 'street_number': value['streetNumber'], + 'country': value['country'], + 'lat': value['lat'], + 'lon': value['lon'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/Waypoint.ts b/sdk/typescript-fetch/src/models/Waypoint.ts new file mode 100644 index 0000000..15634a2 --- /dev/null +++ b/sdk/typescript-fetch/src/models/Waypoint.ts @@ -0,0 +1,75 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface Waypoint + */ +export interface Waypoint { + /** + * + * @type {number} + * @memberof Waypoint + */ + lat: number; + /** + * + * @type {number} + * @memberof Waypoint + */ + lon: number; +} + +/** + * Check if a given object implements the Waypoint interface. + */ +export function instanceOfWaypoint(value: object): value is Waypoint { + if (!('lat' in value) || value['lat'] === undefined) return false; + if (!('lon' in value) || value['lon'] === undefined) return false; + return true; +} + +export function WaypointFromJSON(json: any): Waypoint { + return WaypointFromJSONTyped(json, false); +} + +export function WaypointFromJSONTyped(json: any, ignoreDiscriminator: boolean): Waypoint { + if (json == null) { + return json; + } + return { + + 'lat': json['lat'], + 'lon': json['lon'], + }; +} + +export function WaypointToJSON(json: any): Waypoint { + return WaypointToJSONTyped(json, false); +} + +export function WaypointToJSONTyped(value?: Waypoint | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'lat': value['lat'], + 'lon': value['lon'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkScheduleModel.ts b/sdk/typescript-fetch/src/models/WorkScheduleModel.ts new file mode 100644 index 0000000..5a4cde7 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkScheduleModel.ts @@ -0,0 +1,128 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { WorkScheduleModelType } from './WorkScheduleModelType'; +import { + WorkScheduleModelTypeFromJSON, + WorkScheduleModelTypeFromJSONTyped, + WorkScheduleModelTypeToJSON, + WorkScheduleModelTypeToJSONTyped, +} from './WorkScheduleModelType'; +import type { WorkScheduleModelWeek } from './WorkScheduleModelWeek'; +import { + WorkScheduleModelWeekFromJSON, + WorkScheduleModelWeekFromJSONTyped, + WorkScheduleModelWeekToJSON, + WorkScheduleModelWeekToJSONTyped, +} from './WorkScheduleModelWeek'; +import type { WorkingTimeRules } from './WorkingTimeRules'; +import { + WorkingTimeRulesFromJSON, + WorkingTimeRulesFromJSONTyped, + WorkingTimeRulesToJSON, + WorkingTimeRulesToJSONTyped, +} from './WorkingTimeRules'; + +/** + * The weekday targets a user is measured against: `weeks` holds the layout, `type` selects the calculation mode, and `working_time_rules` the recording constraints. + * + * @export + * @interface WorkScheduleModel + */ +export interface WorkScheduleModel { + /** + * + * @type {string} + * @memberof WorkScheduleModel + */ + id: string; + /** + * + * @type {string} + * @memberof WorkScheduleModel + */ + name: string; + /** + * working-time calculation mode (daily_target_hours or normal_working_time); independent from the internal week layout (fixed_week or alternating_weeks) + * @type {WorkScheduleModelType} + * @memberof WorkScheduleModel + */ + type: WorkScheduleModelType; + /** + * for fixed_week models this array contains exactly one week and week_number/name are omitted; for alternating_weeks models this array contains all configured weeks and each item includes week_number (0-based) and name + * + * @type {Array} + * @memberof WorkScheduleModel + */ + weeks: Array; + /** + * + * @type {WorkingTimeRules} + * @memberof WorkScheduleModel + */ + workingTimeRules: WorkingTimeRules | null; +} + + + +/** + * Check if a given object implements the WorkScheduleModel interface. + */ +export function instanceOfWorkScheduleModel(value: object): value is WorkScheduleModel { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('type' in value) || value['type'] === undefined) return false; + if (!('weeks' in value) || value['weeks'] === undefined) return false; + if (!('workingTimeRules' in value) || value['workingTimeRules'] === undefined) return false; + return true; +} + +export function WorkScheduleModelFromJSON(json: any): WorkScheduleModel { + return WorkScheduleModelFromJSONTyped(json, false); +} + +export function WorkScheduleModelFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkScheduleModel { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'type': WorkScheduleModelTypeFromJSON(json['type']), + 'weeks': ((json['weeks'] as Array).map(WorkScheduleModelWeekFromJSON)), + 'workingTimeRules': WorkingTimeRulesFromJSON(json['working_time_rules']), + }; +} + +export function WorkScheduleModelToJSON(json: any): WorkScheduleModel { + return WorkScheduleModelToJSONTyped(json, false); +} + +export function WorkScheduleModelToJSONTyped(value?: WorkScheduleModel | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'type': WorkScheduleModelTypeToJSON(value['type']), + 'weeks': ((value['weeks'] as Array).map(WorkScheduleModelWeekToJSON)), + 'working_time_rules': WorkingTimeRulesToJSON(value['workingTimeRules']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkScheduleModelPartial.ts b/sdk/typescript-fetch/src/models/WorkScheduleModelPartial.ts new file mode 100644 index 0000000..6aa23af --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkScheduleModelPartial.ts @@ -0,0 +1,75 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface WorkScheduleModelPartial + */ +export interface WorkScheduleModelPartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof WorkScheduleModelPartial + */ + id: string; + /** + * + * @type {string} + * @memberof WorkScheduleModelPartial + */ + name: string; +} + +/** + * Check if a given object implements the WorkScheduleModelPartial interface. + */ +export function instanceOfWorkScheduleModelPartial(value: object): value is WorkScheduleModelPartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + return true; +} + +export function WorkScheduleModelPartialFromJSON(json: any): WorkScheduleModelPartial { + return WorkScheduleModelPartialFromJSONTyped(json, false); +} + +export function WorkScheduleModelPartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkScheduleModelPartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + }; +} + +export function WorkScheduleModelPartialToJSON(json: any): WorkScheduleModelPartial { + return WorkScheduleModelPartialToJSONTyped(json, false); +} + +export function WorkScheduleModelPartialToJSONTyped(value?: WorkScheduleModelPartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkScheduleModelSortColumn.ts b/sdk/typescript-fetch/src/models/WorkScheduleModelSortColumn.ts new file mode 100644 index 0000000..8e508bc --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkScheduleModelSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Work Schedule Models. + * @export + */ +export const WorkScheduleModelSortColumn = { + Name: 'name' +} as const; +export type WorkScheduleModelSortColumn = typeof WorkScheduleModelSortColumn[keyof typeof WorkScheduleModelSortColumn]; + + +export function instanceOfWorkScheduleModelSortColumn(value: any): boolean { + for (const key in WorkScheduleModelSortColumn) { + if (Object.prototype.hasOwnProperty.call(WorkScheduleModelSortColumn, key)) { + if (WorkScheduleModelSortColumn[key as keyof typeof WorkScheduleModelSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function WorkScheduleModelSortColumnFromJSON(json: any): WorkScheduleModelSortColumn { + return WorkScheduleModelSortColumnFromJSONTyped(json, false); +} + +export function WorkScheduleModelSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkScheduleModelSortColumn { + return json as WorkScheduleModelSortColumn; +} + +export function WorkScheduleModelSortColumnToJSON(value?: WorkScheduleModelSortColumn | null): any { + return value as any; +} + +export function WorkScheduleModelSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): WorkScheduleModelSortColumn { + return value as WorkScheduleModelSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/WorkScheduleModelType.ts b/sdk/typescript-fetch/src/models/WorkScheduleModelType.ts new file mode 100644 index 0000000..7164664 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkScheduleModelType.ts @@ -0,0 +1,53 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * How the target working time of the model is defined. + * @export + */ +export const WorkScheduleModelType = { + DailyTargetHours: 'daily_target_hours', + NormalWorkingTime: 'normal_working_time' +} as const; +export type WorkScheduleModelType = typeof WorkScheduleModelType[keyof typeof WorkScheduleModelType]; + + +export function instanceOfWorkScheduleModelType(value: any): boolean { + for (const key in WorkScheduleModelType) { + if (Object.prototype.hasOwnProperty.call(WorkScheduleModelType, key)) { + if (WorkScheduleModelType[key as keyof typeof WorkScheduleModelType] === value) { + return true; + } + } + } + return false; +} + +export function WorkScheduleModelTypeFromJSON(json: any): WorkScheduleModelType { + return WorkScheduleModelTypeFromJSONTyped(json, false); +} + +export function WorkScheduleModelTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkScheduleModelType { + return json as WorkScheduleModelType; +} + +export function WorkScheduleModelTypeToJSON(value?: WorkScheduleModelType | null): any { + return value as any; +} + +export function WorkScheduleModelTypeToJSONTyped(value: any, ignoreDiscriminator: boolean): WorkScheduleModelType { + return value as WorkScheduleModelType; +} + diff --git a/sdk/typescript-fetch/src/models/WorkScheduleModelWeek.ts b/sdk/typescript-fetch/src/models/WorkScheduleModelWeek.ts new file mode 100644 index 0000000..b3665c1 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkScheduleModelWeek.ts @@ -0,0 +1,153 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DailyWorkSchedule } from './DailyWorkSchedule'; +import { + DailyWorkScheduleFromJSON, + DailyWorkScheduleFromJSONTyped, + DailyWorkScheduleToJSON, + DailyWorkScheduleToJSONTyped, +} from './DailyWorkSchedule'; + +/** + * + * @export + * @interface WorkScheduleModelWeek + */ +export interface WorkScheduleModelWeek { + /** + * index of the week in alternating_weeks models (0-based); omitted for fixed_week models + * @type {number} + * @memberof WorkScheduleModelWeek + */ + weekNumber?: number | null; + /** + * display name of the week in alternating_weeks models; omitted for fixed_week models + * @type {string} + * @memberof WorkScheduleModelWeek + */ + name?: string | null; + /** + * value in minutes + * @type {number} + * @memberof WorkScheduleModelWeek + */ + targetDurationWeeklyMinutes: number; + /** + * + * @type {DailyWorkSchedule} + * @memberof WorkScheduleModelWeek + */ + monday: DailyWorkSchedule; + /** + * + * @type {DailyWorkSchedule} + * @memberof WorkScheduleModelWeek + */ + tuesday: DailyWorkSchedule; + /** + * + * @type {DailyWorkSchedule} + * @memberof WorkScheduleModelWeek + */ + wednesday: DailyWorkSchedule; + /** + * + * @type {DailyWorkSchedule} + * @memberof WorkScheduleModelWeek + */ + thursday: DailyWorkSchedule; + /** + * + * @type {DailyWorkSchedule} + * @memberof WorkScheduleModelWeek + */ + friday: DailyWorkSchedule; + /** + * + * @type {DailyWorkSchedule} + * @memberof WorkScheduleModelWeek + */ + saturday: DailyWorkSchedule; + /** + * + * @type {DailyWorkSchedule} + * @memberof WorkScheduleModelWeek + */ + sunday: DailyWorkSchedule; +} + +/** + * Check if a given object implements the WorkScheduleModelWeek interface. + */ +export function instanceOfWorkScheduleModelWeek(value: object): value is WorkScheduleModelWeek { + if (!('targetDurationWeeklyMinutes' in value) || value['targetDurationWeeklyMinutes'] === undefined) return false; + if (!('monday' in value) || value['monday'] === undefined) return false; + if (!('tuesday' in value) || value['tuesday'] === undefined) return false; + if (!('wednesday' in value) || value['wednesday'] === undefined) return false; + if (!('thursday' in value) || value['thursday'] === undefined) return false; + if (!('friday' in value) || value['friday'] === undefined) return false; + if (!('saturday' in value) || value['saturday'] === undefined) return false; + if (!('sunday' in value) || value['sunday'] === undefined) return false; + return true; +} + +export function WorkScheduleModelWeekFromJSON(json: any): WorkScheduleModelWeek { + return WorkScheduleModelWeekFromJSONTyped(json, false); +} + +export function WorkScheduleModelWeekFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkScheduleModelWeek { + if (json == null) { + return json; + } + return { + + 'weekNumber': json['week_number'] == null ? undefined : json['week_number'], + 'name': json['name'] == null ? undefined : json['name'], + 'targetDurationWeeklyMinutes': json['target_duration_weekly_minutes'], + 'monday': DailyWorkScheduleFromJSON(json['monday']), + 'tuesday': DailyWorkScheduleFromJSON(json['tuesday']), + 'wednesday': DailyWorkScheduleFromJSON(json['wednesday']), + 'thursday': DailyWorkScheduleFromJSON(json['thursday']), + 'friday': DailyWorkScheduleFromJSON(json['friday']), + 'saturday': DailyWorkScheduleFromJSON(json['saturday']), + 'sunday': DailyWorkScheduleFromJSON(json['sunday']), + }; +} + +export function WorkScheduleModelWeekToJSON(json: any): WorkScheduleModelWeek { + return WorkScheduleModelWeekToJSONTyped(json, false); +} + +export function WorkScheduleModelWeekToJSONTyped(value?: WorkScheduleModelWeek | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'week_number': value['weekNumber'], + 'name': value['name'], + 'target_duration_weekly_minutes': value['targetDurationWeeklyMinutes'], + 'monday': DailyWorkScheduleToJSON(value['monday']), + 'tuesday': DailyWorkScheduleToJSON(value['tuesday']), + 'wednesday': DailyWorkScheduleToJSON(value['wednesday']), + 'thursday': DailyWorkScheduleToJSON(value['thursday']), + 'friday': DailyWorkScheduleToJSON(value['friday']), + 'saturday': DailyWorkScheduleToJSON(value['saturday']), + 'sunday': DailyWorkScheduleToJSON(value['sunday']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkScheduleModelsPage.ts b/sdk/typescript-fetch/src/models/WorkScheduleModelsPage.ts new file mode 100644 index 0000000..47d9d9b --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkScheduleModelsPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { WorkScheduleModel } from './WorkScheduleModel'; +import { + WorkScheduleModelFromJSON, + WorkScheduleModelFromJSONTyped, + WorkScheduleModelToJSON, + WorkScheduleModelToJSONTyped, +} from './WorkScheduleModel'; + +/** + * + * @export + * @interface WorkScheduleModelsPage + */ +export interface WorkScheduleModelsPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof WorkScheduleModelsPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof WorkScheduleModelsPage + */ + data: Array; +} + +/** + * Check if a given object implements the WorkScheduleModelsPage interface. + */ +export function instanceOfWorkScheduleModelsPage(value: object): value is WorkScheduleModelsPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function WorkScheduleModelsPageFromJSON(json: any): WorkScheduleModelsPage { + return WorkScheduleModelsPageFromJSONTyped(json, false); +} + +export function WorkScheduleModelsPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkScheduleModelsPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(WorkScheduleModelFromJSON)), + }; +} + +export function WorkScheduleModelsPageToJSON(json: any): WorkScheduleModelsPage { + return WorkScheduleModelsPageToJSONTyped(json, false); +} + +export function WorkScheduleModelsPageToJSONTyped(value?: WorkScheduleModelsPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(WorkScheduleModelToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTime.ts b/sdk/typescript-fetch/src/models/WorkingTime.ts new file mode 100644 index 0000000..3ee6650 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTime.ts @@ -0,0 +1,289 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { WorkingTimeDateSpanPartial } from './WorkingTimeDateSpanPartial'; +import { + WorkingTimeDateSpanPartialFromJSON, + WorkingTimeDateSpanPartialFromJSONTyped, + WorkingTimeDateSpanPartialToJSON, + WorkingTimeDateSpanPartialToJSONTyped, +} from './WorkingTimeDateSpanPartial'; +import type { Platform } from './Platform'; +import { + PlatformFromJSON, + PlatformFromJSONTyped, + PlatformToJSON, + PlatformToJSONTyped, +} from './Platform'; +import type { Duration } from './Duration'; +import { + DurationFromJSON, + DurationFromJSONTyped, + DurationToJSON, + DurationToJSONTyped, +} from './Duration'; +import type { WorkingTimeStatus } from './WorkingTimeStatus'; +import { + WorkingTimeStatusFromJSON, + WorkingTimeStatusFromJSONTyped, + WorkingTimeStatusToJSON, + WorkingTimeStatusToJSONTyped, +} from './WorkingTimeStatus'; +import type { BreakTime } from './BreakTime'; +import { + BreakTimeFromJSON, + BreakTimeFromJSONTyped, + BreakTimeToJSON, + BreakTimeToJSONTyped, +} from './BreakTime'; +import type { WorkingTimeTypePartial } from './WorkingTimeTypePartial'; +import { + WorkingTimeTypePartialFromJSON, + WorkingTimeTypePartialFromJSONTyped, + WorkingTimeTypePartialToJSON, + WorkingTimeTypePartialToJSONTyped, +} from './WorkingTimeTypePartial'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; +import type { Location } from './Location'; +import { + LocationFromJSON, + LocationFromJSONTyped, + LocationToJSON, + LocationToJSONTyped, +} from './Location'; + +/** + * One continuous stretch from `start` to `end`, classified by its `working_time_type`. Attendance entries carry `break_times`, locations and the platform they were recorded on; an entry derived from a multi-day absence links back to its `working_time_date_span`. + * + * @export + * @interface WorkingTime + */ +export interface WorkingTime { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof WorkingTime + */ + id: string; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof WorkingTime + */ + start: Date; + /** + * RFC 3339 date-time (ISO-8601) + * @type {Date} + * @memberof WorkingTime + */ + end: Date | null; + /** + * Read-only. Total break time in minutes. Values are calculated as an aggregate of other properties + * @type {number} + * @memberof WorkingTime + */ + breakTimeTotalMinutes: number; + /** + * + * @type {Array} + * @memberof WorkingTime + */ + breakTimes: Array; + /** + * + * @type {Duration} + * @memberof WorkingTime + */ + duration: Duration | null; + /** + * + * @type {boolean} + * @memberof WorkingTime + */ + changed: boolean; + /** + * + * @type {string} + * @memberof WorkingTime + */ + notes: string | null; + /** + * + * @type {UserPartial} + * @memberof WorkingTime + */ + user: UserPartial; + /** + * + * @type {WorkingTimeTypePartial} + * @memberof WorkingTime + */ + workingTimeType: WorkingTimeTypePartial; + /** + * + * @type {WorkingTimeDateSpanPartial} + * @memberof WorkingTime + */ + workingTimeDateSpan: WorkingTimeDateSpanPartial | null; + /** + * + * @type {Location} + * @memberof WorkingTime + */ + startLocation: Location | null; + /** + * + * @type {Location} + * @memberof WorkingTime + */ + endLocation: Location | null; + /** + * + * @type {Platform} + * @memberof WorkingTime + */ + startPlatform: Platform | null; + /** + * + * @type {Platform} + * @memberof WorkingTime + */ + endPlatform: Platform | null; + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof WorkingTime + */ + lastModified: Date; + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * + * @type {UserPartial} + * @memberof WorkingTime + */ + lastModifiedBy: UserPartial | null; + /** + * + * @type {WorkingTimeStatus} + * @memberof WorkingTime + */ + status: WorkingTimeStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof WorkingTime + */ + metadata?: { [key: string]: any; } | null; +} + + + +/** + * Check if a given object implements the WorkingTime interface. + */ +export function instanceOfWorkingTime(value: object): value is WorkingTime { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('start' in value) || value['start'] === undefined) return false; + if (!('end' in value) || value['end'] === undefined) return false; + if (!('breakTimeTotalMinutes' in value) || value['breakTimeTotalMinutes'] === undefined) return false; + if (!('breakTimes' in value) || value['breakTimes'] === undefined) return false; + if (!('duration' in value) || value['duration'] === undefined) return false; + if (!('changed' in value) || value['changed'] === undefined) return false; + if (!('notes' in value) || value['notes'] === undefined) return false; + if (!('user' in value) || value['user'] === undefined) return false; + if (!('workingTimeType' in value) || value['workingTimeType'] === undefined) return false; + if (!('workingTimeDateSpan' in value) || value['workingTimeDateSpan'] === undefined) return false; + if (!('startLocation' in value) || value['startLocation'] === undefined) return false; + if (!('endLocation' in value) || value['endLocation'] === undefined) return false; + if (!('startPlatform' in value) || value['startPlatform'] === undefined) return false; + if (!('endPlatform' in value) || value['endPlatform'] === undefined) return false; + if (!('lastModified' in value) || value['lastModified'] === undefined) return false; + if (!('lastModifiedBy' in value) || value['lastModifiedBy'] === undefined) return false; + if (!('status' in value) || value['status'] === undefined) return false; + return true; +} + +export function WorkingTimeFromJSON(json: any): WorkingTime { + return WorkingTimeFromJSONTyped(json, false); +} + +export function WorkingTimeFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTime { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'start': (new Date(json['start'])), + 'end': (json['end'] == null ? null : new Date(json['end'])), + 'breakTimeTotalMinutes': json['break_time_total_minutes'], + 'breakTimes': ((json['break_times'] as Array).map(BreakTimeFromJSON)), + 'duration': DurationFromJSON(json['duration']), + 'changed': json['changed'], + 'notes': json['notes'], + 'user': UserPartialFromJSON(json['user']), + 'workingTimeType': WorkingTimeTypePartialFromJSON(json['working_time_type']), + 'workingTimeDateSpan': WorkingTimeDateSpanPartialFromJSON(json['working_time_date_span']), + 'startLocation': LocationFromJSON(json['start_location']), + 'endLocation': LocationFromJSON(json['end_location']), + 'startPlatform': PlatformFromJSON(json['start_platform']), + 'endPlatform': PlatformFromJSON(json['end_platform']), + 'lastModified': (new Date(json['last_modified'])), + 'lastModifiedBy': UserPartialFromJSON(json['last_modified_by']), + 'status': WorkingTimeStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function WorkingTimeToJSON(json: any): WorkingTime { + return WorkingTimeToJSONTyped(json, false); +} + +export function WorkingTimeToJSONTyped(value?: WorkingTime | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'start': value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'break_time_total_minutes': value['breakTimeTotalMinutes'], + 'break_times': ((value['breakTimes'] as Array).map(BreakTimeToJSON)), + 'duration': DurationToJSON(value['duration']), + 'changed': value['changed'], + 'notes': value['notes'], + 'user': UserPartialToJSON(value['user']), + 'working_time_type': WorkingTimeTypePartialToJSON(value['workingTimeType']), + 'working_time_date_span': WorkingTimeDateSpanPartialToJSON(value['workingTimeDateSpan']), + 'start_location': LocationToJSON(value['startLocation']), + 'end_location': LocationToJSON(value['endLocation']), + 'start_platform': PlatformToJSON(value['startPlatform']), + 'end_platform': PlatformToJSON(value['endPlatform']), + 'last_modified': value['lastModified'].toISOString(), + 'last_modified_by': UserPartialToJSON(value['lastModifiedBy']), + 'status': WorkingTimeStatusToJSON(value['status']), + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeCreate.ts b/sdk/typescript-fetch/src/models/WorkingTimeCreate.ts new file mode 100644 index 0000000..ffad59a --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeCreate.ts @@ -0,0 +1,191 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DurationType } from './DurationType'; +import { + DurationTypeFromJSON, + DurationTypeFromJSONTyped, + DurationTypeToJSON, + DurationTypeToJSONTyped, +} from './DurationType'; +import type { LocationCreate } from './LocationCreate'; +import { + LocationCreateFromJSON, + LocationCreateFromJSONTyped, + LocationCreateToJSON, + LocationCreateToJSONTyped, +} from './LocationCreate'; +import type { BreakTimeUpdate } from './BreakTimeUpdate'; +import { + BreakTimeUpdateFromJSON, + BreakTimeUpdateFromJSONTyped, + BreakTimeUpdateToJSON, + BreakTimeUpdateToJSONTyped, +} from './BreakTimeUpdate'; +import type { WorkingTimeStatus } from './WorkingTimeStatus'; +import { + WorkingTimeStatusFromJSON, + WorkingTimeStatusFromJSONTyped, + WorkingTimeStatusToJSON, + WorkingTimeStatusToJSONTyped, +} from './WorkingTimeStatus'; + +/** + * + * @export + * @interface WorkingTimeCreate + */ +export interface WorkingTimeCreate { + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof WorkingTimeCreate + */ + start: Date; + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof WorkingTimeCreate + */ + end?: Date | null; + /** + * + * @type {Array} + * @memberof WorkingTimeCreate + */ + breakTimes?: Array; + /** + * Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @type {DurationType} + * @memberof WorkingTimeCreate + */ + durationType?: DurationType | null; + /** + * + * @type {boolean} + * @memberof WorkingTimeCreate + */ + changed: boolean; + /** + * + * @type {string} + * @memberof WorkingTimeCreate + */ + notes?: string | null; + /** + * + * @type {string} + * @memberof WorkingTimeCreate + */ + workingTimeTypeId: string; + /** + * + * @type {WorkingTimeStatus} + * @memberof WorkingTimeCreate + */ + status: WorkingTimeStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof WorkingTimeCreate + */ + metadata?: { [key: string]: any; } | null; + /** + * + * @type {string} + * @memberof WorkingTimeCreate + */ + userId: string; + /** + * + * @type {LocationCreate} + * @memberof WorkingTimeCreate + */ + startLocation?: LocationCreate | null; + /** + * + * @type {LocationCreate} + * @memberof WorkingTimeCreate + */ + endLocation?: LocationCreate | null; +} + + + +/** + * Check if a given object implements the WorkingTimeCreate interface. + */ +export function instanceOfWorkingTimeCreate(value: object): value is WorkingTimeCreate { + if (!('start' in value) || value['start'] === undefined) return false; + if (!('changed' in value) || value['changed'] === undefined) return false; + if (!('workingTimeTypeId' in value) || value['workingTimeTypeId'] === undefined) return false; + if (!('status' in value) || value['status'] === undefined) return false; + if (!('userId' in value) || value['userId'] === undefined) return false; + return true; +} + +export function WorkingTimeCreateFromJSON(json: any): WorkingTimeCreate { + return WorkingTimeCreateFromJSONTyped(json, false); +} + +export function WorkingTimeCreateFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeCreate { + if (json == null) { + return json; + } + return { + + 'start': (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'breakTimes': json['break_times'] == null ? undefined : ((json['break_times'] as Array).map(BreakTimeUpdateFromJSON)), + 'durationType': json['duration_type'] == null ? undefined : DurationTypeFromJSON(json['duration_type']), + 'changed': json['changed'], + 'notes': json['notes'] == null ? undefined : json['notes'], + 'workingTimeTypeId': json['working_time_type_id'], + 'status': WorkingTimeStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + 'userId': json['user_id'], + 'startLocation': json['start_location'] == null ? undefined : LocationCreateFromJSON(json['start_location']), + 'endLocation': json['end_location'] == null ? undefined : LocationCreateFromJSON(json['end_location']), + }; +} + +export function WorkingTimeCreateToJSON(json: any): WorkingTimeCreate { + return WorkingTimeCreateToJSONTyped(json, false); +} + +export function WorkingTimeCreateToJSONTyped(value?: WorkingTimeCreate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'break_times': value['breakTimes'] == null ? undefined : ((value['breakTimes'] as Array).map(BreakTimeUpdateToJSON)), + 'duration_type': DurationTypeToJSON(value['durationType']), + 'changed': value['changed'], + 'notes': value['notes'], + 'working_time_type_id': value['workingTimeTypeId'], + 'status': WorkingTimeStatusToJSON(value['status']), + 'metadata': value['metadata'], + 'user_id': value['userId'], + 'start_location': LocationCreateToJSON(value['startLocation']), + 'end_location': LocationCreateToJSON(value['endLocation']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeDateSpan.ts b/sdk/typescript-fetch/src/models/WorkingTimeDateSpan.ts new file mode 100644 index 0000000..37698a0 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeDateSpan.ts @@ -0,0 +1,181 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { WorkingTimeTypePartial } from './WorkingTimeTypePartial'; +import { + WorkingTimeTypePartialFromJSON, + WorkingTimeTypePartialFromJSONTyped, + WorkingTimeTypePartialToJSON, + WorkingTimeTypePartialToJSONTyped, +} from './WorkingTimeTypePartial'; +import type { UserPartial } from './UserPartial'; +import { + UserPartialFromJSON, + UserPartialFromJSONTyped, + UserPartialToJSON, + UserPartialToJSONTyped, +} from './UserPartial'; + +/** + * A span from `start` to `end` of a single `working_time_type`. Every working time derived for a covered day links back to it via `WorkingTime.working_time_date_span`. It can be created directly or become effective through an approved request. + * + * @export + * @interface WorkingTimeDateSpan + */ +export interface WorkingTimeDateSpan { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof WorkingTimeDateSpan + */ + id: string; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof WorkingTimeDateSpan + */ + start: Date; + /** + * Marks the first day of the working time date span as a half day. + * @type {boolean} + * @memberof WorkingTimeDateSpan + */ + startHalfDay: boolean; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof WorkingTimeDateSpan + */ + end: Date; + /** + * Marks the last day of the working time date span as a half day. + * @type {boolean} + * @memberof WorkingTimeDateSpan + */ + endHalfDay: boolean; + /** + * + * @type {string} + * @memberof WorkingTimeDateSpan + */ + notes: string | null; + /** + * + * @type {UserPartial} + * @memberof WorkingTimeDateSpan + */ + user: UserPartial; + /** + * + * @type {WorkingTimeTypePartial} + * @memberof WorkingTimeDateSpan + */ + workingTimeType: WorkingTimeTypePartial; + /** + * + * @type {UserPartial} + * @memberof WorkingTimeDateSpan + */ + substitute?: UserPartial | null; + /** + * Read-only. Automatically updated when the entity is persisted. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof WorkingTimeDateSpan + */ + lastModified: Date; + /** + * Read-only. The User who last modified the entry, or null if the change was not made in a user context. + * + * @type {UserPartial} + * @memberof WorkingTimeDateSpan + */ + lastModifiedBy: UserPartial | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof WorkingTimeDateSpan + */ + metadata?: { [key: string]: any; } | null; +} + +/** + * Check if a given object implements the WorkingTimeDateSpan interface. + */ +export function instanceOfWorkingTimeDateSpan(value: object): value is WorkingTimeDateSpan { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('start' in value) || value['start'] === undefined) return false; + if (!('startHalfDay' in value) || value['startHalfDay'] === undefined) return false; + if (!('end' in value) || value['end'] === undefined) return false; + if (!('endHalfDay' in value) || value['endHalfDay'] === undefined) return false; + if (!('notes' in value) || value['notes'] === undefined) return false; + if (!('user' in value) || value['user'] === undefined) return false; + if (!('workingTimeType' in value) || value['workingTimeType'] === undefined) return false; + if (!('lastModified' in value) || value['lastModified'] === undefined) return false; + if (!('lastModifiedBy' in value) || value['lastModifiedBy'] === undefined) return false; + return true; +} + +export function WorkingTimeDateSpanFromJSON(json: any): WorkingTimeDateSpan { + return WorkingTimeDateSpanFromJSONTyped(json, false); +} + +export function WorkingTimeDateSpanFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeDateSpan { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'start': (new Date(json['start'])), + 'startHalfDay': json['start_half_day'], + 'end': (new Date(json['end'])), + 'endHalfDay': json['end_half_day'], + 'notes': json['notes'], + 'user': UserPartialFromJSON(json['user']), + 'workingTimeType': WorkingTimeTypePartialFromJSON(json['working_time_type']), + 'substitute': json['substitute'] == null ? undefined : UserPartialFromJSON(json['substitute']), + 'lastModified': (new Date(json['last_modified'])), + 'lastModifiedBy': UserPartialFromJSON(json['last_modified_by']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function WorkingTimeDateSpanToJSON(json: any): WorkingTimeDateSpan { + return WorkingTimeDateSpanToJSONTyped(json, false); +} + +export function WorkingTimeDateSpanToJSONTyped(value?: WorkingTimeDateSpan | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'start': value['start'].toISOString().substring(0,10), + 'start_half_day': value['startHalfDay'], + 'end': value['end'].toISOString().substring(0,10), + 'end_half_day': value['endHalfDay'], + 'notes': value['notes'], + 'user': UserPartialToJSON(value['user']), + 'working_time_type': WorkingTimeTypePartialToJSON(value['workingTimeType']), + 'substitute': UserPartialToJSON(value['substitute']), + 'last_modified': value['lastModified'].toISOString(), + 'last_modified_by': UserPartialToJSON(value['lastModifiedBy']), + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeDateSpanCreate.ts b/sdk/typescript-fetch/src/models/WorkingTimeDateSpanCreate.ts new file mode 100644 index 0000000..316f6a6 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeDateSpanCreate.ts @@ -0,0 +1,133 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface WorkingTimeDateSpanCreate + */ +export interface WorkingTimeDateSpanCreate { + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof WorkingTimeDateSpanCreate + */ + start: Date; + /** + * + * @type {boolean} + * @memberof WorkingTimeDateSpanCreate + */ + startHalfDay?: boolean; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof WorkingTimeDateSpanCreate + */ + end: Date; + /** + * + * @type {boolean} + * @memberof WorkingTimeDateSpanCreate + */ + endHalfDay?: boolean; + /** + * + * @type {string} + * @memberof WorkingTimeDateSpanCreate + */ + notes?: string | null; + /** + * + * @type {string} + * @memberof WorkingTimeDateSpanCreate + */ + workingTimeTypeId: string; + /** + * + * @type {string} + * @memberof WorkingTimeDateSpanCreate + */ + substituteId?: string | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof WorkingTimeDateSpanCreate + */ + metadata?: { [key: string]: any; } | null; + /** + * + * @type {string} + * @memberof WorkingTimeDateSpanCreate + */ + userId: string; +} + +/** + * Check if a given object implements the WorkingTimeDateSpanCreate interface. + */ +export function instanceOfWorkingTimeDateSpanCreate(value: object): value is WorkingTimeDateSpanCreate { + if (!('start' in value) || value['start'] === undefined) return false; + if (!('end' in value) || value['end'] === undefined) return false; + if (!('workingTimeTypeId' in value) || value['workingTimeTypeId'] === undefined) return false; + if (!('userId' in value) || value['userId'] === undefined) return false; + return true; +} + +export function WorkingTimeDateSpanCreateFromJSON(json: any): WorkingTimeDateSpanCreate { + return WorkingTimeDateSpanCreateFromJSONTyped(json, false); +} + +export function WorkingTimeDateSpanCreateFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeDateSpanCreate { + if (json == null) { + return json; + } + return { + + 'start': (new Date(json['start'])), + 'startHalfDay': json['start_half_day'] == null ? undefined : json['start_half_day'], + 'end': (new Date(json['end'])), + 'endHalfDay': json['end_half_day'] == null ? undefined : json['end_half_day'], + 'notes': json['notes'] == null ? undefined : json['notes'], + 'workingTimeTypeId': json['working_time_type_id'], + 'substituteId': json['substitute_id'] == null ? undefined : json['substitute_id'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + 'userId': json['user_id'], + }; +} + +export function WorkingTimeDateSpanCreateToJSON(json: any): WorkingTimeDateSpanCreate { + return WorkingTimeDateSpanCreateToJSONTyped(json, false); +} + +export function WorkingTimeDateSpanCreateToJSONTyped(value?: WorkingTimeDateSpanCreate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'].toISOString().substring(0,10), + 'start_half_day': value['startHalfDay'], + 'end': value['end'].toISOString().substring(0,10), + 'end_half_day': value['endHalfDay'], + 'notes': value['notes'], + 'working_time_type_id': value['workingTimeTypeId'], + 'substitute_id': value['substituteId'], + 'metadata': value['metadata'], + 'user_id': value['userId'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeDateSpanPage.ts b/sdk/typescript-fetch/src/models/WorkingTimeDateSpanPage.ts new file mode 100644 index 0000000..c8fd114 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeDateSpanPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { WorkingTimeDateSpan } from './WorkingTimeDateSpan'; +import { + WorkingTimeDateSpanFromJSON, + WorkingTimeDateSpanFromJSONTyped, + WorkingTimeDateSpanToJSON, + WorkingTimeDateSpanToJSONTyped, +} from './WorkingTimeDateSpan'; + +/** + * + * @export + * @interface WorkingTimeDateSpanPage + */ +export interface WorkingTimeDateSpanPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof WorkingTimeDateSpanPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof WorkingTimeDateSpanPage + */ + data: Array; +} + +/** + * Check if a given object implements the WorkingTimeDateSpanPage interface. + */ +export function instanceOfWorkingTimeDateSpanPage(value: object): value is WorkingTimeDateSpanPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function WorkingTimeDateSpanPageFromJSON(json: any): WorkingTimeDateSpanPage { + return WorkingTimeDateSpanPageFromJSONTyped(json, false); +} + +export function WorkingTimeDateSpanPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeDateSpanPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(WorkingTimeDateSpanFromJSON)), + }; +} + +export function WorkingTimeDateSpanPageToJSON(json: any): WorkingTimeDateSpanPage { + return WorkingTimeDateSpanPageToJSONTyped(json, false); +} + +export function WorkingTimeDateSpanPageToJSONTyped(value?: WorkingTimeDateSpanPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(WorkingTimeDateSpanToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeDateSpanPartial.ts b/sdk/typescript-fetch/src/models/WorkingTimeDateSpanPartial.ts new file mode 100644 index 0000000..fc914e5 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeDateSpanPartial.ts @@ -0,0 +1,67 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * References the date span this working time belongs to, if any. All working times generated for a date span reference the same span; working times recorded on their own have none. + * + * @export + * @interface WorkingTimeDateSpanPartial + */ +export interface WorkingTimeDateSpanPartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof WorkingTimeDateSpanPartial + */ + id: string; +} + +/** + * Check if a given object implements the WorkingTimeDateSpanPartial interface. + */ +export function instanceOfWorkingTimeDateSpanPartial(value: object): value is WorkingTimeDateSpanPartial { + if (!('id' in value) || value['id'] === undefined) return false; + return true; +} + +export function WorkingTimeDateSpanPartialFromJSON(json: any): WorkingTimeDateSpanPartial { + return WorkingTimeDateSpanPartialFromJSONTyped(json, false); +} + +export function WorkingTimeDateSpanPartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeDateSpanPartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + }; +} + +export function WorkingTimeDateSpanPartialToJSON(json: any): WorkingTimeDateSpanPartial { + return WorkingTimeDateSpanPartialToJSONTyped(json, false); +} + +export function WorkingTimeDateSpanPartialToJSONTyped(value?: WorkingTimeDateSpanPartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeDateSpanUpdate.ts b/sdk/typescript-fetch/src/models/WorkingTimeDateSpanUpdate.ts new file mode 100644 index 0000000..703c5f1 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeDateSpanUpdate.ts @@ -0,0 +1,121 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface WorkingTimeDateSpanUpdate + */ +export interface WorkingTimeDateSpanUpdate { + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof WorkingTimeDateSpanUpdate + */ + start?: Date; + /** + * + * @type {boolean} + * @memberof WorkingTimeDateSpanUpdate + */ + startHalfDay?: boolean; + /** + * RFC 3339 date (ISO-8601) + * @type {Date} + * @memberof WorkingTimeDateSpanUpdate + */ + end?: Date; + /** + * + * @type {boolean} + * @memberof WorkingTimeDateSpanUpdate + */ + endHalfDay?: boolean; + /** + * + * @type {string} + * @memberof WorkingTimeDateSpanUpdate + */ + notes?: string | null; + /** + * + * @type {string} + * @memberof WorkingTimeDateSpanUpdate + */ + workingTimeTypeId?: string; + /** + * + * @type {string} + * @memberof WorkingTimeDateSpanUpdate + */ + substituteId?: string | null; + /** + * + * @type {{ [key: string]: any; }} + * @memberof WorkingTimeDateSpanUpdate + */ + metadata?: { [key: string]: any; } | null; +} + +/** + * Check if a given object implements the WorkingTimeDateSpanUpdate interface. + */ +export function instanceOfWorkingTimeDateSpanUpdate(value: object): value is WorkingTimeDateSpanUpdate { + return true; +} + +export function WorkingTimeDateSpanUpdateFromJSON(json: any): WorkingTimeDateSpanUpdate { + return WorkingTimeDateSpanUpdateFromJSONTyped(json, false); +} + +export function WorkingTimeDateSpanUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeDateSpanUpdate { + if (json == null) { + return json; + } + return { + + 'start': json['start'] == null ? undefined : (new Date(json['start'])), + 'startHalfDay': json['start_half_day'] == null ? undefined : json['start_half_day'], + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'endHalfDay': json['end_half_day'] == null ? undefined : json['end_half_day'], + 'notes': json['notes'] == null ? undefined : json['notes'], + 'workingTimeTypeId': json['working_time_type_id'] == null ? undefined : json['working_time_type_id'], + 'substituteId': json['substitute_id'] == null ? undefined : json['substitute_id'], + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function WorkingTimeDateSpanUpdateToJSON(json: any): WorkingTimeDateSpanUpdate { + return WorkingTimeDateSpanUpdateToJSONTyped(json, false); +} + +export function WorkingTimeDateSpanUpdateToJSONTyped(value?: WorkingTimeDateSpanUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'] == null ? value['start'] : value['start'].toISOString().substring(0,10), + 'start_half_day': value['startHalfDay'], + 'end': value['end'] == null ? value['end'] : value['end'].toISOString().substring(0,10), + 'end_half_day': value['endHalfDay'], + 'notes': value['notes'], + 'working_time_type_id': value['workingTimeTypeId'], + 'substitute_id': value['substituteId'], + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeDateSpansSortColumn.ts b/sdk/typescript-fetch/src/models/WorkingTimeDateSpansSortColumn.ts new file mode 100644 index 0000000..94b3e61 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeDateSpansSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Working Time Date Spans. + * @export + */ +export const WorkingTimeDateSpansSortColumn = { + Start: 'start' +} as const; +export type WorkingTimeDateSpansSortColumn = typeof WorkingTimeDateSpansSortColumn[keyof typeof WorkingTimeDateSpansSortColumn]; + + +export function instanceOfWorkingTimeDateSpansSortColumn(value: any): boolean { + for (const key in WorkingTimeDateSpansSortColumn) { + if (Object.prototype.hasOwnProperty.call(WorkingTimeDateSpansSortColumn, key)) { + if (WorkingTimeDateSpansSortColumn[key as keyof typeof WorkingTimeDateSpansSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function WorkingTimeDateSpansSortColumnFromJSON(json: any): WorkingTimeDateSpansSortColumn { + return WorkingTimeDateSpansSortColumnFromJSONTyped(json, false); +} + +export function WorkingTimeDateSpansSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeDateSpansSortColumn { + return json as WorkingTimeDateSpansSortColumn; +} + +export function WorkingTimeDateSpansSortColumnToJSON(value?: WorkingTimeDateSpansSortColumn | null): any { + return value as any; +} + +export function WorkingTimeDateSpansSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): WorkingTimeDateSpansSortColumn { + return value as WorkingTimeDateSpansSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeRules.ts b/sdk/typescript-fetch/src/models/WorkingTimeRules.ts new file mode 100644 index 0000000..00b794c --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeRules.ts @@ -0,0 +1,75 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface WorkingTimeRules + */ +export interface WorkingTimeRules { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof WorkingTimeRules + */ + id: string; + /** + * + * @type {string} + * @memberof WorkingTimeRules + */ + name: string; +} + +/** + * Check if a given object implements the WorkingTimeRules interface. + */ +export function instanceOfWorkingTimeRules(value: object): value is WorkingTimeRules { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + return true; +} + +export function WorkingTimeRulesFromJSON(json: any): WorkingTimeRules { + return WorkingTimeRulesFromJSONTyped(json, false); +} + +export function WorkingTimeRulesFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeRules { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + }; +} + +export function WorkingTimeRulesToJSON(json: any): WorkingTimeRules { + return WorkingTimeRulesToJSONTyped(json, false); +} + +export function WorkingTimeRulesToJSONTyped(value?: WorkingTimeRules | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeStatus.ts b/sdk/typescript-fetch/src/models/WorkingTimeStatus.ts new file mode 100644 index 0000000..15b9931 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeStatus.ts @@ -0,0 +1,58 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Processing state of a Working Time. `running` and `paused` mean the recording is still open; from `changeable` on it is closed and progressively locked down as it is approved, closed and archived. + * @export + */ +export const WorkingTimeStatus = { + Running: 'running', + Paused: 'paused', + Changeable: 'changeable', + Locked: 'locked', + Approved: 'approved', + Closed: 'closed', + Archived: 'archived' +} as const; +export type WorkingTimeStatus = typeof WorkingTimeStatus[keyof typeof WorkingTimeStatus]; + + +export function instanceOfWorkingTimeStatus(value: any): boolean { + for (const key in WorkingTimeStatus) { + if (Object.prototype.hasOwnProperty.call(WorkingTimeStatus, key)) { + if (WorkingTimeStatus[key as keyof typeof WorkingTimeStatus] === value) { + return true; + } + } + } + return false; +} + +export function WorkingTimeStatusFromJSON(json: any): WorkingTimeStatus { + return WorkingTimeStatusFromJSONTyped(json, false); +} + +export function WorkingTimeStatusFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeStatus { + return json as WorkingTimeStatus; +} + +export function WorkingTimeStatusToJSON(value?: WorkingTimeStatus | null): any { + return value as any; +} + +export function WorkingTimeStatusToJSONTyped(value: any, ignoreDiscriminator: boolean): WorkingTimeStatus { + return value as WorkingTimeStatus; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeType.ts b/sdk/typescript-fetch/src/models/WorkingTimeType.ts new file mode 100644 index 0000000..f5a8cfc --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeType.ts @@ -0,0 +1,188 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DurationUnit } from './DurationUnit'; +import { + DurationUnitFromJSON, + DurationUnitFromJSONTyped, + DurationUnitToJSON, + DurationUnitToJSONTyped, +} from './DurationUnit'; +import type { RecordingModeUser } from './RecordingModeUser'; +import { + RecordingModeUserFromJSON, + RecordingModeUserFromJSONTyped, + RecordingModeUserToJSON, + RecordingModeUserToJSONTyped, +} from './RecordingModeUser'; +import type { WorkingTimeTypeCategory } from './WorkingTimeTypeCategory'; +import { + WorkingTimeTypeCategoryFromJSON, + WorkingTimeTypeCategoryFromJSONTyped, + WorkingTimeTypeCategoryToJSON, + WorkingTimeTypeCategoryToJSONTyped, +} from './WorkingTimeTypeCategory'; +import type { WorkingTimeTypeSubCategory } from './WorkingTimeTypeSubCategory'; +import { + WorkingTimeTypeSubCategoryFromJSON, + WorkingTimeTypeSubCategoryFromJSONTyped, + WorkingTimeTypeSubCategoryToJSON, + WorkingTimeTypeSubCategoryToJSONTyped, +} from './WorkingTimeTypeSubCategory'; + +/** + * A working time type. `category` and `sub_category` place it in the classification, `edit_unit` decides whether it is recorded by time or by day, and `requires_substitute` governs how it is recorded. + * + * @export + * @interface WorkingTimeType + */ +export interface WorkingTimeType { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof WorkingTimeType + */ + id: string; + /** + * + * @type {string} + * @memberof WorkingTimeType + */ + name: string; + /** + * + * @type {string} + * @memberof WorkingTimeType + */ + shortName: string | null; + /** + * + * @type {string} + * @memberof WorkingTimeType + */ + description: string | null; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof WorkingTimeType + */ + externalId: string | null; + /** + * + * @type {DurationUnit} + * @memberof WorkingTimeType + */ + editUnit: DurationUnit; + /** + * + * @type {WorkingTimeTypeCategory} + * @memberof WorkingTimeType + */ + category: WorkingTimeTypeCategory; + /** + * + * @type {WorkingTimeTypeSubCategory} + * @memberof WorkingTimeType + */ + subCategory: WorkingTimeTypeSubCategory | null; + /** + * Specifies how the user can record this working time type. + * + * @type {RecordingModeUser} + * @memberof WorkingTimeType + */ + recordingModeUser: RecordingModeUser; + /** + * + * @type {boolean} + * @memberof WorkingTimeType + */ + archived: boolean; + /** + * + * @type {boolean} + * @memberof WorkingTimeType + */ + requiresSubstitute?: boolean; +} + + + +/** + * Check if a given object implements the WorkingTimeType interface. + */ +export function instanceOfWorkingTimeType(value: object): value is WorkingTimeType { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('shortName' in value) || value['shortName'] === undefined) return false; + if (!('description' in value) || value['description'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + if (!('editUnit' in value) || value['editUnit'] === undefined) return false; + if (!('category' in value) || value['category'] === undefined) return false; + if (!('subCategory' in value) || value['subCategory'] === undefined) return false; + if (!('recordingModeUser' in value) || value['recordingModeUser'] === undefined) return false; + if (!('archived' in value) || value['archived'] === undefined) return false; + return true; +} + +export function WorkingTimeTypeFromJSON(json: any): WorkingTimeType { + return WorkingTimeTypeFromJSONTyped(json, false); +} + +export function WorkingTimeTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeType { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'shortName': json['short_name'], + 'description': json['description'], + 'externalId': json['external_id'], + 'editUnit': DurationUnitFromJSON(json['edit_unit']), + 'category': WorkingTimeTypeCategoryFromJSON(json['category']), + 'subCategory': WorkingTimeTypeSubCategoryFromJSON(json['sub_category']), + 'recordingModeUser': RecordingModeUserFromJSON(json['recording_mode_user']), + 'archived': json['archived'], + 'requiresSubstitute': json['requires_substitute'] == null ? undefined : json['requires_substitute'], + }; +} + +export function WorkingTimeTypeToJSON(json: any): WorkingTimeType { + return WorkingTimeTypeToJSONTyped(json, false); +} + +export function WorkingTimeTypeToJSONTyped(value?: WorkingTimeType | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'short_name': value['shortName'], + 'description': value['description'], + 'external_id': value['externalId'], + 'edit_unit': DurationUnitToJSON(value['editUnit']), + 'category': WorkingTimeTypeCategoryToJSON(value['category']), + 'sub_category': WorkingTimeTypeSubCategoryToJSON(value['subCategory']), + 'recording_mode_user': RecordingModeUserToJSON(value['recordingModeUser']), + 'archived': value['archived'], + 'requires_substitute': value['requiresSubstitute'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeTypeCategory.ts b/sdk/typescript-fetch/src/models/WorkingTimeTypeCategory.ts new file mode 100644 index 0000000..6d55067 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeTypeCategory.ts @@ -0,0 +1,57 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Category of a Working Time Type. `attendance_time` counts as time at work, the remaining categories describe kinds of absence. + * @export + */ +export const WorkingTimeTypeCategory = { + AttendanceTime: 'attendance_time', + Vacation: 'vacation', + PaidTimeOff: 'paid_time_off', + UnpaidTimeOff: 'unpaid_time_off', + Suspension: 'suspension', + BreakTime: 'break_time' +} as const; +export type WorkingTimeTypeCategory = typeof WorkingTimeTypeCategory[keyof typeof WorkingTimeTypeCategory]; + + +export function instanceOfWorkingTimeTypeCategory(value: any): boolean { + for (const key in WorkingTimeTypeCategory) { + if (Object.prototype.hasOwnProperty.call(WorkingTimeTypeCategory, key)) { + if (WorkingTimeTypeCategory[key as keyof typeof WorkingTimeTypeCategory] === value) { + return true; + } + } + } + return false; +} + +export function WorkingTimeTypeCategoryFromJSON(json: any): WorkingTimeTypeCategory { + return WorkingTimeTypeCategoryFromJSONTyped(json, false); +} + +export function WorkingTimeTypeCategoryFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeTypeCategory { + return json as WorkingTimeTypeCategory; +} + +export function WorkingTimeTypeCategoryToJSON(value?: WorkingTimeTypeCategory | null): any { + return value as any; +} + +export function WorkingTimeTypeCategoryToJSONTyped(value: any, ignoreDiscriminator: boolean): WorkingTimeTypeCategory { + return value as WorkingTimeTypeCategory; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeTypePartial.ts b/sdk/typescript-fetch/src/models/WorkingTimeTypePartial.ts new file mode 100644 index 0000000..5dba600 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeTypePartial.ts @@ -0,0 +1,84 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +/** + * + * @export + * @interface WorkingTimeTypePartial + */ +export interface WorkingTimeTypePartial { + /** + * Unique identifier. Treat it as an opaque string. + * @type {string} + * @memberof WorkingTimeTypePartial + */ + id: string; + /** + * + * @type {string} + * @memberof WorkingTimeTypePartial + */ + name: string; + /** + * Identifier of the corresponding object in an external system. Set and owned by the client. + * @type {string} + * @memberof WorkingTimeTypePartial + */ + externalId: string | null; +} + +/** + * Check if a given object implements the WorkingTimeTypePartial interface. + */ +export function instanceOfWorkingTimeTypePartial(value: object): value is WorkingTimeTypePartial { + if (!('id' in value) || value['id'] === undefined) return false; + if (!('name' in value) || value['name'] === undefined) return false; + if (!('externalId' in value) || value['externalId'] === undefined) return false; + return true; +} + +export function WorkingTimeTypePartialFromJSON(json: any): WorkingTimeTypePartial { + return WorkingTimeTypePartialFromJSONTyped(json, false); +} + +export function WorkingTimeTypePartialFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeTypePartial { + if (json == null) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + 'externalId': json['external_id'], + }; +} + +export function WorkingTimeTypePartialToJSON(json: any): WorkingTimeTypePartial { + return WorkingTimeTypePartialToJSONTyped(json, false); +} + +export function WorkingTimeTypePartialToJSONTyped(value?: WorkingTimeTypePartial | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'id': value['id'], + 'name': value['name'], + 'external_id': value['externalId'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeTypeSubCategory.ts b/sdk/typescript-fetch/src/models/WorkingTimeTypeSubCategory.ts new file mode 100644 index 0000000..0bff70a --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeTypeSubCategory.ts @@ -0,0 +1,56 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Further classification of a Working Time Type within its category. + * @export + */ +export const WorkingTimeTypeSubCategory = { + Present: 'present', + WorkFromHome: 'work_from_home', + Away: 'away', + ActiveDrivingTime: 'active_driving_time', + PassiveTravellingTime: 'passive_travelling_time' +} as const; +export type WorkingTimeTypeSubCategory = typeof WorkingTimeTypeSubCategory[keyof typeof WorkingTimeTypeSubCategory]; + + +export function instanceOfWorkingTimeTypeSubCategory(value: any): boolean { + for (const key in WorkingTimeTypeSubCategory) { + if (Object.prototype.hasOwnProperty.call(WorkingTimeTypeSubCategory, key)) { + if (WorkingTimeTypeSubCategory[key as keyof typeof WorkingTimeTypeSubCategory] === value) { + return true; + } + } + } + return false; +} + +export function WorkingTimeTypeSubCategoryFromJSON(json: any): WorkingTimeTypeSubCategory { + return WorkingTimeTypeSubCategoryFromJSONTyped(json, false); +} + +export function WorkingTimeTypeSubCategoryFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeTypeSubCategory { + return json as WorkingTimeTypeSubCategory; +} + +export function WorkingTimeTypeSubCategoryToJSON(value?: WorkingTimeTypeSubCategory | null): any { + return value as any; +} + +export function WorkingTimeTypeSubCategoryToJSONTyped(value: any, ignoreDiscriminator: boolean): WorkingTimeTypeSubCategory { + return value as WorkingTimeTypeSubCategory; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeTypesPage.ts b/sdk/typescript-fetch/src/models/WorkingTimeTypesPage.ts new file mode 100644 index 0000000..5d7f337 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeTypesPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { WorkingTimeType } from './WorkingTimeType'; +import { + WorkingTimeTypeFromJSON, + WorkingTimeTypeFromJSONTyped, + WorkingTimeTypeToJSON, + WorkingTimeTypeToJSONTyped, +} from './WorkingTimeType'; + +/** + * + * @export + * @interface WorkingTimeTypesPage + */ +export interface WorkingTimeTypesPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof WorkingTimeTypesPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof WorkingTimeTypesPage + */ + data: Array; +} + +/** + * Check if a given object implements the WorkingTimeTypesPage interface. + */ +export function instanceOfWorkingTimeTypesPage(value: object): value is WorkingTimeTypesPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function WorkingTimeTypesPageFromJSON(json: any): WorkingTimeTypesPage { + return WorkingTimeTypesPageFromJSONTyped(json, false); +} + +export function WorkingTimeTypesPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeTypesPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(WorkingTimeTypeFromJSON)), + }; +} + +export function WorkingTimeTypesPageToJSON(json: any): WorkingTimeTypesPage { + return WorkingTimeTypesPageToJSONTyped(json, false); +} + +export function WorkingTimeTypesPageToJSONTyped(value?: WorkingTimeTypesPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(WorkingTimeTypeToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeTypesSortColumn.ts b/sdk/typescript-fetch/src/models/WorkingTimeTypesSortColumn.ts new file mode 100644 index 0000000..3c036e7 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeTypesSortColumn.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Working Time Types. + * @export + */ +export const WorkingTimeTypesSortColumn = { + Name: 'name' +} as const; +export type WorkingTimeTypesSortColumn = typeof WorkingTimeTypesSortColumn[keyof typeof WorkingTimeTypesSortColumn]; + + +export function instanceOfWorkingTimeTypesSortColumn(value: any): boolean { + for (const key in WorkingTimeTypesSortColumn) { + if (Object.prototype.hasOwnProperty.call(WorkingTimeTypesSortColumn, key)) { + if (WorkingTimeTypesSortColumn[key as keyof typeof WorkingTimeTypesSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function WorkingTimeTypesSortColumnFromJSON(json: any): WorkingTimeTypesSortColumn { + return WorkingTimeTypesSortColumnFromJSONTyped(json, false); +} + +export function WorkingTimeTypesSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeTypesSortColumn { + return json as WorkingTimeTypesSortColumn; +} + +export function WorkingTimeTypesSortColumnToJSON(value?: WorkingTimeTypesSortColumn | null): any { + return value as any; +} + +export function WorkingTimeTypesSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): WorkingTimeTypesSortColumn { + return value as WorkingTimeTypesSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeUpdate.ts b/sdk/typescript-fetch/src/models/WorkingTimeUpdate.ts new file mode 100644 index 0000000..89ff84c --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeUpdate.ts @@ -0,0 +1,178 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DurationType } from './DurationType'; +import { + DurationTypeFromJSON, + DurationTypeFromJSONTyped, + DurationTypeToJSON, + DurationTypeToJSONTyped, +} from './DurationType'; +import type { BreakTimeUpdate } from './BreakTimeUpdate'; +import { + BreakTimeUpdateFromJSON, + BreakTimeUpdateFromJSONTyped, + BreakTimeUpdateToJSON, + BreakTimeUpdateToJSONTyped, +} from './BreakTimeUpdate'; +import type { WorkingTimeStatus } from './WorkingTimeStatus'; +import { + WorkingTimeStatusFromJSON, + WorkingTimeStatusFromJSONTyped, + WorkingTimeStatusToJSON, + WorkingTimeStatusToJSONTyped, +} from './WorkingTimeStatus'; +import type { LocationUpdate } from './LocationUpdate'; +import { + LocationUpdateFromJSON, + LocationUpdateFromJSONTyped, + LocationUpdateToJSON, + LocationUpdateToJSONTyped, +} from './LocationUpdate'; + +/** + * + * @export + * @interface WorkingTimeUpdate + */ +export interface WorkingTimeUpdate { + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof WorkingTimeUpdate + */ + start?: Date; + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof WorkingTimeUpdate + */ + end?: Date | null; + /** + * + * @type {Array} + * @memberof WorkingTimeUpdate + */ + breakTimes?: Array; + /** + * Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @type {DurationType} + * @memberof WorkingTimeUpdate + */ + durationType?: DurationType | null; + /** + * + * @type {boolean} + * @memberof WorkingTimeUpdate + */ + changed?: boolean; + /** + * + * @type {string} + * @memberof WorkingTimeUpdate + */ + notes?: string | null; + /** + * + * @type {string} + * @memberof WorkingTimeUpdate + */ + workingTimeTypeId?: string; + /** + * + * @type {WorkingTimeStatus} + * @memberof WorkingTimeUpdate + */ + status?: WorkingTimeStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof WorkingTimeUpdate + */ + metadata?: { [key: string]: any; } | null; + /** + * + * @type {LocationUpdate} + * @memberof WorkingTimeUpdate + */ + startLocation?: LocationUpdate | null; + /** + * + * @type {LocationUpdate} + * @memberof WorkingTimeUpdate + */ + endLocation?: LocationUpdate | null; +} + + + +/** + * Check if a given object implements the WorkingTimeUpdate interface. + */ +export function instanceOfWorkingTimeUpdate(value: object): value is WorkingTimeUpdate { + return true; +} + +export function WorkingTimeUpdateFromJSON(json: any): WorkingTimeUpdate { + return WorkingTimeUpdateFromJSONTyped(json, false); +} + +export function WorkingTimeUpdateFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeUpdate { + if (json == null) { + return json; + } + return { + + 'start': json['start'] == null ? undefined : (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'breakTimes': json['break_times'] == null ? undefined : ((json['break_times'] as Array).map(BreakTimeUpdateFromJSON)), + 'durationType': json['duration_type'] == null ? undefined : DurationTypeFromJSON(json['duration_type']), + 'changed': json['changed'] == null ? undefined : json['changed'], + 'notes': json['notes'] == null ? undefined : json['notes'], + 'workingTimeTypeId': json['working_time_type_id'] == null ? undefined : json['working_time_type_id'], + 'status': json['status'] == null ? undefined : WorkingTimeStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + 'startLocation': json['start_location'] == null ? undefined : LocationUpdateFromJSON(json['start_location']), + 'endLocation': json['end_location'] == null ? undefined : LocationUpdateFromJSON(json['end_location']), + }; +} + +export function WorkingTimeUpdateToJSON(json: any): WorkingTimeUpdate { + return WorkingTimeUpdateToJSONTyped(json, false); +} + +export function WorkingTimeUpdateToJSONTyped(value?: WorkingTimeUpdate | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'] == null ? value['start'] : value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'break_times': value['breakTimes'] == null ? undefined : ((value['breakTimes'] as Array).map(BreakTimeUpdateToJSON)), + 'duration_type': DurationTypeToJSON(value['durationType']), + 'changed': value['changed'], + 'notes': value['notes'], + 'working_time_type_id': value['workingTimeTypeId'], + 'status': WorkingTimeStatusToJSON(value['status']), + 'metadata': value['metadata'], + 'start_location': LocationUpdateToJSON(value['startLocation']), + 'end_location': LocationUpdateToJSON(value['endLocation']), + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimeUpsert.ts b/sdk/typescript-fetch/src/models/WorkingTimeUpsert.ts new file mode 100644 index 0000000..57dc53b --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimeUpsert.ts @@ -0,0 +1,155 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { DurationType } from './DurationType'; +import { + DurationTypeFromJSON, + DurationTypeFromJSONTyped, + DurationTypeToJSON, + DurationTypeToJSONTyped, +} from './DurationType'; +import type { BreakTimeUpdate } from './BreakTimeUpdate'; +import { + BreakTimeUpdateFromJSON, + BreakTimeUpdateFromJSONTyped, + BreakTimeUpdateToJSON, + BreakTimeUpdateToJSONTyped, +} from './BreakTimeUpdate'; +import type { WorkingTimeStatus } from './WorkingTimeStatus'; +import { + WorkingTimeStatusFromJSON, + WorkingTimeStatusFromJSONTyped, + WorkingTimeStatusToJSON, + WorkingTimeStatusToJSONTyped, +} from './WorkingTimeStatus'; + +/** + * + * @export + * @interface WorkingTimeUpsert + */ +export interface WorkingTimeUpsert { + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `start` must be midnight (00:00) and on the same day as `end`. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof WorkingTimeUpsert + */ + start?: Date; + /** + * For WorkingTimeTypes with `edit_unit` `days` or `half_days`, `end` must be midnight (00:00) and on the same day as `start`. RFC 3339 date-time (ISO-8601) + * + * @type {Date} + * @memberof WorkingTimeUpsert + */ + end?: Date | null; + /** + * + * @type {Array} + * @memberof WorkingTimeUpsert + */ + breakTimes?: Array; + /** + * Must be specified for WorkingTimeTypes with `edit_unit` `days` or `half_days` only + * @type {DurationType} + * @memberof WorkingTimeUpsert + */ + durationType?: DurationType | null; + /** + * + * @type {boolean} + * @memberof WorkingTimeUpsert + */ + changed?: boolean; + /** + * + * @type {string} + * @memberof WorkingTimeUpsert + */ + notes?: string | null; + /** + * + * @type {string} + * @memberof WorkingTimeUpsert + */ + workingTimeTypeId?: string; + /** + * + * @type {WorkingTimeStatus} + * @memberof WorkingTimeUpsert + */ + status?: WorkingTimeStatus; + /** + * + * @type {{ [key: string]: any; }} + * @memberof WorkingTimeUpsert + */ + metadata?: { [key: string]: any; } | null; +} + + + +/** + * Check if a given object implements the WorkingTimeUpsert interface. + */ +export function instanceOfWorkingTimeUpsert(value: object): value is WorkingTimeUpsert { + return true; +} + +export function WorkingTimeUpsertFromJSON(json: any): WorkingTimeUpsert { + return WorkingTimeUpsertFromJSONTyped(json, false); +} + +export function WorkingTimeUpsertFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimeUpsert { + if (json == null) { + return json; + } + return { + + 'start': json['start'] == null ? undefined : (new Date(json['start'])), + 'end': json['end'] == null ? undefined : (new Date(json['end'])), + 'breakTimes': json['break_times'] == null ? undefined : ((json['break_times'] as Array).map(BreakTimeUpdateFromJSON)), + 'durationType': json['duration_type'] == null ? undefined : DurationTypeFromJSON(json['duration_type']), + 'changed': json['changed'] == null ? undefined : json['changed'], + 'notes': json['notes'] == null ? undefined : json['notes'], + 'workingTimeTypeId': json['working_time_type_id'] == null ? undefined : json['working_time_type_id'], + 'status': json['status'] == null ? undefined : WorkingTimeStatusFromJSON(json['status']), + 'metadata': json['metadata'] == null ? undefined : json['metadata'], + }; +} + +export function WorkingTimeUpsertToJSON(json: any): WorkingTimeUpsert { + return WorkingTimeUpsertToJSONTyped(json, false); +} + +export function WorkingTimeUpsertToJSONTyped(value?: WorkingTimeUpsert | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'start': value['start'] == null ? value['start'] : value['start'].toISOString(), + 'end': value['end'] == null ? value['end'] : value['end'].toISOString(), + 'break_times': value['breakTimes'] == null ? undefined : ((value['breakTimes'] as Array).map(BreakTimeUpdateToJSON)), + 'duration_type': DurationTypeToJSON(value['durationType']), + 'changed': value['changed'], + 'notes': value['notes'], + 'working_time_type_id': value['workingTimeTypeId'], + 'status': WorkingTimeStatusToJSON(value['status']), + 'metadata': value['metadata'], + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimesPage.ts b/sdk/typescript-fetch/src/models/WorkingTimesPage.ts new file mode 100644 index 0000000..eb3e518 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimesPage.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { mapValues } from '../runtime'; +import type { WorkingTime } from './WorkingTime'; +import { + WorkingTimeFromJSON, + WorkingTimeFromJSONTyped, + WorkingTimeToJSON, + WorkingTimeToJSONTyped, +} from './WorkingTime'; + +/** + * + * @export + * @interface WorkingTimesPage + */ +export interface WorkingTimesPage { + /** + * Token for the next page, or null when this is the last page. + * @type {string} + * @memberof WorkingTimesPage + */ + nextPageToken: string | null; + /** + * + * @type {Array} + * @memberof WorkingTimesPage + */ + data: Array; +} + +/** + * Check if a given object implements the WorkingTimesPage interface. + */ +export function instanceOfWorkingTimesPage(value: object): value is WorkingTimesPage { + if (!('nextPageToken' in value) || value['nextPageToken'] === undefined) return false; + if (!('data' in value) || value['data'] === undefined) return false; + return true; +} + +export function WorkingTimesPageFromJSON(json: any): WorkingTimesPage { + return WorkingTimesPageFromJSONTyped(json, false); +} + +export function WorkingTimesPageFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimesPage { + if (json == null) { + return json; + } + return { + + 'nextPageToken': json['next_page_token'], + 'data': ((json['data'] as Array).map(WorkingTimeFromJSON)), + }; +} + +export function WorkingTimesPageToJSON(json: any): WorkingTimesPage { + return WorkingTimesPageToJSONTyped(json, false); +} + +export function WorkingTimesPageToJSONTyped(value?: WorkingTimesPage | null, ignoreDiscriminator: boolean = false): any { + if (value == null) { + return value; + } + + return { + + 'next_page_token': value['nextPageToken'], + 'data': ((value['data'] as Array).map(WorkingTimeToJSON)), + }; +} + diff --git a/sdk/typescript-fetch/src/models/WorkingTimesSortColumn.ts b/sdk/typescript-fetch/src/models/WorkingTimesSortColumn.ts new file mode 100644 index 0000000..ff512c2 --- /dev/null +++ b/sdk/typescript-fetch/src/models/WorkingTimesSortColumn.ts @@ -0,0 +1,53 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +/** + * Sort property for Working Times. + * @export + */ +export const WorkingTimesSortColumn = { + Start: 'start', + LastModified: 'last_modified' +} as const; +export type WorkingTimesSortColumn = typeof WorkingTimesSortColumn[keyof typeof WorkingTimesSortColumn]; + + +export function instanceOfWorkingTimesSortColumn(value: any): boolean { + for (const key in WorkingTimesSortColumn) { + if (Object.prototype.hasOwnProperty.call(WorkingTimesSortColumn, key)) { + if (WorkingTimesSortColumn[key as keyof typeof WorkingTimesSortColumn] === value) { + return true; + } + } + } + return false; +} + +export function WorkingTimesSortColumnFromJSON(json: any): WorkingTimesSortColumn { + return WorkingTimesSortColumnFromJSONTyped(json, false); +} + +export function WorkingTimesSortColumnFromJSONTyped(json: any, ignoreDiscriminator: boolean): WorkingTimesSortColumn { + return json as WorkingTimesSortColumn; +} + +export function WorkingTimesSortColumnToJSON(value?: WorkingTimesSortColumn | null): any { + return value as any; +} + +export function WorkingTimesSortColumnToJSONTyped(value: any, ignoreDiscriminator: boolean): WorkingTimesSortColumn { + return value as WorkingTimesSortColumn; +} + diff --git a/sdk/typescript-fetch/src/models/index.ts b/sdk/typescript-fetch/src/models/index.ts new file mode 100644 index 0000000..7ff3575 --- /dev/null +++ b/sdk/typescript-fetch/src/models/index.ts @@ -0,0 +1,135 @@ +/* tslint:disable */ +/* eslint-disable */ +export * from './Accounts'; +export * from './BreakTime'; +export * from './BreakTimeAutomatic'; +export * from './BreakTimeBase'; +export * from './BreakTimeManual'; +export * from './BreakTimeOngoing'; +export * from './BreakTimeType'; +export * from './BreakTimeUpdate'; +export * from './BudgetPlanningType'; +export * from './BudgetPlanningTypeRequest'; +export * from './Car'; +export * from './CarCreate'; +export * from './CarPartial'; +export * from './CarUpdate'; +export * from './CarsPage'; +export * from './CarsSortColumn'; +export * from './DailyWorkSchedule'; +export * from './DeletedEntryPage'; +export * from './DeletedEntryPartial'; +export * from './DeletedEntrySortColumn'; +export * from './DeletedEntryWithMetadata'; +export * from './DeletedEntryWithMetadataPage'; +export * from './DriveLog'; +export * from './DriveLogCategoriesPage'; +export * from './DriveLogCategoriesSortColumn'; +export * from './DriveLogCategory'; +export * from './DriveLogCategoryPartial'; +export * from './DriveLogCreate'; +export * from './DriveLogStatus'; +export * from './DriveLogUpdate'; +export * from './DriveLogUpsert'; +export * from './DriveLogsPage'; +export * from './DriveLogsSortColumn'; +export * from './Duration'; +export * from './DurationType'; +export * from './DurationUnit'; +export * from './ErrorEntry'; +export * from './FlexTimeIndicator'; +export * from './Holiday'; +export * from './HolidayCalendarPartial'; +export * from './HolidayCalendarsPage'; +export * from './HolidayCalendarsSortColumn'; +export * from './HolidaysPage'; +export * from './HolidaysSortColumn'; +export * from './Location'; +export * from './LocationCreate'; +export * from './LocationUpdate'; +export * from './ModelError'; +export * from './NormalWorkingTimes'; +export * from './OvertimeSurchargeAccount'; +export * from './OvertimeSurchargeAccounts'; +export * from './OvertimeSurchargeRule'; +export * from './PagingInformation'; +export * from './Platform'; +export * from './ProblemDetail'; +export * from './ProjectTime'; +export * from './ProjectTimeCreate'; +export * from './ProjectTimeStatus'; +export * from './ProjectTimeUpdate'; +export * from './ProjectTimeUpsert'; +export * from './ProjectTimesPage'; +export * from './ProjectTimesSortColumn'; +export * from './RecordingLockType'; +export * from './RecordingModeUser'; +export * from './SortDirection'; +export * from './Task'; +export * from './TaskBase'; +export * from './TaskCreate'; +export * from './TaskLocation'; +export * from './TaskPartial'; +export * from './TaskReduced'; +export * from './TaskToLeaderAssignment'; +export * from './TaskToLeaderAssignmentsPage'; +export * from './TaskToLeaderAssignmentsSortColumn'; +export * from './TaskToTeamAssignment'; +export * from './TaskToTeamAssignmentsPage'; +export * from './TaskToTeamAssignmentsSortColumn'; +export * from './TaskToUserAssignment'; +export * from './TaskToUserAssignmentUpsert'; +export * from './TaskToUserAssignmentsPage'; +export * from './TaskToUserAssignmentsSortColumn'; +export * from './TaskUpdate'; +export * from './TasksPage'; +export * from './TasksReducedPage'; +export * from './TasksSortColumn'; +export * from './Team'; +export * from './TeamCreate'; +export * from './TeamPartial'; +export * from './TeamUpdate'; +export * from './TeamsPage'; +export * from './TeamsPartialPage'; +export * from './TeamsSortColumn'; +export * from './TimeAccount'; +export * from './User'; +export * from './UserCreate'; +export * from './UserPartial'; +export * from './UserUpdate'; +export * from './UsersPage'; +export * from './UsersPartialPage'; +export * from './UsersSortColumn'; +export * from './VacationAccount'; +export * from './VacationAccountBase'; +export * from './VacationAccountDays'; +export * from './VacationAccountMinutes'; +export * from './VacationUnit'; +export * from './VenuePartial'; +export * from './Waypoint'; +export * from './WorkScheduleModel'; +export * from './WorkScheduleModelPartial'; +export * from './WorkScheduleModelSortColumn'; +export * from './WorkScheduleModelType'; +export * from './WorkScheduleModelWeek'; +export * from './WorkScheduleModelsPage'; +export * from './WorkingTime'; +export * from './WorkingTimeCreate'; +export * from './WorkingTimeDateSpan'; +export * from './WorkingTimeDateSpanCreate'; +export * from './WorkingTimeDateSpanPage'; +export * from './WorkingTimeDateSpanPartial'; +export * from './WorkingTimeDateSpanUpdate'; +export * from './WorkingTimeDateSpansSortColumn'; +export * from './WorkingTimeRules'; +export * from './WorkingTimeStatus'; +export * from './WorkingTimeType'; +export * from './WorkingTimeTypeCategory'; +export * from './WorkingTimeTypePartial'; +export * from './WorkingTimeTypeSubCategory'; +export * from './WorkingTimeTypesPage'; +export * from './WorkingTimeTypesSortColumn'; +export * from './WorkingTimeUpdate'; +export * from './WorkingTimeUpsert'; +export * from './WorkingTimesPage'; +export * from './WorkingTimesSortColumn'; diff --git a/sdk/typescript-fetch/src/runtime.ts b/sdk/typescript-fetch/src/runtime.ts new file mode 100644 index 0000000..e3588c0 --- /dev/null +++ b/sdk/typescript-fetch/src/runtime.ts @@ -0,0 +1,449 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * timr API + * REST API for the timr time tracking service. It exposes the recordings a user makes (working times, project times, drive logs) together with the master data they refer to (users, teams, tasks, cars, working time types, work schedule models, holiday calendars). + * + * The version of the OpenAPI document: 1.0.0 + * Contact: info@timr.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +export const BASE_PATH = "https://api.timr.com/v1".replace(/\/+$/, ""); + +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | Promise | ((name: string) => string | Promise); // parameter for apiKey security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + set config(configuration: Configuration) { + this.configuration = configuration; + } + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI | undefined { + return this.configuration.fetchApi; + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string | Promise) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : async () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export const DefaultConfig = new Configuration(); + +/** + * This is the base class for all generated API classes. + */ +export class BaseAPI { + + private static readonly jsonRegex = /^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$/i; + private middleware: Middleware[]; + + constructor(protected configuration = DefaultConfig) { + this.middleware = configuration.middleware; + } + + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; + } + + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); + } + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + const middlewares = postMiddlewares.map((post) => ({ post })); + return this.withMiddleware(...middlewares); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + protected isJsonMime(mime: string | null | undefined): boolean { + if (!mime) { + return false; + } + return BaseAPI.jsonRegex.test(mime); + } + + protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { + const { url, init } = await this.createFetchParams(context, initOverrides); + const response = await this.fetchApi(url, init); + if (response && (response.status >= 200 && response.status < 300)) { + return response; + } + throw new ResponseError(response, 'Response returned an error code'); + } + + private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) { + let url = this.configuration.basePath + context.path; + if (context.query !== undefined && Object.keys(context.query).length !== 0) { + // only add the querystring to the URL if there are query parameters. + // this is done to avoid urls ending with a "?" character which buggy webservers + // do not handle correctly sometimes. + url += '?' + this.configuration.queryParamsStringify(context.query); + } + + const headers = Object.assign({}, this.configuration.headers, context.headers); + Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {}); + + const initOverrideFn = + typeof initOverrides === "function" + ? initOverrides + : async () => initOverrides; + + const initParams = { + method: context.method, + headers, + body: context.body, + credentials: this.configuration.credentials, + }; + + const overriddenInit: RequestInit = { + ...initParams, + ...(await initOverrideFn({ + init: initParams, + context, + })) + }; + + let body: any; + if (isFormData(overriddenInit.body) + || (overriddenInit.body instanceof URLSearchParams) + || isBlob(overriddenInit.body)) { + body = overriddenInit.body; + } else if (this.isJsonMime(headers['Content-Type'])) { + body = JSON.stringify(overriddenInit.body); + } else { + body = overriddenInit.body; + } + + const init: RequestInit = { + ...overriddenInit, + body + }; + + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response: Response | undefined = undefined; + try { + response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init); + } catch (e) { + for (const middleware of this.middleware) { + if (middleware.onError) { + response = await middleware.onError({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + error: e, + response: response ? response.clone() : undefined, + }) || response; + } + } + if (response === undefined) { + if (e instanceof Error) { + throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response'); + } else { + throw e; + } + } + } + for (const middleware of this.middleware) { + if (middleware.post) { + response = await middleware.post({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of `this` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; + +function isBlob(value: any): value is Blob { + return typeof Blob !== 'undefined' && value instanceof Blob; +} + +function isFormData(value: any): value is FormData { + return typeof FormData !== "undefined" && value instanceof FormData; +} + +export class ResponseError extends Error { + override name: "ResponseError" = "ResponseError"; + constructor(public response: Response, msg?: string) { + super(msg); + + // restore prototype chain + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } + } +} + +export class FetchError extends Error { + override name: "FetchError" = "FetchError"; + constructor(public cause: Error, msg?: string) { + super(msg); + + // restore prototype chain + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } + } +} + +export class RequiredError extends Error { + override name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + + // restore prototype chain + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } + } +} + +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; + +export type Json = any; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; +export type HTTPHeaders = { [key: string]: string }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | Set | HTTPQuery }; +export type HTTPBody = Json | FormData | URLSearchParams; +export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody }; +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; + +export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise + +export interface FetchParams { + url: string; + init: RequestInit; +} + +export interface RequestOpts { + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; +} + +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map(key => querystringSingleKey(key, params[key], prefix)) + .filter(part => part.length > 0) + .join('&'); +} + +function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array | Set | HTTPQuery, keyPrefix: string = ''): string { + const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key); + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(`&${encodeURIComponent(fullKey)}=`); + return `${encodeURIComponent(fullKey)}=${multiValue}`; + } + if (value instanceof Set) { + const valueAsArray = Array.from(value); + return querystringSingleKey(key, valueAsArray, keyPrefix); + } + if (value instanceof Date) { + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; +} + +export function exists(json: any, key: string) { + const value = json[key]; + return value !== null && value !== undefined; +} + +export function mapValues(data: any, fn: (item: any) => any) { + const result: { [key: string]: any } = {}; + for (const key of Object.keys(data)) { + result[key] = fn(data[key]); + } + return result; +} + +export function canConsumeForm(consumes: Consume[]): boolean { + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } + } + return false; +} + +export interface Consume { + contentType: string; +} + +export interface RequestContext { + fetch: FetchAPI; + url: string; + init: RequestInit; +} + +export interface ResponseContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; +} + +export interface ErrorContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + error: unknown; + response?: Response; +} + +export interface Middleware { + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; + onError?(context: ErrorContext): Promise; +} + +export interface ApiResponse { + raw: Response; + value(): Promise; +} + +export interface ResponseTransformer { + (json: any): T; +} + +export class JSONApiResponse { + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} + + async value(): Promise { + return this.transformer(await this.raw.json()); + } +} + +export class VoidApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return undefined; + } +} + +export class BlobApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.blob(); + }; +} + +export class TextApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.text(); + }; +} diff --git a/sdk/typescript-fetch/tsconfig.esm.json b/sdk/typescript-fetch/tsconfig.esm.json new file mode 100644 index 0000000..2c0331c --- /dev/null +++ b/sdk/typescript-fetch/tsconfig.esm.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "esnext", + "outDir": "dist/esm" + } +} diff --git a/sdk/typescript-fetch/tsconfig.json b/sdk/typescript-fetch/tsconfig.json new file mode 100644 index 0000000..250280d --- /dev/null +++ b/sdk/typescript-fetch/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es6", + "module": "commonjs", + "moduleResolution": "node", + "outDir": "dist", + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "dist", + "node_modules" + ] +} diff --git a/sdk/versions.properties b/sdk/versions.properties new file mode 100644 index 0000000..6175976 --- /dev/null +++ b/sdk/versions.properties @@ -0,0 +1,12 @@ +# The version of each published SDK. Each one describes its own surface: it moves when that SDK +# changes, and stands still when another one does. It is not derived from the specification version — +# a generator upgrade that renames a method, a language baseline that drops a runtime, or a package +# rename all break callers while the contract stands still, and a derived version has no way to say +# so. Which contract an SDK speaks is recorded at release time instead. See VERSIONING.md. +java-restclient=1.0.0 +java-resttemplate=1.0.0 +kotlin-okhttp=1.0.0 +python=1.0.0 +swift=1.0.0 +typescript-fetch=1.0.0 +dotnet=1.0.0 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..1b9f549 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,9 @@ +rootProject.name = 'timr-api' + +// Every directory under sdk/ with a build file is a module, named after the directory. +file('sdk').eachDir { dir -> + if (new File(dir, 'build.gradle').exists()) { + include dir.name + project(":${dir.name}").projectDir = dir + } +}