From 3338c7540bd959c01beedabb1caa25b9c62cffd7 Mon Sep 17 00:00:00 2001 From: speakeasybot Date: Mon, 25 Nov 2024 00:16:00 +0000 Subject: [PATCH] ci: regenerated with OpenAPI Doc , Speakeasy CLI 1.444.3 --- .speakeasy/gen.lock | 43 +- .speakeasy/workflow.lock | 29 + .speakeasy/workflow.yaml | 3 + README.md | 9 +- RELEASES.md | 12 +- docs/data-sources/price.md | 136 --- docs/data-sources/product.md | 162 ---- docs/data-sources/tax.md | 83 -- docs/index.md | 2 +- docs/resources/price.md | 206 ----- docs/resources/product.md | 243 ----- docs/resources/tax.md | 115 --- .../epilot-product_price/data-source.tf | 4 - .../epilot-product_product/data-source.tf | 4 - .../epilot-product_tax/data-source.tf | 4 - examples/provider/provider.tf | 2 +- .../resources/epilot-product_price/import.sh | 1 - .../epilot-product_price/resource.tf | 64 -- .../epilot-product_product/import.sh | 1 - .../epilot-product_product/resource.tf | 74 -- .../resources/epilot-product_tax/import.sh | 1 - .../resources/epilot-product_tax/resource.tf | 27 - gen.yaml | 4 +- go.mod | 5 +- go.sum | 2 - internal/provider/price_data_source.go | 406 --------- internal/provider/price_data_source_sdk.go | 238 ----- internal/provider/price_resource.go | 836 ------------------ internal/provider/price_resource_sdk.go | 788 ----------------- internal/provider/product_data_source.go | 366 -------- internal/provider/product_data_source_sdk.go | 213 ----- internal/provider/product_resource.go | 718 --------------- internal/provider/product_resource_sdk.go | 615 ------------- internal/provider/provider.go | 17 +- internal/provider/reflect/helpers.go | 2 +- internal/provider/tax_data_source.go | 262 ------ internal/provider/tax_data_source_sdk.go | 105 --- internal/provider/tax_resource.go | 506 ----------- internal/provider/tax_resource_sdk.go | 269 ------ internal/provider/types/base_entity_acl.go | 11 - internal/provider/types/base_entity_owner.go | 10 - internal/provider/types/base_relation.go | 7 - internal/provider/types/dollar_relation.go | 10 - .../types/price_component_relation.go | 10 - .../types/price_create_price_components.go | 7 - internal/provider/types/price_tier.go | 14 - internal/provider/utils.go | 185 ++++ internal/sdk/internal/utils/retries.go | 152 +++- internal/sdk/price.go | 487 ++-------- internal/sdk/product.go | 487 ++-------- internal/sdk/retry/config.go | 129 +++ internal/sdk/sdk.go | 5 +- internal/sdk/tax.go | 487 ++-------- 53 files changed, 768 insertions(+), 7810 deletions(-) create mode 100644 .speakeasy/workflow.lock delete mode 100644 docs/data-sources/price.md delete mode 100644 docs/data-sources/product.md delete mode 100644 docs/data-sources/tax.md delete mode 100644 docs/resources/price.md delete mode 100644 docs/resources/product.md delete mode 100644 docs/resources/tax.md delete mode 100644 examples/data-sources/epilot-product_price/data-source.tf delete mode 100644 examples/data-sources/epilot-product_product/data-source.tf delete mode 100644 examples/data-sources/epilot-product_tax/data-source.tf delete mode 100644 examples/resources/epilot-product_price/import.sh delete mode 100644 examples/resources/epilot-product_price/resource.tf delete mode 100644 examples/resources/epilot-product_product/import.sh delete mode 100644 examples/resources/epilot-product_product/resource.tf delete mode 100644 examples/resources/epilot-product_tax/import.sh delete mode 100644 examples/resources/epilot-product_tax/resource.tf delete mode 100644 internal/provider/price_data_source.go delete mode 100644 internal/provider/price_data_source_sdk.go delete mode 100644 internal/provider/price_resource.go delete mode 100644 internal/provider/price_resource_sdk.go delete mode 100644 internal/provider/product_data_source.go delete mode 100644 internal/provider/product_data_source_sdk.go delete mode 100644 internal/provider/product_resource.go delete mode 100644 internal/provider/product_resource_sdk.go delete mode 100644 internal/provider/tax_data_source.go delete mode 100644 internal/provider/tax_data_source_sdk.go delete mode 100644 internal/provider/tax_resource.go delete mode 100644 internal/provider/tax_resource_sdk.go delete mode 100644 internal/provider/types/base_entity_acl.go delete mode 100644 internal/provider/types/base_entity_owner.go delete mode 100644 internal/provider/types/base_relation.go delete mode 100644 internal/provider/types/dollar_relation.go delete mode 100644 internal/provider/types/price_component_relation.go delete mode 100644 internal/provider/types/price_create_price_components.go delete mode 100644 internal/provider/types/price_tier.go diff --git a/.speakeasy/gen.lock b/.speakeasy/gen.lock index 623235e..22a6e24 100755 --- a/.speakeasy/gen.lock +++ b/.speakeasy/gen.lock @@ -1,12 +1,12 @@ lockVersion: 2.0.0 id: 5a857039-7f4b-42d5-86fd-449767242ed2 management: - docChecksum: 9e3d08aa4c4e92fee60362eb116ea477 + docChecksum: 8fcb58bef3a7629c0383e8b5cb994341 docVersion: 1.0.0 - speakeasyVersion: 1.422.1 - generationVersion: 2.438.15 - releaseVersion: 0.11.5 - configChecksum: 2a1d7870feb5d7f02fd1530a5d48bc65 + speakeasyVersion: 1.444.3 + generationVersion: 2.461.4 + releaseVersion: 0.12.0 + configChecksum: 894c060a021a3bf4a06361a3eab946f9 repoURL: https://github.com/epilot-dev/terraform-provider-epilot-product.git repoSubDirectory: . published: true @@ -21,28 +21,18 @@ features: unions: 2.85.0 terraform: additionalDependencies: 0.1.0 - constsAndDefaults: 0.1.4 - core: 3.25.0 + constsAndDefaults: 0.2.0 + core: 3.26.3 envVarSecurityUsage: 0.1.0 globalSecurity: 2.81.9 globalServerURLs: 2.82.1 nullables: 0.0.0 - retries: 2.81.1 generatedFiles: - .gitattributes - CONTRIBUTING.md - USAGE.md - examples/README.md - - examples/data-sources/epilot-product_price/data-source.tf - - examples/data-sources/epilot-product_product/data-source.tf - - examples/data-sources/epilot-product_tax/data-source.tf - examples/provider/provider.tf - - examples/resources/epilot-product_price/import.sh - - examples/resources/epilot-product_price/resource.tf - - examples/resources/epilot-product_product/import.sh - - examples/resources/epilot-product_product/resource.tf - - examples/resources/epilot-product_tax/import.sh - - examples/resources/epilot-product_tax/resource.tf - go.mod - go.sum - internal/planmodifiers/boolplanmodifier/suppress_diff.go @@ -55,14 +45,6 @@ generatedFiles: - internal/planmodifiers/setplanmodifier/suppress_diff.go - internal/planmodifiers/stringplanmodifier/suppress_diff.go - internal/planmodifiers/utils/state_check.go - - internal/provider/price_data_source.go - - internal/provider/price_data_source_sdk.go - - internal/provider/price_resource.go - - internal/provider/price_resource_sdk.go - - internal/provider/product_data_source.go - - internal/provider/product_data_source_sdk.go - - internal/provider/product_resource.go - - internal/provider/product_resource_sdk.go - internal/provider/provider.go - internal/provider/reflect/diags.go - internal/provider/reflect/doc.go @@ -78,17 +60,6 @@ generatedFiles: - internal/provider/reflect/primitive.go - internal/provider/reflect/slice.go - internal/provider/reflect/struct.go - - internal/provider/tax_data_source.go - - internal/provider/tax_data_source_sdk.go - - internal/provider/tax_resource.go - - internal/provider/tax_resource_sdk.go - - internal/provider/types/base_entity_acl.go - - internal/provider/types/base_entity_owner.go - - internal/provider/types/base_relation.go - - internal/provider/types/dollar_relation.go - - internal/provider/types/price_component_relation.go - - internal/provider/types/price_create_price_components.go - - internal/provider/types/price_tier.go - internal/provider/utils.go - internal/sdk/.gitattributes - internal/sdk/.gitignore diff --git a/.speakeasy/workflow.lock b/.speakeasy/workflow.lock new file mode 100644 index 0000000..937a5d5 --- /dev/null +++ b/.speakeasy/workflow.lock @@ -0,0 +1,29 @@ +speakeasyVersion: 1.444.3 +sources: + my-source: + sourceNamespace: my-source + sourceRevisionDigest: sha256:d983953e2c04e1418ebf105c10f904ebfc8b6999a5a85289b31e6d08b4f43eb1 + sourceBlobDigest: sha256:c80aafb06ecac703c4330e1a09a87b8e6f8bf14a816ae0ab3674f561ba9459f9 + tags: + - latest + - speakeasy-sdk-regen-1730746369 + - 1.0.0 +targets: + terraform: + source: my-source + sourceNamespace: my-source + sourceRevisionDigest: sha256:d983953e2c04e1418ebf105c10f904ebfc8b6999a5a85289b31e6d08b4f43eb1 + sourceBlobDigest: sha256:c80aafb06ecac703c4330e1a09a87b8e6f8bf14a816ae0ab3674f561ba9459f9 +workflow: + workflowVersion: 1.0.0 + speakeasyVersion: latest + sources: + my-source: + inputs: + - location: https://docs.api.epilot.io/product.yaml + registry: + location: registry.speakeasyapi.dev/epilot/epilot/my-source + targets: + terraform: + target: terraform + source: my-source diff --git a/.speakeasy/workflow.yaml b/.speakeasy/workflow.yaml index 5634c6d..a229d2b 100644 --- a/.speakeasy/workflow.yaml +++ b/.speakeasy/workflow.yaml @@ -1,8 +1,11 @@ workflowVersion: 1.0.0 +speakeasyVersion: latest sources: my-source: inputs: - location: https://docs.api.epilot.io/product.yaml + registry: + location: registry.speakeasyapi.dev/epilot/epilot/my-source targets: terraform: target: terraform diff --git a/README.md b/README.md index 0fc7e8c..88ba532 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ terraform { required_providers { epilot-product = { source = "epilot-dev/epilot-product" - version = "0.11.5" + version = "0.12.0" } } } @@ -140,14 +140,7 @@ provider_installation { ### Resources -* [epilot-product_price](docs/resources/price.md) -* [epilot-product_product](docs/resources/product.md) -* [epilot-product_tax](docs/resources/tax.md) ### Data Sources - -* [epilot-product_price](docs/data-sources/price.md) -* [epilot-product_product](docs/data-sources/product.md) -* [epilot-product_tax](docs/data-sources/tax.md) diff --git a/RELEASES.md b/RELEASES.md index f4a2be8..571833b 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -14,4 +14,14 @@ Based on: - OpenAPI Doc 1.0.0 - Speakeasy CLI 1.147.0 (2.237.2) https://github.com/speakeasy-api/speakeasy ### Generated -- [terraform v0.4.4] . \ No newline at end of file +- [terraform v0.4.4] . + +## 2024-11-25 00:14:45 +### Changes +Based on: +- OpenAPI Doc +- Speakeasy CLI 1.444.3 (2.461.4) https://github.com/speakeasy-api/speakeasy +### Generated +- [terraform v0.12.0] . +### Releases +- [Terraform v0.12.0] https://registry.terraform.io/providers/epilot-dev/epilot-product/0.12.0 - . \ No newline at end of file diff --git a/docs/data-sources/price.md b/docs/data-sources/price.md deleted file mode 100644 index 9d535b2..0000000 --- a/docs/data-sources/price.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-product_price Data Source - terraform-provider-epilot-product" -subcategory: "" -description: |- - Price DataSource ---- - -# epilot-product_price (Data Source) - -Price DataSource - -## Example Usage - -```terraform -data "epilot-product_price" "my_price" { - hydrate = true - strict = true -} -``` - - -## Schema - -### Optional - -- `hydrate` (Boolean) Hydrates entities in relations when passed true -- `strict` (Boolean) When passed true, the response will contain only fields that match the schema, with non-matching fields included in `__additional` - -### Read-Only - -- `acl` (Attributes) Access control list (ACL) for an entity. Defines sharing access to external orgs or users. (see [below for nested schema](#nestedatt--acl)) -- `active` (Boolean) Whether the price can be used for new purchases. -- `additional` (Map of String) Additional fields that are not part of the schema -- `billing_duration_amount` (Number) The billing period duration -- `billing_duration_unit` (String) The billing period duration unit -- `created_at` (String) -- `description` (String) A brief description of the price. -- `files` (Attributes) (see [below for nested schema](#nestedatt--files)) -- `id` (String) The ID of this resource. -- `is_composite_price` (Boolean) The flag for prices that contain price components. -- `is_tax_inclusive` (Boolean) Specifies whether the price is considered `inclusive` of taxes or not. -- `long_description` (String) A detailed description of the price. This is shown on the order document and order table. Multi-line supported. -- `manifest` (List of String) Manifest ID used to create/update the entity -- `notice_time_amount` (Number) The notice period duration -- `notice_time_unit` (String) The notice period duration unit -- `org` (String) Organization Id the entity belongs to -- `owners` (Attributes List) (see [below for nested schema](#nestedatt--owners)) -- `price_components` (Attributes) A set of [price](/api/pricing#tag/simple_price_schema) components that define the composite price. (see [below for nested schema](#nestedatt--price_components)) -- `price_display_in_journeys` (String) Defines the way the price amount is display in epilot journeys. -- `pricing_model` (String) Describes how to compute the price per period. Either `per_unit`, `tiered_graduated` or `tiered_volume`. -- `per_unit` indicates that the fixed amount (specified in unit_amount or unit_amount_decimal) will be charged per unit in quantity -- `tiered_graduated` indicates that the unit pricing will be computed using tiers attribute. The customer pays the price per unit in every range their purchase rises through. -- `tiered_volume` indicates that the unit pricing will be computed using tiers attribute. The customer pays the same unit price for all purchased units. -- `tiered_flatfee` While similar to tiered_volume, tiered flat fee charges for the same price (flat) for the entire range instead using the unit price to multiply the quantity. -- `renewal_duration_amount` (Number) The renewal period duration -- `renewal_duration_unit` (String) The renewal period duration unit -- `schema` (String) -- `tags` (List of String) -- `tax` (String) Parsed as JSON. -- `termination_time_amount` (Number) The termination period duration -- `termination_time_unit` (String) The termination period duration unit -- `tiers` (Attributes List) Defines an array of tiers. Each tier has an upper bound, an unit amount and a flat fee. (see [below for nested schema](#nestedatt--tiers)) -- `title` (String) -- `type` (String) One of `one_time` or `recurring` depending on whether the price is for a one-time purchase or a recurring (subscription) purchase. -- `unit` (String) The unit of measurement used for display purposes and possibly for calculations when the price is variable. -- `unit_amount` (Number) The unit amount in cents to be charged, represented as a whole integer if possible. -- `unit_amount_currency` (String) Three-letter ISO currency code, in lowercase. -- `unit_amount_decimal` (String) The unit amount in cents to be charged, represented as a decimal string with at most 12 decimal places. -- `updated_at` (String) -- `variable_price` (Boolean) The flag for prices that can be influenced by external variables such as user input. - - -### Nested Schema for `acl` - -Read-Only: - -- `delete` (List of String) -- `edit` (List of String) -- `view` (List of String) - - - -### Nested Schema for `files` - -Read-Only: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--files--dollar_relation)) - - -### Nested Schema for `files.dollar_relation` - -Read-Only: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `owners` - -Read-Only: - -- `org_id` (String) -- `user_id` (String) - - - -### Nested Schema for `price_components` - -Read-Only: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--price_components--dollar_relation)) - - -### Nested Schema for `price_components.dollar_relation` - -Read-Only: - -- `entity_id` (String) The id of the price component -- `tags` (List of String) An arbitrary set of tags attached to the composite price - component relation - - - - -### Nested Schema for `tiers` - -Read-Only: - -- `display_mode` (String) -- `flat_fee_amount` (Number) -- `flat_fee_amount_decimal` (String) -- `unit_amount` (Number) -- `unit_amount_decimal` (String) -- `up_to` (Number) diff --git a/docs/data-sources/product.md b/docs/data-sources/product.md deleted file mode 100644 index 6257b48..0000000 --- a/docs/data-sources/product.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-product_product Data Source - terraform-provider-epilot-product" -subcategory: "" -description: |- - Product DataSource ---- - -# epilot-product_product (Data Source) - -Product DataSource - -## Example Usage - -```terraform -data "epilot-product_product" "my_product" { - hydrate = false - strict = true -} -``` - - -## Schema - -### Optional - -- `hydrate` (Boolean) Hydrates entities in relations when passed true -- `strict` (Boolean) When passed true, the response will contain only fields that match the schema, with non-matching fields included in `__additional` - -### Read-Only - -- `acl` (Attributes) Access control list (ACL) for an entity. Defines sharing access to external orgs or users. (see [below for nested schema](#nestedatt--acl)) -- `active` (Boolean) -- `additional` (Map of String) Additional fields that are not part of the schema -- `availability_files` (Attributes) (see [below for nested schema](#nestedatt--availability_files)) -- `code` (String) The product code -- `created_at` (String) -- `description` (String) A description of the product. Multi-line supported. -- `feature` (List of String) -- `files` (Attributes) (see [below for nested schema](#nestedatt--files)) -- `id` (String) The ID of this resource. -- `internal_name` (String) Not visible to customers, only in internal tables -- `manifest` (List of String) Manifest ID used to create/update the entity -- `name` (String) The description for the product -- `org` (String) Organization Id the entity belongs to -- `owners` (Attributes List) (see [below for nested schema](#nestedatt--owners)) -- `price_options` (Attributes) (see [below for nested schema](#nestedatt--price_options)) -- `product_downloads` (Attributes) (see [below for nested schema](#nestedatt--product_downloads)) -- `product_images` (Attributes) (see [below for nested schema](#nestedatt--product_images)) -- `purpose` (List of String) -- `schema` (String) -- `tags` (List of String) -- `title` (String) -- `type` (String) The type of Product: - -| type | description | -|----| ----| -| `product` | Represents a physical good | -| `service` | Represents a service or virtual product | -- `updated_at` (String) - - -### Nested Schema for `acl` - -Read-Only: - -- `delete` (List of String) -- `edit` (List of String) -- `view` (List of String) - - - -### Nested Schema for `availability_files` - -Read-Only: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--availability_files--dollar_relation)) - - -### Nested Schema for `availability_files.dollar_relation` - -Read-Only: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `files` - -Read-Only: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--files--dollar_relation)) - - -### Nested Schema for `files.dollar_relation` - -Read-Only: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `owners` - -Read-Only: - -- `org_id` (String) -- `user_id` (String) - - - -### Nested Schema for `price_options` - -Read-Only: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--price_options--dollar_relation)) - - -### Nested Schema for `price_options.dollar_relation` - -Read-Only: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `product_downloads` - -Read-Only: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--product_downloads--dollar_relation)) - - -### Nested Schema for `product_downloads.dollar_relation` - -Read-Only: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `product_images` - -Read-Only: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--product_images--dollar_relation)) - - -### Nested Schema for `product_images.dollar_relation` - -Read-Only: - -- `entity_id` (String) -- `tags` (List of String) diff --git a/docs/data-sources/tax.md b/docs/data-sources/tax.md deleted file mode 100644 index 1a5958a..0000000 --- a/docs/data-sources/tax.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-product_tax Data Source - terraform-provider-epilot-product" -subcategory: "" -description: |- - Tax DataSource ---- - -# epilot-product_tax (Data Source) - -Tax DataSource - -## Example Usage - -```terraform -data "epilot-product_tax" "my_tax" { - hydrate = true - strict = false -} -``` - - -## Schema - -### Optional - -- `hydrate` (Boolean) Hydrates entities in relations when passed true -- `strict` (Boolean) When passed true, the response will contain only fields that match the schema, with non-matching fields included in `__additional` - -### Read-Only - -- `acl` (Attributes) Access control list (ACL) for an entity. Defines sharing access to external orgs or users. (see [below for nested schema](#nestedatt--acl)) -- `active` (Boolean) -- `additional` (Map of String) Additional fields that are not part of the schema -- `created_at` (String) -- `description` (String) -- `files` (Attributes) (see [below for nested schema](#nestedatt--files)) -- `id` (String) The ID of this resource. -- `manifest` (List of String) Manifest ID used to create/update the entity -- `org` (String) Organization Id the entity belongs to -- `owners` (Attributes List) (see [below for nested schema](#nestedatt--owners)) -- `rate` (String) -- `region` (String) -- `schema` (String) -- `tags` (List of String) -- `title` (String) -- `type` (String) -- `updated_at` (String) - - -### Nested Schema for `acl` - -Read-Only: - -- `delete` (List of String) -- `edit` (List of String) -- `view` (List of String) - - - -### Nested Schema for `files` - -Read-Only: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--files--dollar_relation)) - - -### Nested Schema for `files.dollar_relation` - -Read-Only: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `owners` - -Read-Only: - -- `org_id` (String) -- `user_id` (String) diff --git a/docs/index.md b/docs/index.md index 93030b4..969846e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -17,7 +17,7 @@ terraform { required_providers { epilot-product = { source = "epilot-dev/epilot-product" - version = "0.11.5" + version = "0.12.0" } } } diff --git a/docs/resources/price.md b/docs/resources/price.md deleted file mode 100644 index fba1dde..0000000 --- a/docs/resources/price.md +++ /dev/null @@ -1,206 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-product_price Resource - terraform-provider-epilot-product" -subcategory: "" -description: |- - Price Resource ---- - -# epilot-product_price (Resource) - -Price Resource - -## Example Usage - -```terraform -resource "epilot-product_price" "my_price" { - active = true - additional = { - "see" : jsonencode("documentation"), - } - billing_duration_amount = 4.23 - billing_duration_unit = "years" - description = "...my_description..." - files = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - is_composite_price = true - is_tax_inclusive = false - long_description = "...my_long_description..." - manifest = [ - "123e4567-e89b-12d3-a456-426614174000" - ] - notice_time_amount = 7.88 - notice_time_unit = "weeks" - price_components = { - dollar_relation = [ - { - entity_id = "...my_entity_id..." - tags = [ - "..." - ] - } - ] - } - price_display_in_journeys = "show_price" - pricing_model = "tiered_graduated" - renewal_duration_amount = 3.79 - renewal_duration_unit = "years" - schema = "price" - tags = [ - "..." - ] - tax = "{ \"see\": \"documentation\" }" - termination_time_amount = 2.23 - termination_time_unit = "years" - tiers = [ - { - display_mode = "on_request" - flat_fee_amount = 1.58 - flat_fee_amount_decimal = "...my_flat_fee_amount_decimal..." - unit_amount = 4.92 - unit_amount_decimal = "...my_unit_amount_decimal..." - up_to = 5.32 - } - ] - type = "one_time" - unit = "...my_unit..." - unit_amount = 6.37 - unit_amount_currency = "EUR" - unit_amount_decimal = "...my_unit_amount_decimal..." - variable_price = false -} -``` - - -## Schema - -### Required - -- `active` (Boolean) Whether the price can be used for new purchases. -- `description` (String) A brief description of the price. - -### Optional - -- `additional` (Map of String) Additional fields that are not part of the schema -- `billing_duration_amount` (Number) The billing period duration -- `billing_duration_unit` (String) The billing period duration unit. must be one of ["weeks", "months", "years"] -- `files` (Attributes) (see [below for nested schema](#nestedatt--files)) -- `is_composite_price` (Boolean) The flag for prices that contain price components. -- `is_tax_inclusive` (Boolean) Specifies whether the price is considered `inclusive` of taxes or not. Default: false -- `long_description` (String) A detailed description of the price. This is shown on the order document and order table. Multi-line supported. -- `manifest` (List of String) Manifest ID used to create/update the entity -- `notice_time_amount` (Number) The notice period duration -- `notice_time_unit` (String) The notice period duration unit. must be one of ["weeks", "months", "years"] -- `price_components` (Attributes) A set of [price](/api/pricing#tag/simple_price_schema) components that define the composite price. (see [below for nested schema](#nestedatt--price_components)) -- `price_display_in_journeys` (String) Defines the way the price amount is display in epilot journeys. must be one of ["show_price", "show_as_starting_price", "show_as_on_request"] -- `pricing_model` (String) Describes how to compute the price per period. Either `per_unit`, `tiered_graduated` or `tiered_volume`. -- `per_unit` indicates that the fixed amount (specified in unit_amount or unit_amount_decimal) will be charged per unit in quantity -- `tiered_graduated` indicates that the unit pricing will be computed using tiers attribute. The customer pays the price per unit in every range their purchase rises through. -- `tiered_volume` indicates that the unit pricing will be computed using tiers attribute. The customer pays the same unit price for all purchased units. -- `tiered_flatfee` While similar to tiered_volume, tiered flat fee charges for the same price (flat) for the entire range instead using the unit price to multiply the quantity. -Default: "per_unit"; must be one of ["per_unit", "tiered_volume", "tiered_graduated", "tiered_flatfee"] -- `renewal_duration_amount` (Number) The renewal period duration -- `renewal_duration_unit` (String) The renewal period duration unit. must be one of ["weeks", "months", "years"] -- `schema` (String) must be "price" -- `tags` (List of String) -- `tax` (String) Parsed as JSON. -- `termination_time_amount` (Number) The termination period duration -- `termination_time_unit` (String) The termination period duration unit. must be one of ["weeks", "months", "years"] -- `tiers` (Attributes List) Defines an array of tiers. Each tier has an upper bound, an unit amount and a flat fee. (see [below for nested schema](#nestedatt--tiers)) -- `type` (String) One of `one_time` or `recurring` depending on whether the price is for a one-time purchase or a recurring (subscription) purchase. Default: "one_time"; must be one of ["one_time", "recurring"] -- `unit` (String) The unit of measurement used for display purposes and possibly for calculations when the price is variable. -- `unit_amount` (Number) The unit amount in cents to be charged, represented as a whole integer if possible. -- `unit_amount_currency` (String) Three-letter ISO currency code, in lowercase. -- `unit_amount_decimal` (String) The unit amount in cents to be charged, represented as a decimal string with at most 12 decimal places. -- `variable_price` (Boolean) The flag for prices that can be influenced by external variables such as user input. Default: false - -### Read-Only - -- `acl` (Attributes) Access control list (ACL) for an entity. Defines sharing access to external orgs or users. (see [below for nested schema](#nestedatt--acl)) -- `created_at` (String) -- `id` (String) The ID of this resource. -- `org` (String) Organization Id the entity belongs to -- `owners` (Attributes List) (see [below for nested schema](#nestedatt--owners)) -- `title` (String) -- `updated_at` (String) - - -### Nested Schema for `files` - -Optional: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--files--dollar_relation)) - - -### Nested Schema for `files.dollar_relation` - -Optional: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `price_components` - -Optional: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--price_components--dollar_relation)) - - -### Nested Schema for `price_components.dollar_relation` - -Optional: - -- `entity_id` (String) The id of the price component -- `tags` (List of String) An arbitrary set of tags attached to the composite price - component relation - - - - -### Nested Schema for `tiers` - -Optional: - -- `display_mode` (String) must be one of ["hidden", "on_request"] -- `flat_fee_amount` (Number) -- `flat_fee_amount_decimal` (String) -- `unit_amount` (Number) -- `unit_amount_decimal` (String) -- `up_to` (Number) - - - -### Nested Schema for `acl` - -Read-Only: - -- `delete` (List of String) -- `edit` (List of String) -- `view` (List of String) - - - -### Nested Schema for `owners` - -Read-Only: - -- `org_id` (String) -- `user_id` (String) - -## Import - -Import is supported using the following syntax: - -```shell -terraform import epilot-product_price.my_epilot-product_price "123e4567-e89b-12d3-a456-426614174000" -``` diff --git a/docs/resources/product.md b/docs/resources/product.md deleted file mode 100644 index 18b0d7d..0000000 --- a/docs/resources/product.md +++ /dev/null @@ -1,243 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-product_product Resource - terraform-provider-epilot-product" -subcategory: "" -description: |- - Product Resource ---- - -# epilot-product_product (Resource) - -Product Resource - -## Example Usage - -```terraform -resource "epilot-product_product" "my_product" { - active = false - additional = { - "see" : jsonencode("documentation"), - } - availability_files = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - code = "...my_code..." - description = "...my_description..." - feature = [ - "{ \"see\": \"documentation\" }" - ] - files = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - internal_name = "...my_internal_name..." - manifest = [ - "123e4567-e89b-12d3-a456-426614174000" - ] - name = "...my_name..." - price_options = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - product_downloads = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - product_images = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - purpose = [ - "..." - ] - schema = "product" - tags = [ - "..." - ] - type = "service" -} -``` - - -## Schema - -### Required - -- `active` (Boolean) -- `name` (String) The description for the product - -### Optional - -- `additional` (Map of String) Additional fields that are not part of the schema -- `availability_files` (Attributes) (see [below for nested schema](#nestedatt--availability_files)) -- `code` (String) The product code -- `description` (String) A description of the product. Multi-line supported. -- `feature` (List of String) -- `files` (Attributes) (see [below for nested schema](#nestedatt--files)) -- `internal_name` (String) Not visible to customers, only in internal tables -- `manifest` (List of String) Manifest ID used to create/update the entity -- `price_options` (Attributes) (see [below for nested schema](#nestedatt--price_options)) -- `product_downloads` (Attributes) (see [below for nested schema](#nestedatt--product_downloads)) -- `product_images` (Attributes) (see [below for nested schema](#nestedatt--product_images)) -- `purpose` (List of String) -- `schema` (String) must be "product" -- `tags` (List of String) -- `type` (String) The type of Product: - -| type | description | -|----| ----| -| `product` | Represents a physical good | -| `service` | Represents a service or virtual product | -Default: "product"; must be one of ["product", "service"] - -### Read-Only - -- `acl` (Attributes) Access control list (ACL) for an entity. Defines sharing access to external orgs or users. (see [below for nested schema](#nestedatt--acl)) -- `created_at` (String) -- `id` (String) The ID of this resource. -- `org` (String) Organization Id the entity belongs to -- `owners` (Attributes List) (see [below for nested schema](#nestedatt--owners)) -- `title` (String) -- `updated_at` (String) - - -### Nested Schema for `availability_files` - -Optional: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--availability_files--dollar_relation)) - - -### Nested Schema for `availability_files.dollar_relation` - -Optional: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `files` - -Optional: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--files--dollar_relation)) - - -### Nested Schema for `files.dollar_relation` - -Optional: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `price_options` - -Optional: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--price_options--dollar_relation)) - - -### Nested Schema for `price_options.dollar_relation` - -Optional: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `product_downloads` - -Optional: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--product_downloads--dollar_relation)) - - -### Nested Schema for `product_downloads.dollar_relation` - -Optional: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `product_images` - -Optional: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--product_images--dollar_relation)) - - -### Nested Schema for `product_images.dollar_relation` - -Optional: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `acl` - -Read-Only: - -- `delete` (List of String) -- `edit` (List of String) -- `view` (List of String) - - - -### Nested Schema for `owners` - -Read-Only: - -- `org_id` (String) -- `user_id` (String) - -## Import - -Import is supported using the following syntax: - -```shell -terraform import epilot-product_product.my_epilot-product_product "123e4567-e89b-12d3-a456-426614174000" -``` diff --git a/docs/resources/tax.md b/docs/resources/tax.md deleted file mode 100644 index a145bee..0000000 --- a/docs/resources/tax.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -# generated by https://github.com/hashicorp/terraform-plugin-docs -page_title: "epilot-product_tax Resource - terraform-provider-epilot-product" -subcategory: "" -description: |- - Tax Resource ---- - -# epilot-product_tax (Resource) - -Tax Resource - -## Example Usage - -```terraform -resource "epilot-product_tax" "my_tax" { - active = true - additional = { - "see" : jsonencode("documentation"), - } - description = "...my_description..." - files = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - manifest = [ - "123e4567-e89b-12d3-a456-426614174000" - ] - rate = "...my_rate..." - region = "DE" - schema = "tax" - tags = [ - "..." - ] - type = "VAT" -} -``` - - -## Schema - -### Required - -- `active` (Boolean) -- `rate` (String) -- `region` (String) -- `type` (String) must be one of ["VAT", "Custom"] - -### Optional - -- `additional` (Map of String) Additional fields that are not part of the schema -- `description` (String) -- `files` (Attributes) (see [below for nested schema](#nestedatt--files)) -- `manifest` (List of String) Manifest ID used to create/update the entity -- `schema` (String) must be "tax" -- `tags` (List of String) - -### Read-Only - -- `acl` (Attributes) Access control list (ACL) for an entity. Defines sharing access to external orgs or users. (see [below for nested schema](#nestedatt--acl)) -- `created_at` (String) -- `id` (String) The ID of this resource. -- `org` (String) Organization Id the entity belongs to -- `owners` (Attributes List) (see [below for nested schema](#nestedatt--owners)) -- `title` (String) -- `updated_at` (String) - - -### Nested Schema for `files` - -Optional: - -- `dollar_relation` (Attributes List) (see [below for nested schema](#nestedatt--files--dollar_relation)) - - -### Nested Schema for `files.dollar_relation` - -Optional: - -- `entity_id` (String) -- `tags` (List of String) - - - - -### Nested Schema for `acl` - -Read-Only: - -- `delete` (List of String) -- `edit` (List of String) -- `view` (List of String) - - - -### Nested Schema for `owners` - -Read-Only: - -- `org_id` (String) -- `user_id` (String) - -## Import - -Import is supported using the following syntax: - -```shell -terraform import epilot-product_tax.my_epilot-product_tax "123e4567-e89b-12d3-a456-426614174000" -``` diff --git a/examples/data-sources/epilot-product_price/data-source.tf b/examples/data-sources/epilot-product_price/data-source.tf deleted file mode 100644 index 7679bb2..0000000 --- a/examples/data-sources/epilot-product_price/data-source.tf +++ /dev/null @@ -1,4 +0,0 @@ -data "epilot-product_price" "my_price" { - hydrate = true - strict = true -} \ No newline at end of file diff --git a/examples/data-sources/epilot-product_product/data-source.tf b/examples/data-sources/epilot-product_product/data-source.tf deleted file mode 100644 index 6bc1187..0000000 --- a/examples/data-sources/epilot-product_product/data-source.tf +++ /dev/null @@ -1,4 +0,0 @@ -data "epilot-product_product" "my_product" { - hydrate = false - strict = true -} \ No newline at end of file diff --git a/examples/data-sources/epilot-product_tax/data-source.tf b/examples/data-sources/epilot-product_tax/data-source.tf deleted file mode 100644 index 5ba5bf4..0000000 --- a/examples/data-sources/epilot-product_tax/data-source.tf +++ /dev/null @@ -1,4 +0,0 @@ -data "epilot-product_tax" "my_tax" { - hydrate = true - strict = false -} \ No newline at end of file diff --git a/examples/provider/provider.tf b/examples/provider/provider.tf index fe62a14..99d85f7 100644 --- a/examples/provider/provider.tf +++ b/examples/provider/provider.tf @@ -2,7 +2,7 @@ terraform { required_providers { epilot-product = { source = "epilot-dev/epilot-product" - version = "0.11.5" + version = "0.12.0" } } } diff --git a/examples/resources/epilot-product_price/import.sh b/examples/resources/epilot-product_price/import.sh deleted file mode 100644 index c9cf333..0000000 --- a/examples/resources/epilot-product_price/import.sh +++ /dev/null @@ -1 +0,0 @@ -terraform import epilot-product_price.my_epilot-product_price "123e4567-e89b-12d3-a456-426614174000" diff --git a/examples/resources/epilot-product_price/resource.tf b/examples/resources/epilot-product_price/resource.tf deleted file mode 100644 index c5da90d..0000000 --- a/examples/resources/epilot-product_price/resource.tf +++ /dev/null @@ -1,64 +0,0 @@ -resource "epilot-product_price" "my_price" { - active = true - additional = { - "see" : jsonencode("documentation"), - } - billing_duration_amount = 4.23 - billing_duration_unit = "years" - description = "...my_description..." - files = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - is_composite_price = true - is_tax_inclusive = false - long_description = "...my_long_description..." - manifest = [ - "123e4567-e89b-12d3-a456-426614174000" - ] - notice_time_amount = 7.88 - notice_time_unit = "weeks" - price_components = { - dollar_relation = [ - { - entity_id = "...my_entity_id..." - tags = [ - "..." - ] - } - ] - } - price_display_in_journeys = "show_price" - pricing_model = "tiered_graduated" - renewal_duration_amount = 3.79 - renewal_duration_unit = "years" - schema = "price" - tags = [ - "..." - ] - tax = "{ \"see\": \"documentation\" }" - termination_time_amount = 2.23 - termination_time_unit = "years" - tiers = [ - { - display_mode = "on_request" - flat_fee_amount = 1.58 - flat_fee_amount_decimal = "...my_flat_fee_amount_decimal..." - unit_amount = 4.92 - unit_amount_decimal = "...my_unit_amount_decimal..." - up_to = 5.32 - } - ] - type = "one_time" - unit = "...my_unit..." - unit_amount = 6.37 - unit_amount_currency = "EUR" - unit_amount_decimal = "...my_unit_amount_decimal..." - variable_price = false -} \ No newline at end of file diff --git a/examples/resources/epilot-product_product/import.sh b/examples/resources/epilot-product_product/import.sh deleted file mode 100644 index 34d83f0..0000000 --- a/examples/resources/epilot-product_product/import.sh +++ /dev/null @@ -1 +0,0 @@ -terraform import epilot-product_product.my_epilot-product_product "123e4567-e89b-12d3-a456-426614174000" diff --git a/examples/resources/epilot-product_product/resource.tf b/examples/resources/epilot-product_product/resource.tf deleted file mode 100644 index 86d7381..0000000 --- a/examples/resources/epilot-product_product/resource.tf +++ /dev/null @@ -1,74 +0,0 @@ -resource "epilot-product_product" "my_product" { - active = false - additional = { - "see" : jsonencode("documentation"), - } - availability_files = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - code = "...my_code..." - description = "...my_description..." - feature = [ - "{ \"see\": \"documentation\" }" - ] - files = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - internal_name = "...my_internal_name..." - manifest = [ - "123e4567-e89b-12d3-a456-426614174000" - ] - name = "...my_name..." - price_options = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - product_downloads = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - product_images = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - purpose = [ - "..." - ] - schema = "product" - tags = [ - "..." - ] - type = "service" -} \ No newline at end of file diff --git a/examples/resources/epilot-product_tax/import.sh b/examples/resources/epilot-product_tax/import.sh deleted file mode 100644 index 1549643..0000000 --- a/examples/resources/epilot-product_tax/import.sh +++ /dev/null @@ -1 +0,0 @@ -terraform import epilot-product_tax.my_epilot-product_tax "123e4567-e89b-12d3-a456-426614174000" diff --git a/examples/resources/epilot-product_tax/resource.tf b/examples/resources/epilot-product_tax/resource.tf deleted file mode 100644 index 6936fa2..0000000 --- a/examples/resources/epilot-product_tax/resource.tf +++ /dev/null @@ -1,27 +0,0 @@ -resource "epilot-product_tax" "my_tax" { - active = true - additional = { - "see" : jsonencode("documentation"), - } - description = "...my_description..." - files = { - dollar_relation = [ - { - entity_id = "123e4567-e89b-12d3-a456-426614174000" - tags = [ - "..." - ] - } - ] - } - manifest = [ - "123e4567-e89b-12d3-a456-426614174000" - ] - rate = "...my_rate..." - region = "DE" - schema = "tax" - tags = [ - "..." - ] - type = "VAT" -} \ No newline at end of file diff --git a/gen.yaml b/gen.yaml index aa0026a..86778d4 100644 --- a/gen.yaml +++ b/gen.yaml @@ -9,6 +9,7 @@ generation: requestResponseComponentNamesFeb2024: false auth: oAuth2ClientCredentialsEnabled: false + oAuth2PasswordEnabled: false telemetryEnabled: false go: version: 0.0.1 @@ -27,12 +28,13 @@ go: outputModelSuffix: output packageName: openapi terraform: - version: 0.11.5 + version: 0.12.0 additionalDataSources: [] additionalDependencies: {} additionalResources: [] allowUnknownFieldsInWeakUnions: false author: epilot-dev + defaultErrorName: SDKError environmentVariables: [] imports: option: openapi diff --git a/go.mod b/go.mod index bd5408e..9b2bd44 100644 --- a/go.mod +++ b/go.mod @@ -3,12 +3,13 @@ module github.com/epilot-dev/terraform-provider-epilot-product go 1.22.0 require ( - github.com/cenkalti/backoff/v4 v4.2.0 github.com/ericlagergren/decimal v0.0.0-20221120152707-495c53812d05 + github.com/hashicorp/go-uuid v1.0.3 github.com/hashicorp/terraform-plugin-docs v0.19.4 github.com/hashicorp/terraform-plugin-framework v1.12.0 github.com/hashicorp/terraform-plugin-framework-validators v0.13.0 github.com/hashicorp/terraform-plugin-go v0.24.0 + github.com/hashicorp/terraform-plugin-log v0.9.0 ) require ( @@ -33,12 +34,10 @@ require ( github.com/hashicorp/go-hclog v1.5.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-plugin v1.6.1 // indirect - github.com/hashicorp/go-uuid v1.0.3 // indirect github.com/hashicorp/go-version v1.7.0 // indirect github.com/hashicorp/hc-install v0.7.0 // indirect github.com/hashicorp/terraform-exec v0.21.0 // indirect github.com/hashicorp/terraform-json v0.22.1 // indirect - github.com/hashicorp/terraform-plugin-log v0.9.0 // indirect github.com/hashicorp/terraform-registry-address v0.2.3 // indirect github.com/hashicorp/terraform-svchost v0.1.1 // indirect github.com/hashicorp/yamux v0.1.1 // indirect diff --git a/go.sum b/go.sum index f9e8505..762ad5a 100644 --- a/go.sum +++ b/go.sum @@ -24,8 +24,6 @@ github.com/bmatcuk/doublestar/v4 v4.6.1 h1:FH9SifrbvJhnlQpztAx++wlkk70QBf0iBWDwN github.com/bmatcuk/doublestar/v4 v4.6.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA= github.com/bufbuild/protocompile v0.4.0/go.mod h1:3v93+mbWn/v3xzN+31nwkJfrEpAUwp+BagBSZWx+TP8= -github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4= -github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU= github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA= github.com/cyphar/filepath-securejoin v0.2.4 h1:Ugdm7cg7i6ZK6x3xDF1oEu1nfkyfH53EtKeQYTC3kyg= diff --git a/internal/provider/price_data_source.go b/internal/provider/price_data_source.go deleted file mode 100644 index 1cbcf29..0000000 --- a/internal/provider/price_data_source.go +++ /dev/null @@ -1,406 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/operations" - "github.com/hashicorp/terraform-plugin-framework/datasource" - "github.com/hashicorp/terraform-plugin-framework/datasource/schema" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ datasource.DataSource = &PriceDataSource{} -var _ datasource.DataSourceWithConfigure = &PriceDataSource{} - -func NewPriceDataSource() datasource.DataSource { - return &PriceDataSource{} -} - -// PriceDataSource is the data source implementation. -type PriceDataSource struct { - client *sdk.SDK -} - -// PriceDataSourceModel describes the data model. -type PriceDataSourceModel struct { - ACL *tfTypes.BaseEntityACL `tfsdk:"acl"` - Active types.Bool `tfsdk:"active"` - Additional map[string]types.String `tfsdk:"additional"` - BillingDurationAmount types.Number `tfsdk:"billing_duration_amount"` - BillingDurationUnit types.String `tfsdk:"billing_duration_unit"` - CreatedAt types.String `tfsdk:"created_at"` - Description types.String `tfsdk:"description"` - Files *tfTypes.BaseRelation `tfsdk:"files"` - Hydrate types.Bool `tfsdk:"hydrate"` - ID types.String `tfsdk:"id"` - IsCompositePrice types.Bool `tfsdk:"is_composite_price"` - IsTaxInclusive types.Bool `tfsdk:"is_tax_inclusive"` - LongDescription types.String `tfsdk:"long_description"` - Manifest []types.String `tfsdk:"manifest"` - NoticeTimeAmount types.Number `tfsdk:"notice_time_amount"` - NoticeTimeUnit types.String `tfsdk:"notice_time_unit"` - Org types.String `tfsdk:"org"` - Owners []tfTypes.BaseEntityOwner `tfsdk:"owners"` - PriceComponents *tfTypes.PriceCreatePriceComponents `tfsdk:"price_components"` - PriceDisplayInJourneys types.String `tfsdk:"price_display_in_journeys"` - PricingModel types.String `tfsdk:"pricing_model"` - RenewalDurationAmount types.Number `tfsdk:"renewal_duration_amount"` - RenewalDurationUnit types.String `tfsdk:"renewal_duration_unit"` - Schema types.String `tfsdk:"schema"` - Strict types.Bool `tfsdk:"strict"` - Tags []types.String `tfsdk:"tags"` - Tax types.String `tfsdk:"tax"` - TerminationTimeAmount types.Number `tfsdk:"termination_time_amount"` - TerminationTimeUnit types.String `tfsdk:"termination_time_unit"` - Tiers []tfTypes.PriceTier `tfsdk:"tiers"` - Title types.String `tfsdk:"title"` - Type types.String `tfsdk:"type"` - Unit types.String `tfsdk:"unit"` - UnitAmount types.Number `tfsdk:"unit_amount"` - UnitAmountCurrency types.String `tfsdk:"unit_amount_currency"` - UnitAmountDecimal types.String `tfsdk:"unit_amount_decimal"` - UpdatedAt types.String `tfsdk:"updated_at"` - VariablePrice types.Bool `tfsdk:"variable_price"` -} - -// Metadata returns the data source type name. -func (r *PriceDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_price" -} - -// Schema defines the schema for the data source. -func (r *PriceDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "Price DataSource", - - Attributes: map[string]schema.Attribute{ - "acl": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "delete": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "edit": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "view": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - Description: `Access control list (ACL) for an entity. Defines sharing access to external orgs or users.`, - }, - "active": schema.BoolAttribute{ - Computed: true, - Description: `Whether the price can be used for new purchases.`, - }, - "additional": schema.MapAttribute{ - Computed: true, - ElementType: types.StringType, - Description: `Additional fields that are not part of the schema`, - }, - "billing_duration_amount": schema.NumberAttribute{ - Computed: true, - Description: `The billing period duration`, - }, - "billing_duration_unit": schema.StringAttribute{ - Computed: true, - Description: `The billing period duration unit`, - }, - "created_at": schema.StringAttribute{ - Computed: true, - }, - "description": schema.StringAttribute{ - Computed: true, - Description: `A brief description of the price.`, - }, - "files": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "hydrate": schema.BoolAttribute{ - Computed: true, - Optional: true, - Description: `Hydrates entities in relations when passed true`, - }, - "id": schema.StringAttribute{ - Computed: true, - }, - "is_composite_price": schema.BoolAttribute{ - Computed: true, - Description: `The flag for prices that contain price components.`, - }, - "is_tax_inclusive": schema.BoolAttribute{ - Computed: true, - Description: `Specifies whether the price is considered ` + "`" + `inclusive` + "`" + ` of taxes or not.`, - }, - "long_description": schema.StringAttribute{ - Computed: true, - Description: `A detailed description of the price. This is shown on the order document and order table. Multi-line supported.`, - }, - "manifest": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - Description: `Manifest ID used to create/update the entity`, - }, - "notice_time_amount": schema.NumberAttribute{ - Computed: true, - Description: `The notice period duration`, - }, - "notice_time_unit": schema.StringAttribute{ - Computed: true, - Description: `The notice period duration unit`, - }, - "org": schema.StringAttribute{ - Computed: true, - Description: `Organization Id the entity belongs to`, - }, - "owners": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "org_id": schema.StringAttribute{ - Computed: true, - }, - "user_id": schema.StringAttribute{ - Computed: true, - }, - }, - }, - }, - "price_components": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - Description: `The id of the price component`, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - Description: `An arbitrary set of tags attached to the composite price - component relation`, - }, - }, - }, - }, - }, - Description: `A set of [price](/api/pricing#tag/simple_price_schema) components that define the composite price.`, - }, - "price_display_in_journeys": schema.StringAttribute{ - Computed: true, - Description: `Defines the way the price amount is display in epilot journeys.`, - }, - "pricing_model": schema.StringAttribute{ - Computed: true, - MarkdownDescription: `Describes how to compute the price per period. Either ` + "`" + `per_unit` + "`" + `, ` + "`" + `tiered_graduated` + "`" + ` or ` + "`" + `tiered_volume` + "`" + `.` + "\n" + - `- ` + "`" + `per_unit` + "`" + ` indicates that the fixed amount (specified in unit_amount or unit_amount_decimal) will be charged per unit in quantity` + "\n" + - `- ` + "`" + `tiered_graduated` + "`" + ` indicates that the unit pricing will be computed using tiers attribute. The customer pays the price per unit in every range their purchase rises through.` + "\n" + - `- ` + "`" + `tiered_volume` + "`" + ` indicates that the unit pricing will be computed using tiers attribute. The customer pays the same unit price for all purchased units.` + "\n" + - `- ` + "`" + `tiered_flatfee` + "`" + ` While similar to tiered_volume, tiered flat fee charges for the same price (flat) for the entire range instead using the unit price to multiply the quantity.`, - }, - "renewal_duration_amount": schema.NumberAttribute{ - Computed: true, - Description: `The renewal period duration`, - }, - "renewal_duration_unit": schema.StringAttribute{ - Computed: true, - Description: `The renewal period duration unit`, - }, - "schema": schema.StringAttribute{ - Computed: true, - }, - "strict": schema.BoolAttribute{ - Computed: true, - Optional: true, - Description: `When passed true, the response will contain only fields that match the schema, with non-matching fields included in ` + "`" + `__additional` + "`" + ``, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "tax": schema.StringAttribute{ - Computed: true, - Description: `Parsed as JSON.`, - }, - "termination_time_amount": schema.NumberAttribute{ - Computed: true, - Description: `The termination period duration`, - }, - "termination_time_unit": schema.StringAttribute{ - Computed: true, - Description: `The termination period duration unit`, - }, - "tiers": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "display_mode": schema.StringAttribute{ - Computed: true, - }, - "flat_fee_amount": schema.NumberAttribute{ - Computed: true, - }, - "flat_fee_amount_decimal": schema.StringAttribute{ - Computed: true, - }, - "unit_amount": schema.NumberAttribute{ - Computed: true, - }, - "unit_amount_decimal": schema.StringAttribute{ - Computed: true, - }, - "up_to": schema.NumberAttribute{ - Computed: true, - }, - }, - }, - Description: `Defines an array of tiers. Each tier has an upper bound, an unit amount and a flat fee.`, - }, - "title": schema.StringAttribute{ - Computed: true, - }, - "type": schema.StringAttribute{ - Computed: true, - Description: `One of ` + "`" + `one_time` + "`" + ` or ` + "`" + `recurring` + "`" + ` depending on whether the price is for a one-time purchase or a recurring (subscription) purchase.`, - }, - "unit": schema.StringAttribute{ - Computed: true, - Description: `The unit of measurement used for display purposes and possibly for calculations when the price is variable.`, - }, - "unit_amount": schema.NumberAttribute{ - Computed: true, - Description: `The unit amount in cents to be charged, represented as a whole integer if possible.`, - }, - "unit_amount_currency": schema.StringAttribute{ - Computed: true, - Description: `Three-letter ISO currency code, in lowercase.`, - }, - "unit_amount_decimal": schema.StringAttribute{ - Computed: true, - Description: `The unit amount in cents to be charged, represented as a decimal string with at most 12 decimal places.`, - }, - "updated_at": schema.StringAttribute{ - Computed: true, - }, - "variable_price": schema.BoolAttribute{ - Computed: true, - Description: `The flag for prices that can be influenced by external variables such as user input.`, - }, - }, - } -} - -func (r *PriceDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected DataSource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *PriceDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { - var data *PriceDataSourceModel - var item types.Object - - resp.Diagnostics.Append(req.Config.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - hydrate := new(bool) - if !data.Hydrate.IsUnknown() && !data.Hydrate.IsNull() { - *hydrate = data.Hydrate.ValueBool() - } else { - hydrate = nil - } - var priceID string - priceID = data.ID.ValueString() - - strict := new(bool) - if !data.Strict.IsUnknown() && !data.Strict.IsNull() { - *strict = data.Strict.ValueBool() - } else { - strict = nil - } - request := operations.GetPriceRequest{ - Hydrate: hydrate, - PriceID: priceID, - Strict: strict, - } - res, err := r.client.Price.GetPrice(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Price != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedPrice(res.Price) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} diff --git a/internal/provider/price_data_source_sdk.go b/internal/provider/price_data_source_sdk.go deleted file mode 100644 index 0948099..0000000 --- a/internal/provider/price_data_source_sdk.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "encoding/json" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" - "math/big" - "time" -) - -func (r *PriceDataSourceModel) RefreshFromSharedPrice(resp *shared.Price) { - if resp != nil { - if len(resp.Additional) > 0 { - r.Additional = make(map[string]types.String) - for key, value := range resp.Additional { - result, _ := json.Marshal(value) - r.Additional[key] = types.StringValue(string(result)) - } - } - if resp.ACL == nil { - r.ACL = nil - } else { - r.ACL = &tfTypes.BaseEntityACL{} - r.ACL.Delete = []types.String{} - for _, v := range resp.ACL.Delete { - r.ACL.Delete = append(r.ACL.Delete, types.StringValue(v)) - } - r.ACL.Edit = []types.String{} - for _, v := range resp.ACL.Edit { - r.ACL.Edit = append(r.ACL.Edit, types.StringValue(v)) - } - r.ACL.View = []types.String{} - for _, v := range resp.ACL.View { - r.ACL.View = append(r.ACL.View, types.StringValue(v)) - } - } - if resp.CreatedAt != nil { - r.CreatedAt = types.StringValue(resp.CreatedAt.Format(time.RFC3339Nano)) - } else { - r.CreatedAt = types.StringNull() - } - if resp.Files == nil { - r.Files = nil - } else { - r.Files = &tfTypes.BaseRelation{} - r.Files.DollarRelation = []tfTypes.DollarRelation{} - if len(r.Files.DollarRelation) > len(resp.Files.DollarRelation) { - r.Files.DollarRelation = r.Files.DollarRelation[:len(resp.Files.DollarRelation)] - } - for dollarRelationCount, dollarRelationItem := range resp.Files.DollarRelation { - var dollarRelation1 tfTypes.DollarRelation - dollarRelation1.Tags = []types.String{} - for _, v := range dollarRelationItem.Tags { - dollarRelation1.Tags = append(dollarRelation1.Tags, types.StringValue(v)) - } - dollarRelation1.EntityID = types.StringPointerValue(dollarRelationItem.EntityID) - if dollarRelationCount+1 > len(r.Files.DollarRelation) { - r.Files.DollarRelation = append(r.Files.DollarRelation, dollarRelation1) - } else { - r.Files.DollarRelation[dollarRelationCount].Tags = dollarRelation1.Tags - r.Files.DollarRelation[dollarRelationCount].EntityID = dollarRelation1.EntityID - } - } - } - r.ID = types.StringPointerValue(resp.ID) - r.Manifest = []types.String{} - for _, v := range resp.Manifest { - r.Manifest = append(r.Manifest, types.StringValue(v)) - } - r.Org = types.StringValue(resp.Org) - r.Owners = []tfTypes.BaseEntityOwner{} - if len(r.Owners) > len(resp.Owners) { - r.Owners = r.Owners[:len(resp.Owners)] - } - for ownersCount, ownersItem := range resp.Owners { - var owners1 tfTypes.BaseEntityOwner - owners1.OrgID = types.StringValue(ownersItem.OrgID) - owners1.UserID = types.StringPointerValue(ownersItem.UserID) - if ownersCount+1 > len(r.Owners) { - r.Owners = append(r.Owners, owners1) - } else { - r.Owners[ownersCount].OrgID = owners1.OrgID - r.Owners[ownersCount].UserID = owners1.UserID - } - } - r.Schema = types.StringValue(string(resp.Schema)) - r.Tags = []types.String{} - for _, v := range resp.Tags { - r.Tags = append(r.Tags, types.StringValue(v)) - } - r.Title = types.StringPointerValue(resp.Title) - if resp.UpdatedAt != nil { - r.UpdatedAt = types.StringValue(resp.UpdatedAt.Format(time.RFC3339Nano)) - } else { - r.UpdatedAt = types.StringNull() - } - r.Active = types.BoolValue(resp.Active) - if resp.BillingDurationAmount != nil { - r.BillingDurationAmount = types.NumberValue(big.NewFloat(float64(*resp.BillingDurationAmount))) - } else { - r.BillingDurationAmount = types.NumberNull() - } - if resp.BillingDurationUnit != nil { - r.BillingDurationUnit = types.StringValue(string(*resp.BillingDurationUnit)) - } else { - r.BillingDurationUnit = types.StringNull() - } - r.Description = types.StringValue(resp.Description) - r.IsCompositePrice = types.BoolPointerValue(resp.IsCompositePrice) - r.IsTaxInclusive = types.BoolPointerValue(resp.IsTaxInclusive) - r.LongDescription = types.StringPointerValue(resp.LongDescription) - if resp.NoticeTimeAmount != nil { - r.NoticeTimeAmount = types.NumberValue(big.NewFloat(float64(*resp.NoticeTimeAmount))) - } else { - r.NoticeTimeAmount = types.NumberNull() - } - if resp.NoticeTimeUnit != nil { - r.NoticeTimeUnit = types.StringValue(string(*resp.NoticeTimeUnit)) - } else { - r.NoticeTimeUnit = types.StringNull() - } - if resp.PriceComponents == nil { - r.PriceComponents = nil - } else { - r.PriceComponents = &tfTypes.PriceCreatePriceComponents{} - r.PriceComponents.DollarRelation = []tfTypes.PriceComponentRelation{} - if len(r.PriceComponents.DollarRelation) > len(resp.PriceComponents.DollarRelation) { - r.PriceComponents.DollarRelation = r.PriceComponents.DollarRelation[:len(resp.PriceComponents.DollarRelation)] - } - for dollarRelationCount1, dollarRelationItem1 := range resp.PriceComponents.DollarRelation { - var dollarRelation3 tfTypes.PriceComponentRelation - dollarRelation3.Tags = []types.String{} - for _, v := range dollarRelationItem1.Tags { - dollarRelation3.Tags = append(dollarRelation3.Tags, types.StringValue(v)) - } - dollarRelation3.EntityID = types.StringPointerValue(dollarRelationItem1.EntityID) - if dollarRelationCount1+1 > len(r.PriceComponents.DollarRelation) { - r.PriceComponents.DollarRelation = append(r.PriceComponents.DollarRelation, dollarRelation3) - } else { - r.PriceComponents.DollarRelation[dollarRelationCount1].Tags = dollarRelation3.Tags - r.PriceComponents.DollarRelation[dollarRelationCount1].EntityID = dollarRelation3.EntityID - } - } - } - if resp.PriceDisplayInJourneys != nil { - r.PriceDisplayInJourneys = types.StringValue(string(*resp.PriceDisplayInJourneys)) - } else { - r.PriceDisplayInJourneys = types.StringNull() - } - if resp.PricingModel != nil { - r.PricingModel = types.StringValue(string(*resp.PricingModel)) - } else { - r.PricingModel = types.StringNull() - } - if resp.RenewalDurationAmount != nil { - r.RenewalDurationAmount = types.NumberValue(big.NewFloat(float64(*resp.RenewalDurationAmount))) - } else { - r.RenewalDurationAmount = types.NumberNull() - } - if resp.RenewalDurationUnit != nil { - r.RenewalDurationUnit = types.StringValue(string(*resp.RenewalDurationUnit)) - } else { - r.RenewalDurationUnit = types.StringNull() - } - if resp.Tax == nil { - r.Tax = types.StringNull() - } else { - taxResult, _ := json.Marshal(resp.Tax) - r.Tax = types.StringValue(string(taxResult)) - } - if resp.TerminationTimeAmount != nil { - r.TerminationTimeAmount = types.NumberValue(big.NewFloat(float64(*resp.TerminationTimeAmount))) - } else { - r.TerminationTimeAmount = types.NumberNull() - } - if resp.TerminationTimeUnit != nil { - r.TerminationTimeUnit = types.StringValue(string(*resp.TerminationTimeUnit)) - } else { - r.TerminationTimeUnit = types.StringNull() - } - r.Tiers = []tfTypes.PriceTier{} - if len(r.Tiers) > len(resp.Tiers) { - r.Tiers = r.Tiers[:len(resp.Tiers)] - } - for tiersCount, tiersItem := range resp.Tiers { - var tiers1 tfTypes.PriceTier - if tiersItem.DisplayMode != nil { - tiers1.DisplayMode = types.StringValue(string(*tiersItem.DisplayMode)) - } else { - tiers1.DisplayMode = types.StringNull() - } - if tiersItem.FlatFeeAmount != nil { - tiers1.FlatFeeAmount = types.NumberValue(big.NewFloat(float64(*tiersItem.FlatFeeAmount))) - } else { - tiers1.FlatFeeAmount = types.NumberNull() - } - tiers1.FlatFeeAmountDecimal = types.StringPointerValue(tiersItem.FlatFeeAmountDecimal) - if tiersItem.UnitAmount != nil { - tiers1.UnitAmount = types.NumberValue(big.NewFloat(float64(*tiersItem.UnitAmount))) - } else { - tiers1.UnitAmount = types.NumberNull() - } - tiers1.UnitAmountDecimal = types.StringPointerValue(tiersItem.UnitAmountDecimal) - if tiersItem.UpTo != nil { - tiers1.UpTo = types.NumberValue(big.NewFloat(float64(*tiersItem.UpTo))) - } else { - tiers1.UpTo = types.NumberNull() - } - if tiersCount+1 > len(r.Tiers) { - r.Tiers = append(r.Tiers, tiers1) - } else { - r.Tiers[tiersCount].DisplayMode = tiers1.DisplayMode - r.Tiers[tiersCount].FlatFeeAmount = tiers1.FlatFeeAmount - r.Tiers[tiersCount].FlatFeeAmountDecimal = tiers1.FlatFeeAmountDecimal - r.Tiers[tiersCount].UnitAmount = tiers1.UnitAmount - r.Tiers[tiersCount].UnitAmountDecimal = tiers1.UnitAmountDecimal - r.Tiers[tiersCount].UpTo = tiers1.UpTo - } - } - if resp.Type != nil { - r.Type = types.StringValue(string(*resp.Type)) - } else { - r.Type = types.StringNull() - } - r.Unit = types.StringPointerValue(resp.Unit) - if resp.UnitAmount != nil { - r.UnitAmount = types.NumberValue(big.NewFloat(float64(*resp.UnitAmount))) - } else { - r.UnitAmount = types.NumberNull() - } - r.UnitAmountCurrency = types.StringPointerValue(resp.UnitAmountCurrency) - r.UnitAmountDecimal = types.StringPointerValue(resp.UnitAmountDecimal) - r.VariablePrice = types.BoolPointerValue(resp.VariablePrice) - } -} diff --git a/internal/provider/price_resource.go b/internal/provider/price_resource.go deleted file mode 100644 index f49fd11..0000000 --- a/internal/provider/price_resource.go +++ /dev/null @@ -1,836 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - speakeasy_boolplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/boolplanmodifier" - speakeasy_listplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/listplanmodifier" - speakeasy_mapplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/mapplanmodifier" - speakeasy_numberplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/numberplanmodifier" - speakeasy_objectplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/objectplanmodifier" - speakeasy_stringplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/stringplanmodifier" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/operations" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/validators" - speakeasy_objectvalidators "github.com/epilot-dev/terraform-provider-epilot-product/internal/validators/objectvalidators" - "github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator" - "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" - "github.com/hashicorp/terraform-plugin-framework/path" - "github.com/hashicorp/terraform-plugin-framework/resource" - "github.com/hashicorp/terraform-plugin-framework/resource/schema" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" - "github.com/hashicorp/terraform-plugin-framework/schema/validator" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ resource.Resource = &PriceResource{} -var _ resource.ResourceWithImportState = &PriceResource{} - -func NewPriceResource() resource.Resource { - return &PriceResource{} -} - -// PriceResource defines the resource implementation. -type PriceResource struct { - client *sdk.SDK -} - -// PriceResourceModel describes the resource data model. -type PriceResourceModel struct { - ACL *tfTypes.BaseEntityACL `tfsdk:"acl"` - Active types.Bool `tfsdk:"active"` - Additional map[string]types.String `tfsdk:"additional"` - BillingDurationAmount types.Number `tfsdk:"billing_duration_amount"` - BillingDurationUnit types.String `tfsdk:"billing_duration_unit"` - CreatedAt types.String `tfsdk:"created_at"` - Description types.String `tfsdk:"description"` - Files *tfTypes.BaseRelation `tfsdk:"files"` - ID types.String `tfsdk:"id"` - IsCompositePrice types.Bool `tfsdk:"is_composite_price"` - IsTaxInclusive types.Bool `tfsdk:"is_tax_inclusive"` - LongDescription types.String `tfsdk:"long_description"` - Manifest []types.String `tfsdk:"manifest"` - NoticeTimeAmount types.Number `tfsdk:"notice_time_amount"` - NoticeTimeUnit types.String `tfsdk:"notice_time_unit"` - Org types.String `tfsdk:"org"` - Owners []tfTypes.BaseEntityOwner `tfsdk:"owners"` - PriceComponents *tfTypes.PriceCreatePriceComponents `tfsdk:"price_components"` - PriceDisplayInJourneys types.String `tfsdk:"price_display_in_journeys"` - PricingModel types.String `tfsdk:"pricing_model"` - RenewalDurationAmount types.Number `tfsdk:"renewal_duration_amount"` - RenewalDurationUnit types.String `tfsdk:"renewal_duration_unit"` - Schema types.String `tfsdk:"schema"` - Tags []types.String `tfsdk:"tags"` - Tax types.String `tfsdk:"tax"` - TerminationTimeAmount types.Number `tfsdk:"termination_time_amount"` - TerminationTimeUnit types.String `tfsdk:"termination_time_unit"` - Tiers []tfTypes.PriceTier `tfsdk:"tiers"` - Title types.String `tfsdk:"title"` - Type types.String `tfsdk:"type"` - Unit types.String `tfsdk:"unit"` - UnitAmount types.Number `tfsdk:"unit_amount"` - UnitAmountCurrency types.String `tfsdk:"unit_amount_currency"` - UnitAmountDecimal types.String `tfsdk:"unit_amount_decimal"` - UpdatedAt types.String `tfsdk:"updated_at"` - VariablePrice types.Bool `tfsdk:"variable_price"` -} - -func (r *PriceResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_price" -} - -func (r *PriceResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "Price Resource", - Attributes: map[string]schema.Attribute{ - "acl": schema.SingleNestedAttribute{ - Computed: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "delete": schema.ListAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "edit": schema.ListAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "view": schema.ListAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - Description: `Access control list (ACL) for an entity. Defines sharing access to external orgs or users.`, - }, - "active": schema.BoolAttribute{ - Required: true, - PlanModifiers: []planmodifier.Bool{ - speakeasy_boolplanmodifier.SuppressDiff(speakeasy_boolplanmodifier.ExplicitSuppress), - }, - Description: `Whether the price can be used for new purchases.`, - }, - "additional": schema.MapAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Map{ - speakeasy_mapplanmodifier.SuppressDiff(speakeasy_mapplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - Description: `Additional fields that are not part of the schema`, - Validators: []validator.Map{ - mapvalidator.ValueStringsAre(validators.IsValidJSON()), - }, - }, - "billing_duration_amount": schema.NumberAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Number{ - speakeasy_numberplanmodifier.SuppressDiff(speakeasy_numberplanmodifier.ExplicitSuppress), - }, - Description: `The billing period duration`, - }, - "billing_duration_unit": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `The billing period duration unit. must be one of ["weeks", "months", "years"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "weeks", - "months", - "years", - ), - }, - }, - "created_at": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Validators: []validator.String{ - validators.IsRFC3339(), - }, - }, - "description": schema.StringAttribute{ - Required: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `A brief description of the price.`, - }, - "files": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "id": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "is_composite_price": schema.BoolAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Bool{ - speakeasy_boolplanmodifier.SuppressDiff(speakeasy_boolplanmodifier.ExplicitSuppress), - }, - Description: `The flag for prices that contain price components.`, - }, - "is_tax_inclusive": schema.BoolAttribute{ - Computed: true, - Optional: true, - Default: booldefault.StaticBool(false), - PlanModifiers: []planmodifier.Bool{ - speakeasy_boolplanmodifier.SuppressDiff(speakeasy_boolplanmodifier.ExplicitSuppress), - }, - Description: `Specifies whether the price is considered ` + "`" + `inclusive` + "`" + ` of taxes or not. Default: false`, - }, - "long_description": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `A detailed description of the price. This is shown on the order document and order table. Multi-line supported.`, - }, - "manifest": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - Description: `Manifest ID used to create/update the entity`, - }, - "notice_time_amount": schema.NumberAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Number{ - speakeasy_numberplanmodifier.SuppressDiff(speakeasy_numberplanmodifier.ExplicitSuppress), - }, - Description: `The notice period duration`, - }, - "notice_time_unit": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `The notice period duration unit. must be one of ["weeks", "months", "years"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "weeks", - "months", - "years", - ), - }, - }, - "org": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Organization Id the entity belongs to`, - }, - "owners": schema.ListNestedAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "org_id": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "user_id": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - }, - }, - }, - "price_components": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `The id of the price component`, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - Description: `An arbitrary set of tags attached to the composite price - component relation`, - }, - }, - }, - }, - }, - Description: `A set of [price](/api/pricing#tag/simple_price_schema) components that define the composite price.`, - }, - "price_display_in_journeys": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Defines the way the price amount is display in epilot journeys. must be one of ["show_price", "show_as_starting_price", "show_as_on_request"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "show_price", - "show_as_starting_price", - "show_as_on_request", - ), - }, - }, - "pricing_model": schema.StringAttribute{ - Computed: true, - Optional: true, - Default: stringdefault.StaticString("per_unit"), - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - MarkdownDescription: `Describes how to compute the price per period. Either ` + "`" + `per_unit` + "`" + `, ` + "`" + `tiered_graduated` + "`" + ` or ` + "`" + `tiered_volume` + "`" + `.` + "\n" + - `- ` + "`" + `per_unit` + "`" + ` indicates that the fixed amount (specified in unit_amount or unit_amount_decimal) will be charged per unit in quantity` + "\n" + - `- ` + "`" + `tiered_graduated` + "`" + ` indicates that the unit pricing will be computed using tiers attribute. The customer pays the price per unit in every range their purchase rises through.` + "\n" + - `- ` + "`" + `tiered_volume` + "`" + ` indicates that the unit pricing will be computed using tiers attribute. The customer pays the same unit price for all purchased units.` + "\n" + - `- ` + "`" + `tiered_flatfee` + "`" + ` While similar to tiered_volume, tiered flat fee charges for the same price (flat) for the entire range instead using the unit price to multiply the quantity.` + "\n" + - `Default: "per_unit"; must be one of ["per_unit", "tiered_volume", "tiered_graduated", "tiered_flatfee"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "per_unit", - "tiered_volume", - "tiered_graduated", - "tiered_flatfee", - ), - }, - }, - "renewal_duration_amount": schema.NumberAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Number{ - speakeasy_numberplanmodifier.SuppressDiff(speakeasy_numberplanmodifier.ExplicitSuppress), - }, - Description: `The renewal period duration`, - }, - "renewal_duration_unit": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `The renewal period duration unit. must be one of ["weeks", "months", "years"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "weeks", - "months", - "years", - ), - }, - }, - "schema": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `must be "price"`, - Validators: []validator.String{ - stringvalidator.OneOf("price"), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "tax": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Parsed as JSON.`, - Validators: []validator.String{ - validators.IsValidJSON(), - }, - }, - "termination_time_amount": schema.NumberAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Number{ - speakeasy_numberplanmodifier.SuppressDiff(speakeasy_numberplanmodifier.ExplicitSuppress), - }, - Description: `The termination period duration`, - }, - "termination_time_unit": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `The termination period duration unit. must be one of ["weeks", "months", "years"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "weeks", - "months", - "years", - ), - }, - }, - "tiers": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "display_mode": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `must be one of ["hidden", "on_request"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "hidden", - "on_request", - ), - }, - }, - "flat_fee_amount": schema.NumberAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Number{ - speakeasy_numberplanmodifier.SuppressDiff(speakeasy_numberplanmodifier.ExplicitSuppress), - }, - }, - "flat_fee_amount_decimal": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "unit_amount": schema.NumberAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Number{ - speakeasy_numberplanmodifier.SuppressDiff(speakeasy_numberplanmodifier.ExplicitSuppress), - }, - }, - "unit_amount_decimal": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "up_to": schema.NumberAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Number{ - speakeasy_numberplanmodifier.SuppressDiff(speakeasy_numberplanmodifier.ExplicitSuppress), - }, - }, - }, - }, - Description: `Defines an array of tiers. Each tier has an upper bound, an unit amount and a flat fee.`, - }, - "title": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "type": schema.StringAttribute{ - Computed: true, - Optional: true, - Default: stringdefault.StaticString("one_time"), - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `One of ` + "`" + `one_time` + "`" + ` or ` + "`" + `recurring` + "`" + ` depending on whether the price is for a one-time purchase or a recurring (subscription) purchase. Default: "one_time"; must be one of ["one_time", "recurring"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "one_time", - "recurring", - ), - }, - }, - "unit": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `The unit of measurement used for display purposes and possibly for calculations when the price is variable.`, - }, - "unit_amount": schema.NumberAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Number{ - speakeasy_numberplanmodifier.SuppressDiff(speakeasy_numberplanmodifier.ExplicitSuppress), - }, - Description: `The unit amount in cents to be charged, represented as a whole integer if possible.`, - }, - "unit_amount_currency": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Three-letter ISO currency code, in lowercase.`, - }, - "unit_amount_decimal": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `The unit amount in cents to be charged, represented as a decimal string with at most 12 decimal places.`, - }, - "updated_at": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Validators: []validator.String{ - validators.IsRFC3339(), - }, - }, - "variable_price": schema.BoolAttribute{ - Computed: true, - Optional: true, - Default: booldefault.StaticBool(false), - PlanModifiers: []planmodifier.Bool{ - speakeasy_boolplanmodifier.SuppressDiff(speakeasy_boolplanmodifier.ExplicitSuppress), - }, - Description: `The flag for prices that can be influenced by external variables such as user input. Default: false`, - }, - }, - } -} - -func (r *PriceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected Resource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *PriceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - var data *PriceResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(plan.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - request := *data.ToSharedPriceCreate() - res, err := r.client.Price.CreatePrice(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 201 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Price != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedPrice(res.Price) - refreshPlan(ctx, plan, &data, resp.Diagnostics) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *PriceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - var data *PriceResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - // read.price.hydrateread.price.hydrate impedance mismatch: boolean != classtrace=["Price#create.req"] - var hydrate *bool - var priceID string - priceID = data.ID.ValueString() - - // read.price.strictread.price.strict impedance mismatch: boolean != classtrace=["Price#create.req"] - var strict *bool - request := operations.GetPriceRequest{ - Hydrate: hydrate, - PriceID: priceID, - Strict: strict, - } - res, err := r.client.Price.GetPrice(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Price != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedPrice(res.Price) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *PriceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { - var data *PriceResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - merge(ctx, req, resp, &data) - if resp.Diagnostics.HasError() { - return - } - - pricePatch := *data.ToSharedPricePatch() - var priceID string - priceID = data.ID.ValueString() - - request := operations.PatchPriceRequest{ - PricePatch: pricePatch, - PriceID: priceID, - } - res, err := r.client.Price.PatchPrice(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Price != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedPrice(res.Price) - refreshPlan(ctx, plan, &data, resp.Diagnostics) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *PriceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { - var data *PriceResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - var priceID string - priceID = data.ID.ValueString() - - request := operations.DeletePriceRequest{ - PriceID: priceID, - } - res, err := r.client.Price.DeletePrice(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - -} - -func (r *PriceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { - resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...) -} diff --git a/internal/provider/price_resource_sdk.go b/internal/provider/price_resource_sdk.go deleted file mode 100644 index d8ab9ac..0000000 --- a/internal/provider/price_resource_sdk.go +++ /dev/null @@ -1,788 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "encoding/json" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" - "math/big" - "time" -) - -func (r *PriceResourceModel) ToSharedPriceCreate() *shared.PriceCreate { - additional := make(map[string]interface{}) - for additionalKey, additionalValue := range r.Additional { - var additionalInst interface{} - _ = json.Unmarshal([]byte(additionalValue.ValueString()), &additionalInst) - additional[additionalKey] = additionalInst - } - var files *shared.BaseRelation - if r.Files != nil { - var dollarRelation []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem := range r.Files.DollarRelation { - var tags []string = []string{} - for _, tagsItem := range dollarRelationItem.Tags { - tags = append(tags, tagsItem.ValueString()) - } - entityID := new(string) - if !dollarRelationItem.EntityID.IsUnknown() && !dollarRelationItem.EntityID.IsNull() { - *entityID = dollarRelationItem.EntityID.ValueString() - } else { - entityID = nil - } - dollarRelation = append(dollarRelation, shared.DollarRelation{ - Tags: tags, - EntityID: entityID, - }) - } - files = &shared.BaseRelation{ - DollarRelation: dollarRelation, - } - } - var manifest []string = []string{} - for _, manifestItem := range r.Manifest { - manifest = append(manifest, manifestItem.ValueString()) - } - schema := new(shared.PriceCreateSchema) - if !r.Schema.IsUnknown() && !r.Schema.IsNull() { - *schema = shared.PriceCreateSchema(r.Schema.ValueString()) - } else { - schema = nil - } - var tags1 []string = []string{} - for _, tagsItem1 := range r.Tags { - tags1 = append(tags1, tagsItem1.ValueString()) - } - var active bool - active = r.Active.ValueBool() - - billingDurationAmount := new(float64) - if !r.BillingDurationAmount.IsUnknown() && !r.BillingDurationAmount.IsNull() { - *billingDurationAmount, _ = r.BillingDurationAmount.ValueBigFloat().Float64() - } else { - billingDurationAmount = nil - } - billingDurationUnit := new(shared.PriceCreateBillingDurationUnit) - if !r.BillingDurationUnit.IsUnknown() && !r.BillingDurationUnit.IsNull() { - *billingDurationUnit = shared.PriceCreateBillingDurationUnit(r.BillingDurationUnit.ValueString()) - } else { - billingDurationUnit = nil - } - var description string - description = r.Description.ValueString() - - isCompositePrice := new(bool) - if !r.IsCompositePrice.IsUnknown() && !r.IsCompositePrice.IsNull() { - *isCompositePrice = r.IsCompositePrice.ValueBool() - } else { - isCompositePrice = nil - } - isTaxInclusive := new(bool) - if !r.IsTaxInclusive.IsUnknown() && !r.IsTaxInclusive.IsNull() { - *isTaxInclusive = r.IsTaxInclusive.ValueBool() - } else { - isTaxInclusive = nil - } - longDescription := new(string) - if !r.LongDescription.IsUnknown() && !r.LongDescription.IsNull() { - *longDescription = r.LongDescription.ValueString() - } else { - longDescription = nil - } - noticeTimeAmount := new(float64) - if !r.NoticeTimeAmount.IsUnknown() && !r.NoticeTimeAmount.IsNull() { - *noticeTimeAmount, _ = r.NoticeTimeAmount.ValueBigFloat().Float64() - } else { - noticeTimeAmount = nil - } - noticeTimeUnit := new(shared.PriceCreateNoticeTimeUnit) - if !r.NoticeTimeUnit.IsUnknown() && !r.NoticeTimeUnit.IsNull() { - *noticeTimeUnit = shared.PriceCreateNoticeTimeUnit(r.NoticeTimeUnit.ValueString()) - } else { - noticeTimeUnit = nil - } - var priceComponents *shared.PriceCreatePriceComponents - if r.PriceComponents != nil { - var dollarRelation1 []shared.PriceComponentRelation = []shared.PriceComponentRelation{} - for _, dollarRelationItem1 := range r.PriceComponents.DollarRelation { - var tags2 []string = []string{} - for _, tagsItem2 := range dollarRelationItem1.Tags { - tags2 = append(tags2, tagsItem2.ValueString()) - } - entityId1 := new(string) - if !dollarRelationItem1.EntityID.IsUnknown() && !dollarRelationItem1.EntityID.IsNull() { - *entityId1 = dollarRelationItem1.EntityID.ValueString() - } else { - entityId1 = nil - } - dollarRelation1 = append(dollarRelation1, shared.PriceComponentRelation{ - Tags: tags2, - EntityID: entityId1, - }) - } - priceComponents = &shared.PriceCreatePriceComponents{ - DollarRelation: dollarRelation1, - } - } - priceDisplayInJourneys := new(shared.PriceCreatePriceDisplayInJourneys) - if !r.PriceDisplayInJourneys.IsUnknown() && !r.PriceDisplayInJourneys.IsNull() { - *priceDisplayInJourneys = shared.PriceCreatePriceDisplayInJourneys(r.PriceDisplayInJourneys.ValueString()) - } else { - priceDisplayInJourneys = nil - } - pricingModel := new(shared.PriceCreatePricingModel) - if !r.PricingModel.IsUnknown() && !r.PricingModel.IsNull() { - *pricingModel = shared.PriceCreatePricingModel(r.PricingModel.ValueString()) - } else { - pricingModel = nil - } - renewalDurationAmount := new(float64) - if !r.RenewalDurationAmount.IsUnknown() && !r.RenewalDurationAmount.IsNull() { - *renewalDurationAmount, _ = r.RenewalDurationAmount.ValueBigFloat().Float64() - } else { - renewalDurationAmount = nil - } - renewalDurationUnit := new(shared.PriceCreateRenewalDurationUnit) - if !r.RenewalDurationUnit.IsUnknown() && !r.RenewalDurationUnit.IsNull() { - *renewalDurationUnit = shared.PriceCreateRenewalDurationUnit(r.RenewalDurationUnit.ValueString()) - } else { - renewalDurationUnit = nil - } - var tax interface{} - if !r.Tax.IsUnknown() && !r.Tax.IsNull() { - _ = json.Unmarshal([]byte(r.Tax.ValueString()), &tax) - } - terminationTimeAmount := new(float64) - if !r.TerminationTimeAmount.IsUnknown() && !r.TerminationTimeAmount.IsNull() { - *terminationTimeAmount, _ = r.TerminationTimeAmount.ValueBigFloat().Float64() - } else { - terminationTimeAmount = nil - } - terminationTimeUnit := new(shared.PriceCreateTerminationTimeUnit) - if !r.TerminationTimeUnit.IsUnknown() && !r.TerminationTimeUnit.IsNull() { - *terminationTimeUnit = shared.PriceCreateTerminationTimeUnit(r.TerminationTimeUnit.ValueString()) - } else { - terminationTimeUnit = nil - } - var tiers []shared.PriceTier = []shared.PriceTier{} - for _, tiersItem := range r.Tiers { - displayMode := new(shared.PriceTierDisplayMode) - if !tiersItem.DisplayMode.IsUnknown() && !tiersItem.DisplayMode.IsNull() { - *displayMode = shared.PriceTierDisplayMode(tiersItem.DisplayMode.ValueString()) - } else { - displayMode = nil - } - flatFeeAmount := new(float64) - if !tiersItem.FlatFeeAmount.IsUnknown() && !tiersItem.FlatFeeAmount.IsNull() { - *flatFeeAmount, _ = tiersItem.FlatFeeAmount.ValueBigFloat().Float64() - } else { - flatFeeAmount = nil - } - flatFeeAmountDecimal := new(string) - if !tiersItem.FlatFeeAmountDecimal.IsUnknown() && !tiersItem.FlatFeeAmountDecimal.IsNull() { - *flatFeeAmountDecimal = tiersItem.FlatFeeAmountDecimal.ValueString() - } else { - flatFeeAmountDecimal = nil - } - unitAmount := new(float64) - if !tiersItem.UnitAmount.IsUnknown() && !tiersItem.UnitAmount.IsNull() { - *unitAmount, _ = tiersItem.UnitAmount.ValueBigFloat().Float64() - } else { - unitAmount = nil - } - unitAmountDecimal := new(string) - if !tiersItem.UnitAmountDecimal.IsUnknown() && !tiersItem.UnitAmountDecimal.IsNull() { - *unitAmountDecimal = tiersItem.UnitAmountDecimal.ValueString() - } else { - unitAmountDecimal = nil - } - upTo := new(float64) - if !tiersItem.UpTo.IsUnknown() && !tiersItem.UpTo.IsNull() { - *upTo, _ = tiersItem.UpTo.ValueBigFloat().Float64() - } else { - upTo = nil - } - tiers = append(tiers, shared.PriceTier{ - DisplayMode: displayMode, - FlatFeeAmount: flatFeeAmount, - FlatFeeAmountDecimal: flatFeeAmountDecimal, - UnitAmount: unitAmount, - UnitAmountDecimal: unitAmountDecimal, - UpTo: upTo, - }) - } - typeVar := new(shared.PriceCreateType) - if !r.Type.IsUnknown() && !r.Type.IsNull() { - *typeVar = shared.PriceCreateType(r.Type.ValueString()) - } else { - typeVar = nil - } - unit := new(string) - if !r.Unit.IsUnknown() && !r.Unit.IsNull() { - *unit = r.Unit.ValueString() - } else { - unit = nil - } - unitAmount1 := new(float64) - if !r.UnitAmount.IsUnknown() && !r.UnitAmount.IsNull() { - *unitAmount1, _ = r.UnitAmount.ValueBigFloat().Float64() - } else { - unitAmount1 = nil - } - unitAmountCurrency := new(string) - if !r.UnitAmountCurrency.IsUnknown() && !r.UnitAmountCurrency.IsNull() { - *unitAmountCurrency = r.UnitAmountCurrency.ValueString() - } else { - unitAmountCurrency = nil - } - unitAmountDecimal1 := new(string) - if !r.UnitAmountDecimal.IsUnknown() && !r.UnitAmountDecimal.IsNull() { - *unitAmountDecimal1 = r.UnitAmountDecimal.ValueString() - } else { - unitAmountDecimal1 = nil - } - variablePrice := new(bool) - if !r.VariablePrice.IsUnknown() && !r.VariablePrice.IsNull() { - *variablePrice = r.VariablePrice.ValueBool() - } else { - variablePrice = nil - } - out := shared.PriceCreate{ - Additional: additional, - Files: files, - Manifest: manifest, - Schema: schema, - Tags: tags1, - Active: active, - BillingDurationAmount: billingDurationAmount, - BillingDurationUnit: billingDurationUnit, - Description: description, - IsCompositePrice: isCompositePrice, - IsTaxInclusive: isTaxInclusive, - LongDescription: longDescription, - NoticeTimeAmount: noticeTimeAmount, - NoticeTimeUnit: noticeTimeUnit, - PriceComponents: priceComponents, - PriceDisplayInJourneys: priceDisplayInJourneys, - PricingModel: pricingModel, - RenewalDurationAmount: renewalDurationAmount, - RenewalDurationUnit: renewalDurationUnit, - Tax: tax, - TerminationTimeAmount: terminationTimeAmount, - TerminationTimeUnit: terminationTimeUnit, - Tiers: tiers, - Type: typeVar, - Unit: unit, - UnitAmount: unitAmount1, - UnitAmountCurrency: unitAmountCurrency, - UnitAmountDecimal: unitAmountDecimal1, - VariablePrice: variablePrice, - } - return &out -} - -func (r *PriceResourceModel) RefreshFromSharedPrice(resp *shared.Price) { - if resp != nil { - if len(resp.Additional) > 0 { - r.Additional = make(map[string]types.String) - for key, value := range resp.Additional { - result, _ := json.Marshal(value) - r.Additional[key] = types.StringValue(string(result)) - } - } - if resp.ACL == nil { - r.ACL = nil - } else { - r.ACL = &tfTypes.BaseEntityACL{} - r.ACL.Delete = []types.String{} - for _, v := range resp.ACL.Delete { - r.ACL.Delete = append(r.ACL.Delete, types.StringValue(v)) - } - r.ACL.Edit = []types.String{} - for _, v := range resp.ACL.Edit { - r.ACL.Edit = append(r.ACL.Edit, types.StringValue(v)) - } - r.ACL.View = []types.String{} - for _, v := range resp.ACL.View { - r.ACL.View = append(r.ACL.View, types.StringValue(v)) - } - } - if resp.CreatedAt != nil { - r.CreatedAt = types.StringValue(resp.CreatedAt.Format(time.RFC3339Nano)) - } else { - r.CreatedAt = types.StringNull() - } - if resp.Files == nil { - r.Files = nil - } else { - r.Files = &tfTypes.BaseRelation{} - r.Files.DollarRelation = []tfTypes.DollarRelation{} - if len(r.Files.DollarRelation) > len(resp.Files.DollarRelation) { - r.Files.DollarRelation = r.Files.DollarRelation[:len(resp.Files.DollarRelation)] - } - for dollarRelationCount, dollarRelationItem := range resp.Files.DollarRelation { - var dollarRelation1 tfTypes.DollarRelation - dollarRelation1.Tags = []types.String{} - for _, v := range dollarRelationItem.Tags { - dollarRelation1.Tags = append(dollarRelation1.Tags, types.StringValue(v)) - } - dollarRelation1.EntityID = types.StringPointerValue(dollarRelationItem.EntityID) - if dollarRelationCount+1 > len(r.Files.DollarRelation) { - r.Files.DollarRelation = append(r.Files.DollarRelation, dollarRelation1) - } else { - r.Files.DollarRelation[dollarRelationCount].Tags = dollarRelation1.Tags - r.Files.DollarRelation[dollarRelationCount].EntityID = dollarRelation1.EntityID - } - } - } - r.ID = types.StringPointerValue(resp.ID) - r.Manifest = []types.String{} - for _, v := range resp.Manifest { - r.Manifest = append(r.Manifest, types.StringValue(v)) - } - r.Org = types.StringValue(resp.Org) - r.Owners = []tfTypes.BaseEntityOwner{} - if len(r.Owners) > len(resp.Owners) { - r.Owners = r.Owners[:len(resp.Owners)] - } - for ownersCount, ownersItem := range resp.Owners { - var owners1 tfTypes.BaseEntityOwner - owners1.OrgID = types.StringValue(ownersItem.OrgID) - owners1.UserID = types.StringPointerValue(ownersItem.UserID) - if ownersCount+1 > len(r.Owners) { - r.Owners = append(r.Owners, owners1) - } else { - r.Owners[ownersCount].OrgID = owners1.OrgID - r.Owners[ownersCount].UserID = owners1.UserID - } - } - r.Schema = types.StringValue(string(resp.Schema)) - r.Tags = []types.String{} - for _, v := range resp.Tags { - r.Tags = append(r.Tags, types.StringValue(v)) - } - r.Title = types.StringPointerValue(resp.Title) - if resp.UpdatedAt != nil { - r.UpdatedAt = types.StringValue(resp.UpdatedAt.Format(time.RFC3339Nano)) - } else { - r.UpdatedAt = types.StringNull() - } - r.Active = types.BoolValue(resp.Active) - if resp.BillingDurationAmount != nil { - r.BillingDurationAmount = types.NumberValue(big.NewFloat(float64(*resp.BillingDurationAmount))) - } else { - r.BillingDurationAmount = types.NumberNull() - } - if resp.BillingDurationUnit != nil { - r.BillingDurationUnit = types.StringValue(string(*resp.BillingDurationUnit)) - } else { - r.BillingDurationUnit = types.StringNull() - } - r.Description = types.StringValue(resp.Description) - r.IsCompositePrice = types.BoolPointerValue(resp.IsCompositePrice) - r.IsTaxInclusive = types.BoolPointerValue(resp.IsTaxInclusive) - r.LongDescription = types.StringPointerValue(resp.LongDescription) - if resp.NoticeTimeAmount != nil { - r.NoticeTimeAmount = types.NumberValue(big.NewFloat(float64(*resp.NoticeTimeAmount))) - } else { - r.NoticeTimeAmount = types.NumberNull() - } - if resp.NoticeTimeUnit != nil { - r.NoticeTimeUnit = types.StringValue(string(*resp.NoticeTimeUnit)) - } else { - r.NoticeTimeUnit = types.StringNull() - } - if resp.PriceComponents == nil { - r.PriceComponents = nil - } else { - r.PriceComponents = &tfTypes.PriceCreatePriceComponents{} - r.PriceComponents.DollarRelation = []tfTypes.PriceComponentRelation{} - if len(r.PriceComponents.DollarRelation) > len(resp.PriceComponents.DollarRelation) { - r.PriceComponents.DollarRelation = r.PriceComponents.DollarRelation[:len(resp.PriceComponents.DollarRelation)] - } - for dollarRelationCount1, dollarRelationItem1 := range resp.PriceComponents.DollarRelation { - var dollarRelation3 tfTypes.PriceComponentRelation - dollarRelation3.Tags = []types.String{} - for _, v := range dollarRelationItem1.Tags { - dollarRelation3.Tags = append(dollarRelation3.Tags, types.StringValue(v)) - } - dollarRelation3.EntityID = types.StringPointerValue(dollarRelationItem1.EntityID) - if dollarRelationCount1+1 > len(r.PriceComponents.DollarRelation) { - r.PriceComponents.DollarRelation = append(r.PriceComponents.DollarRelation, dollarRelation3) - } else { - r.PriceComponents.DollarRelation[dollarRelationCount1].Tags = dollarRelation3.Tags - r.PriceComponents.DollarRelation[dollarRelationCount1].EntityID = dollarRelation3.EntityID - } - } - } - if resp.PriceDisplayInJourneys != nil { - r.PriceDisplayInJourneys = types.StringValue(string(*resp.PriceDisplayInJourneys)) - } else { - r.PriceDisplayInJourneys = types.StringNull() - } - if resp.PricingModel != nil { - r.PricingModel = types.StringValue(string(*resp.PricingModel)) - } else { - r.PricingModel = types.StringNull() - } - if resp.RenewalDurationAmount != nil { - r.RenewalDurationAmount = types.NumberValue(big.NewFloat(float64(*resp.RenewalDurationAmount))) - } else { - r.RenewalDurationAmount = types.NumberNull() - } - if resp.RenewalDurationUnit != nil { - r.RenewalDurationUnit = types.StringValue(string(*resp.RenewalDurationUnit)) - } else { - r.RenewalDurationUnit = types.StringNull() - } - if resp.Tax == nil { - r.Tax = types.StringNull() - } else { - taxResult, _ := json.Marshal(resp.Tax) - r.Tax = types.StringValue(string(taxResult)) - } - if resp.TerminationTimeAmount != nil { - r.TerminationTimeAmount = types.NumberValue(big.NewFloat(float64(*resp.TerminationTimeAmount))) - } else { - r.TerminationTimeAmount = types.NumberNull() - } - if resp.TerminationTimeUnit != nil { - r.TerminationTimeUnit = types.StringValue(string(*resp.TerminationTimeUnit)) - } else { - r.TerminationTimeUnit = types.StringNull() - } - r.Tiers = []tfTypes.PriceTier{} - if len(r.Tiers) > len(resp.Tiers) { - r.Tiers = r.Tiers[:len(resp.Tiers)] - } - for tiersCount, tiersItem := range resp.Tiers { - var tiers1 tfTypes.PriceTier - if tiersItem.DisplayMode != nil { - tiers1.DisplayMode = types.StringValue(string(*tiersItem.DisplayMode)) - } else { - tiers1.DisplayMode = types.StringNull() - } - if tiersItem.FlatFeeAmount != nil { - tiers1.FlatFeeAmount = types.NumberValue(big.NewFloat(float64(*tiersItem.FlatFeeAmount))) - } else { - tiers1.FlatFeeAmount = types.NumberNull() - } - tiers1.FlatFeeAmountDecimal = types.StringPointerValue(tiersItem.FlatFeeAmountDecimal) - if tiersItem.UnitAmount != nil { - tiers1.UnitAmount = types.NumberValue(big.NewFloat(float64(*tiersItem.UnitAmount))) - } else { - tiers1.UnitAmount = types.NumberNull() - } - tiers1.UnitAmountDecimal = types.StringPointerValue(tiersItem.UnitAmountDecimal) - if tiersItem.UpTo != nil { - tiers1.UpTo = types.NumberValue(big.NewFloat(float64(*tiersItem.UpTo))) - } else { - tiers1.UpTo = types.NumberNull() - } - if tiersCount+1 > len(r.Tiers) { - r.Tiers = append(r.Tiers, tiers1) - } else { - r.Tiers[tiersCount].DisplayMode = tiers1.DisplayMode - r.Tiers[tiersCount].FlatFeeAmount = tiers1.FlatFeeAmount - r.Tiers[tiersCount].FlatFeeAmountDecimal = tiers1.FlatFeeAmountDecimal - r.Tiers[tiersCount].UnitAmount = tiers1.UnitAmount - r.Tiers[tiersCount].UnitAmountDecimal = tiers1.UnitAmountDecimal - r.Tiers[tiersCount].UpTo = tiers1.UpTo - } - } - if resp.Type != nil { - r.Type = types.StringValue(string(*resp.Type)) - } else { - r.Type = types.StringNull() - } - r.Unit = types.StringPointerValue(resp.Unit) - if resp.UnitAmount != nil { - r.UnitAmount = types.NumberValue(big.NewFloat(float64(*resp.UnitAmount))) - } else { - r.UnitAmount = types.NumberNull() - } - r.UnitAmountCurrency = types.StringPointerValue(resp.UnitAmountCurrency) - r.UnitAmountDecimal = types.StringPointerValue(resp.UnitAmountDecimal) - r.VariablePrice = types.BoolPointerValue(resp.VariablePrice) - } -} - -func (r *PriceResourceModel) ToSharedPricePatch() *shared.PricePatch { - additional := make(map[string]interface{}) - for additionalKey, additionalValue := range r.Additional { - var additionalInst interface{} - _ = json.Unmarshal([]byte(additionalValue.ValueString()), &additionalInst) - additional[additionalKey] = additionalInst - } - var files *shared.BaseRelation - if r.Files != nil { - var dollarRelation []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem := range r.Files.DollarRelation { - var tags []string = []string{} - for _, tagsItem := range dollarRelationItem.Tags { - tags = append(tags, tagsItem.ValueString()) - } - entityID := new(string) - if !dollarRelationItem.EntityID.IsUnknown() && !dollarRelationItem.EntityID.IsNull() { - *entityID = dollarRelationItem.EntityID.ValueString() - } else { - entityID = nil - } - dollarRelation = append(dollarRelation, shared.DollarRelation{ - Tags: tags, - EntityID: entityID, - }) - } - files = &shared.BaseRelation{ - DollarRelation: dollarRelation, - } - } - var manifest []string = []string{} - for _, manifestItem := range r.Manifest { - manifest = append(manifest, manifestItem.ValueString()) - } - schema := new(shared.PricePatchSchema) - if !r.Schema.IsUnknown() && !r.Schema.IsNull() { - *schema = shared.PricePatchSchema(r.Schema.ValueString()) - } else { - schema = nil - } - var tags1 []string = []string{} - for _, tagsItem1 := range r.Tags { - tags1 = append(tags1, tagsItem1.ValueString()) - } - active := new(bool) - if !r.Active.IsUnknown() && !r.Active.IsNull() { - *active = r.Active.ValueBool() - } else { - active = nil - } - billingDurationAmount := new(float64) - if !r.BillingDurationAmount.IsUnknown() && !r.BillingDurationAmount.IsNull() { - *billingDurationAmount, _ = r.BillingDurationAmount.ValueBigFloat().Float64() - } else { - billingDurationAmount = nil - } - billingDurationUnit := new(shared.PricePatchBillingDurationUnit) - if !r.BillingDurationUnit.IsUnknown() && !r.BillingDurationUnit.IsNull() { - *billingDurationUnit = shared.PricePatchBillingDurationUnit(r.BillingDurationUnit.ValueString()) - } else { - billingDurationUnit = nil - } - description := new(string) - if !r.Description.IsUnknown() && !r.Description.IsNull() { - *description = r.Description.ValueString() - } else { - description = nil - } - isCompositePrice := new(bool) - if !r.IsCompositePrice.IsUnknown() && !r.IsCompositePrice.IsNull() { - *isCompositePrice = r.IsCompositePrice.ValueBool() - } else { - isCompositePrice = nil - } - isTaxInclusive := new(bool) - if !r.IsTaxInclusive.IsUnknown() && !r.IsTaxInclusive.IsNull() { - *isTaxInclusive = r.IsTaxInclusive.ValueBool() - } else { - isTaxInclusive = nil - } - longDescription := new(string) - if !r.LongDescription.IsUnknown() && !r.LongDescription.IsNull() { - *longDescription = r.LongDescription.ValueString() - } else { - longDescription = nil - } - noticeTimeAmount := new(float64) - if !r.NoticeTimeAmount.IsUnknown() && !r.NoticeTimeAmount.IsNull() { - *noticeTimeAmount, _ = r.NoticeTimeAmount.ValueBigFloat().Float64() - } else { - noticeTimeAmount = nil - } - noticeTimeUnit := new(shared.PricePatchNoticeTimeUnit) - if !r.NoticeTimeUnit.IsUnknown() && !r.NoticeTimeUnit.IsNull() { - *noticeTimeUnit = shared.PricePatchNoticeTimeUnit(r.NoticeTimeUnit.ValueString()) - } else { - noticeTimeUnit = nil - } - var priceComponents *shared.PricePatchPriceComponents - if r.PriceComponents != nil { - var dollarRelation1 []shared.PriceComponentRelation = []shared.PriceComponentRelation{} - for _, dollarRelationItem1 := range r.PriceComponents.DollarRelation { - var tags2 []string = []string{} - for _, tagsItem2 := range dollarRelationItem1.Tags { - tags2 = append(tags2, tagsItem2.ValueString()) - } - entityId1 := new(string) - if !dollarRelationItem1.EntityID.IsUnknown() && !dollarRelationItem1.EntityID.IsNull() { - *entityId1 = dollarRelationItem1.EntityID.ValueString() - } else { - entityId1 = nil - } - dollarRelation1 = append(dollarRelation1, shared.PriceComponentRelation{ - Tags: tags2, - EntityID: entityId1, - }) - } - priceComponents = &shared.PricePatchPriceComponents{ - DollarRelation: dollarRelation1, - } - } - priceDisplayInJourneys := new(shared.PricePatchPriceDisplayInJourneys) - if !r.PriceDisplayInJourneys.IsUnknown() && !r.PriceDisplayInJourneys.IsNull() { - *priceDisplayInJourneys = shared.PricePatchPriceDisplayInJourneys(r.PriceDisplayInJourneys.ValueString()) - } else { - priceDisplayInJourneys = nil - } - pricingModel := new(shared.PricePatchPricingModel) - if !r.PricingModel.IsUnknown() && !r.PricingModel.IsNull() { - *pricingModel = shared.PricePatchPricingModel(r.PricingModel.ValueString()) - } else { - pricingModel = nil - } - renewalDurationAmount := new(float64) - if !r.RenewalDurationAmount.IsUnknown() && !r.RenewalDurationAmount.IsNull() { - *renewalDurationAmount, _ = r.RenewalDurationAmount.ValueBigFloat().Float64() - } else { - renewalDurationAmount = nil - } - renewalDurationUnit := new(shared.PricePatchRenewalDurationUnit) - if !r.RenewalDurationUnit.IsUnknown() && !r.RenewalDurationUnit.IsNull() { - *renewalDurationUnit = shared.PricePatchRenewalDurationUnit(r.RenewalDurationUnit.ValueString()) - } else { - renewalDurationUnit = nil - } - var tax interface{} - if !r.Tax.IsUnknown() && !r.Tax.IsNull() { - _ = json.Unmarshal([]byte(r.Tax.ValueString()), &tax) - } - terminationTimeAmount := new(float64) - if !r.TerminationTimeAmount.IsUnknown() && !r.TerminationTimeAmount.IsNull() { - *terminationTimeAmount, _ = r.TerminationTimeAmount.ValueBigFloat().Float64() - } else { - terminationTimeAmount = nil - } - terminationTimeUnit := new(shared.PricePatchTerminationTimeUnit) - if !r.TerminationTimeUnit.IsUnknown() && !r.TerminationTimeUnit.IsNull() { - *terminationTimeUnit = shared.PricePatchTerminationTimeUnit(r.TerminationTimeUnit.ValueString()) - } else { - terminationTimeUnit = nil - } - var tiers []shared.PriceTier = []shared.PriceTier{} - for _, tiersItem := range r.Tiers { - displayMode := new(shared.PriceTierDisplayMode) - if !tiersItem.DisplayMode.IsUnknown() && !tiersItem.DisplayMode.IsNull() { - *displayMode = shared.PriceTierDisplayMode(tiersItem.DisplayMode.ValueString()) - } else { - displayMode = nil - } - flatFeeAmount := new(float64) - if !tiersItem.FlatFeeAmount.IsUnknown() && !tiersItem.FlatFeeAmount.IsNull() { - *flatFeeAmount, _ = tiersItem.FlatFeeAmount.ValueBigFloat().Float64() - } else { - flatFeeAmount = nil - } - flatFeeAmountDecimal := new(string) - if !tiersItem.FlatFeeAmountDecimal.IsUnknown() && !tiersItem.FlatFeeAmountDecimal.IsNull() { - *flatFeeAmountDecimal = tiersItem.FlatFeeAmountDecimal.ValueString() - } else { - flatFeeAmountDecimal = nil - } - unitAmount := new(float64) - if !tiersItem.UnitAmount.IsUnknown() && !tiersItem.UnitAmount.IsNull() { - *unitAmount, _ = tiersItem.UnitAmount.ValueBigFloat().Float64() - } else { - unitAmount = nil - } - unitAmountDecimal := new(string) - if !tiersItem.UnitAmountDecimal.IsUnknown() && !tiersItem.UnitAmountDecimal.IsNull() { - *unitAmountDecimal = tiersItem.UnitAmountDecimal.ValueString() - } else { - unitAmountDecimal = nil - } - upTo := new(float64) - if !tiersItem.UpTo.IsUnknown() && !tiersItem.UpTo.IsNull() { - *upTo, _ = tiersItem.UpTo.ValueBigFloat().Float64() - } else { - upTo = nil - } - tiers = append(tiers, shared.PriceTier{ - DisplayMode: displayMode, - FlatFeeAmount: flatFeeAmount, - FlatFeeAmountDecimal: flatFeeAmountDecimal, - UnitAmount: unitAmount, - UnitAmountDecimal: unitAmountDecimal, - UpTo: upTo, - }) - } - typeVar := new(shared.PricePatchType) - if !r.Type.IsUnknown() && !r.Type.IsNull() { - *typeVar = shared.PricePatchType(r.Type.ValueString()) - } else { - typeVar = nil - } - unit := new(string) - if !r.Unit.IsUnknown() && !r.Unit.IsNull() { - *unit = r.Unit.ValueString() - } else { - unit = nil - } - unitAmount1 := new(float64) - if !r.UnitAmount.IsUnknown() && !r.UnitAmount.IsNull() { - *unitAmount1, _ = r.UnitAmount.ValueBigFloat().Float64() - } else { - unitAmount1 = nil - } - unitAmountCurrency := new(string) - if !r.UnitAmountCurrency.IsUnknown() && !r.UnitAmountCurrency.IsNull() { - *unitAmountCurrency = r.UnitAmountCurrency.ValueString() - } else { - unitAmountCurrency = nil - } - unitAmountDecimal1 := new(string) - if !r.UnitAmountDecimal.IsUnknown() && !r.UnitAmountDecimal.IsNull() { - *unitAmountDecimal1 = r.UnitAmountDecimal.ValueString() - } else { - unitAmountDecimal1 = nil - } - variablePrice := new(bool) - if !r.VariablePrice.IsUnknown() && !r.VariablePrice.IsNull() { - *variablePrice = r.VariablePrice.ValueBool() - } else { - variablePrice = nil - } - out := shared.PricePatch{ - Additional: additional, - Files: files, - Manifest: manifest, - Schema: schema, - Tags: tags1, - Active: active, - BillingDurationAmount: billingDurationAmount, - BillingDurationUnit: billingDurationUnit, - Description: description, - IsCompositePrice: isCompositePrice, - IsTaxInclusive: isTaxInclusive, - LongDescription: longDescription, - NoticeTimeAmount: noticeTimeAmount, - NoticeTimeUnit: noticeTimeUnit, - PriceComponents: priceComponents, - PriceDisplayInJourneys: priceDisplayInJourneys, - PricingModel: pricingModel, - RenewalDurationAmount: renewalDurationAmount, - RenewalDurationUnit: renewalDurationUnit, - Tax: tax, - TerminationTimeAmount: terminationTimeAmount, - TerminationTimeUnit: terminationTimeUnit, - Tiers: tiers, - Type: typeVar, - Unit: unit, - UnitAmount: unitAmount1, - UnitAmountCurrency: unitAmountCurrency, - UnitAmountDecimal: unitAmountDecimal1, - VariablePrice: variablePrice, - } - return &out -} diff --git a/internal/provider/product_data_source.go b/internal/provider/product_data_source.go deleted file mode 100644 index e5aa336..0000000 --- a/internal/provider/product_data_source.go +++ /dev/null @@ -1,366 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/operations" - "github.com/hashicorp/terraform-plugin-framework/datasource" - "github.com/hashicorp/terraform-plugin-framework/datasource/schema" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ datasource.DataSource = &ProductDataSource{} -var _ datasource.DataSourceWithConfigure = &ProductDataSource{} - -func NewProductDataSource() datasource.DataSource { - return &ProductDataSource{} -} - -// ProductDataSource is the data source implementation. -type ProductDataSource struct { - client *sdk.SDK -} - -// ProductDataSourceModel describes the data model. -type ProductDataSourceModel struct { - ACL *tfTypes.BaseEntityACL `tfsdk:"acl"` - Active types.Bool `tfsdk:"active"` - Additional map[string]types.String `tfsdk:"additional"` - AvailabilityFiles *tfTypes.BaseRelation `tfsdk:"availability_files"` - Code types.String `tfsdk:"code"` - CreatedAt types.String `tfsdk:"created_at"` - Description types.String `tfsdk:"description"` - Feature []types.String `tfsdk:"feature"` - Files *tfTypes.BaseRelation `tfsdk:"files"` - Hydrate types.Bool `tfsdk:"hydrate"` - ID types.String `tfsdk:"id"` - InternalName types.String `tfsdk:"internal_name"` - Manifest []types.String `tfsdk:"manifest"` - Name types.String `tfsdk:"name"` - Org types.String `tfsdk:"org"` - Owners []tfTypes.BaseEntityOwner `tfsdk:"owners"` - PriceOptions *tfTypes.BaseRelation `tfsdk:"price_options"` - ProductDownloads *tfTypes.BaseRelation `tfsdk:"product_downloads"` - ProductImages *tfTypes.BaseRelation `tfsdk:"product_images"` - Purpose []types.String `tfsdk:"purpose"` - Schema types.String `tfsdk:"schema"` - Strict types.Bool `tfsdk:"strict"` - Tags []types.String `tfsdk:"tags"` - Title types.String `tfsdk:"title"` - Type types.String `tfsdk:"type"` - UpdatedAt types.String `tfsdk:"updated_at"` -} - -// Metadata returns the data source type name. -func (r *ProductDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_product" -} - -// Schema defines the schema for the data source. -func (r *ProductDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "Product DataSource", - - Attributes: map[string]schema.Attribute{ - "acl": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "delete": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "edit": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "view": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - Description: `Access control list (ACL) for an entity. Defines sharing access to external orgs or users.`, - }, - "active": schema.BoolAttribute{ - Computed: true, - }, - "additional": schema.MapAttribute{ - Computed: true, - ElementType: types.StringType, - Description: `Additional fields that are not part of the schema`, - }, - "availability_files": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "code": schema.StringAttribute{ - Computed: true, - Description: `The product code`, - }, - "created_at": schema.StringAttribute{ - Computed: true, - }, - "description": schema.StringAttribute{ - Computed: true, - Description: `A description of the product. Multi-line supported.`, - }, - "feature": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "files": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "hydrate": schema.BoolAttribute{ - Computed: true, - Optional: true, - Description: `Hydrates entities in relations when passed true`, - }, - "id": schema.StringAttribute{ - Computed: true, - }, - "internal_name": schema.StringAttribute{ - Computed: true, - Description: `Not visible to customers, only in internal tables`, - }, - "manifest": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - Description: `Manifest ID used to create/update the entity`, - }, - "name": schema.StringAttribute{ - Computed: true, - Description: `The description for the product`, - }, - "org": schema.StringAttribute{ - Computed: true, - Description: `Organization Id the entity belongs to`, - }, - "owners": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "org_id": schema.StringAttribute{ - Computed: true, - }, - "user_id": schema.StringAttribute{ - Computed: true, - }, - }, - }, - }, - "price_options": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "product_downloads": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "product_images": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "purpose": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "schema": schema.StringAttribute{ - Computed: true, - }, - "strict": schema.BoolAttribute{ - Computed: true, - Optional: true, - Description: `When passed true, the response will contain only fields that match the schema, with non-matching fields included in ` + "`" + `__additional` + "`" + ``, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "title": schema.StringAttribute{ - Computed: true, - }, - "type": schema.StringAttribute{ - Computed: true, - MarkdownDescription: `The type of Product:` + "\n" + - `` + "\n" + - `| type | description |` + "\n" + - `|----| ----|` + "\n" + - `| ` + "`" + `product` + "`" + ` | Represents a physical good |` + "\n" + - `| ` + "`" + `service` + "`" + ` | Represents a service or virtual product |`, - }, - "updated_at": schema.StringAttribute{ - Computed: true, - }, - }, - } -} - -func (r *ProductDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected DataSource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *ProductDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { - var data *ProductDataSourceModel - var item types.Object - - resp.Diagnostics.Append(req.Config.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - hydrate := new(bool) - if !data.Hydrate.IsUnknown() && !data.Hydrate.IsNull() { - *hydrate = data.Hydrate.ValueBool() - } else { - hydrate = nil - } - var productID string - productID = data.ID.ValueString() - - strict := new(bool) - if !data.Strict.IsUnknown() && !data.Strict.IsNull() { - *strict = data.Strict.ValueBool() - } else { - strict = nil - } - request := operations.GetProductRequest{ - Hydrate: hydrate, - ProductID: productID, - Strict: strict, - } - res, err := r.client.Product.GetProduct(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Product != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedProduct(res.Product) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} diff --git a/internal/provider/product_data_source_sdk.go b/internal/provider/product_data_source_sdk.go deleted file mode 100644 index 60dd438..0000000 --- a/internal/provider/product_data_source_sdk.go +++ /dev/null @@ -1,213 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "encoding/json" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" - "time" -) - -func (r *ProductDataSourceModel) RefreshFromSharedProduct(resp *shared.Product) { - if resp != nil { - if len(resp.Additional) > 0 { - r.Additional = make(map[string]types.String) - for key, value := range resp.Additional { - result, _ := json.Marshal(value) - r.Additional[key] = types.StringValue(string(result)) - } - } - if resp.ACL == nil { - r.ACL = nil - } else { - r.ACL = &tfTypes.BaseEntityACL{} - r.ACL.Delete = []types.String{} - for _, v := range resp.ACL.Delete { - r.ACL.Delete = append(r.ACL.Delete, types.StringValue(v)) - } - r.ACL.Edit = []types.String{} - for _, v := range resp.ACL.Edit { - r.ACL.Edit = append(r.ACL.Edit, types.StringValue(v)) - } - r.ACL.View = []types.String{} - for _, v := range resp.ACL.View { - r.ACL.View = append(r.ACL.View, types.StringValue(v)) - } - } - if resp.AvailabilityFiles == nil { - r.AvailabilityFiles = nil - } else { - r.AvailabilityFiles = &tfTypes.BaseRelation{} - r.AvailabilityFiles.DollarRelation = []tfTypes.DollarRelation{} - if len(r.AvailabilityFiles.DollarRelation) > len(resp.AvailabilityFiles.DollarRelation) { - r.AvailabilityFiles.DollarRelation = r.AvailabilityFiles.DollarRelation[:len(resp.AvailabilityFiles.DollarRelation)] - } - for dollarRelationCount, dollarRelationItem := range resp.AvailabilityFiles.DollarRelation { - var dollarRelation1 tfTypes.DollarRelation - dollarRelation1.Tags = []types.String{} - for _, v := range dollarRelationItem.Tags { - dollarRelation1.Tags = append(dollarRelation1.Tags, types.StringValue(v)) - } - dollarRelation1.EntityID = types.StringPointerValue(dollarRelationItem.EntityID) - if dollarRelationCount+1 > len(r.AvailabilityFiles.DollarRelation) { - r.AvailabilityFiles.DollarRelation = append(r.AvailabilityFiles.DollarRelation, dollarRelation1) - } else { - r.AvailabilityFiles.DollarRelation[dollarRelationCount].Tags = dollarRelation1.Tags - r.AvailabilityFiles.DollarRelation[dollarRelationCount].EntityID = dollarRelation1.EntityID - } - } - } - if resp.CreatedAt != nil { - r.CreatedAt = types.StringValue(resp.CreatedAt.Format(time.RFC3339Nano)) - } else { - r.CreatedAt = types.StringNull() - } - if resp.Files == nil { - r.Files = nil - } else { - r.Files = &tfTypes.BaseRelation{} - r.Files.DollarRelation = []tfTypes.DollarRelation{} - if len(r.Files.DollarRelation) > len(resp.Files.DollarRelation) { - r.Files.DollarRelation = r.Files.DollarRelation[:len(resp.Files.DollarRelation)] - } - for dollarRelationCount1, dollarRelationItem1 := range resp.Files.DollarRelation { - var dollarRelation3 tfTypes.DollarRelation - dollarRelation3.Tags = []types.String{} - for _, v := range dollarRelationItem1.Tags { - dollarRelation3.Tags = append(dollarRelation3.Tags, types.StringValue(v)) - } - dollarRelation3.EntityID = types.StringPointerValue(dollarRelationItem1.EntityID) - if dollarRelationCount1+1 > len(r.Files.DollarRelation) { - r.Files.DollarRelation = append(r.Files.DollarRelation, dollarRelation3) - } else { - r.Files.DollarRelation[dollarRelationCount1].Tags = dollarRelation3.Tags - r.Files.DollarRelation[dollarRelationCount1].EntityID = dollarRelation3.EntityID - } - } - } - r.ID = types.StringPointerValue(resp.ID) - r.Manifest = []types.String{} - for _, v := range resp.Manifest { - r.Manifest = append(r.Manifest, types.StringValue(v)) - } - r.Org = types.StringValue(resp.Org) - r.Owners = []tfTypes.BaseEntityOwner{} - if len(r.Owners) > len(resp.Owners) { - r.Owners = r.Owners[:len(resp.Owners)] - } - for ownersCount, ownersItem := range resp.Owners { - var owners1 tfTypes.BaseEntityOwner - owners1.OrgID = types.StringValue(ownersItem.OrgID) - owners1.UserID = types.StringPointerValue(ownersItem.UserID) - if ownersCount+1 > len(r.Owners) { - r.Owners = append(r.Owners, owners1) - } else { - r.Owners[ownersCount].OrgID = owners1.OrgID - r.Owners[ownersCount].UserID = owners1.UserID - } - } - r.Purpose = []types.String{} - for _, v := range resp.Purpose { - r.Purpose = append(r.Purpose, types.StringValue(v)) - } - r.Schema = types.StringValue(string(resp.Schema)) - r.Tags = []types.String{} - for _, v := range resp.Tags { - r.Tags = append(r.Tags, types.StringValue(v)) - } - r.Title = types.StringPointerValue(resp.Title) - if resp.UpdatedAt != nil { - r.UpdatedAt = types.StringValue(resp.UpdatedAt.Format(time.RFC3339Nano)) - } else { - r.UpdatedAt = types.StringNull() - } - r.Active = types.BoolValue(resp.Active) - r.Code = types.StringPointerValue(resp.Code) - r.Description = types.StringPointerValue(resp.Description) - r.Feature = nil - for _, featureItem := range resp.Feature { - var feature1 types.String - feature1Result, _ := json.Marshal(featureItem) - feature1 = types.StringValue(string(feature1Result)) - r.Feature = append(r.Feature, feature1) - } - r.InternalName = types.StringPointerValue(resp.InternalName) - r.Name = types.StringValue(resp.Name) - if resp.PriceOptions == nil { - r.PriceOptions = nil - } else { - r.PriceOptions = &tfTypes.BaseRelation{} - r.PriceOptions.DollarRelation = []tfTypes.DollarRelation{} - if len(r.PriceOptions.DollarRelation) > len(resp.PriceOptions.DollarRelation) { - r.PriceOptions.DollarRelation = r.PriceOptions.DollarRelation[:len(resp.PriceOptions.DollarRelation)] - } - for dollarRelationCount2, dollarRelationItem2 := range resp.PriceOptions.DollarRelation { - var dollarRelation5 tfTypes.DollarRelation - dollarRelation5.Tags = []types.String{} - for _, v := range dollarRelationItem2.Tags { - dollarRelation5.Tags = append(dollarRelation5.Tags, types.StringValue(v)) - } - dollarRelation5.EntityID = types.StringPointerValue(dollarRelationItem2.EntityID) - if dollarRelationCount2+1 > len(r.PriceOptions.DollarRelation) { - r.PriceOptions.DollarRelation = append(r.PriceOptions.DollarRelation, dollarRelation5) - } else { - r.PriceOptions.DollarRelation[dollarRelationCount2].Tags = dollarRelation5.Tags - r.PriceOptions.DollarRelation[dollarRelationCount2].EntityID = dollarRelation5.EntityID - } - } - } - if resp.ProductDownloads == nil { - r.ProductDownloads = nil - } else { - r.ProductDownloads = &tfTypes.BaseRelation{} - r.ProductDownloads.DollarRelation = []tfTypes.DollarRelation{} - if len(r.ProductDownloads.DollarRelation) > len(resp.ProductDownloads.DollarRelation) { - r.ProductDownloads.DollarRelation = r.ProductDownloads.DollarRelation[:len(resp.ProductDownloads.DollarRelation)] - } - for dollarRelationCount3, dollarRelationItem3 := range resp.ProductDownloads.DollarRelation { - var dollarRelation7 tfTypes.DollarRelation - dollarRelation7.Tags = []types.String{} - for _, v := range dollarRelationItem3.Tags { - dollarRelation7.Tags = append(dollarRelation7.Tags, types.StringValue(v)) - } - dollarRelation7.EntityID = types.StringPointerValue(dollarRelationItem3.EntityID) - if dollarRelationCount3+1 > len(r.ProductDownloads.DollarRelation) { - r.ProductDownloads.DollarRelation = append(r.ProductDownloads.DollarRelation, dollarRelation7) - } else { - r.ProductDownloads.DollarRelation[dollarRelationCount3].Tags = dollarRelation7.Tags - r.ProductDownloads.DollarRelation[dollarRelationCount3].EntityID = dollarRelation7.EntityID - } - } - } - if resp.ProductImages == nil { - r.ProductImages = nil - } else { - r.ProductImages = &tfTypes.BaseRelation{} - r.ProductImages.DollarRelation = []tfTypes.DollarRelation{} - if len(r.ProductImages.DollarRelation) > len(resp.ProductImages.DollarRelation) { - r.ProductImages.DollarRelation = r.ProductImages.DollarRelation[:len(resp.ProductImages.DollarRelation)] - } - for dollarRelationCount4, dollarRelationItem4 := range resp.ProductImages.DollarRelation { - var dollarRelation9 tfTypes.DollarRelation - dollarRelation9.Tags = []types.String{} - for _, v := range dollarRelationItem4.Tags { - dollarRelation9.Tags = append(dollarRelation9.Tags, types.StringValue(v)) - } - dollarRelation9.EntityID = types.StringPointerValue(dollarRelationItem4.EntityID) - if dollarRelationCount4+1 > len(r.ProductImages.DollarRelation) { - r.ProductImages.DollarRelation = append(r.ProductImages.DollarRelation, dollarRelation9) - } else { - r.ProductImages.DollarRelation[dollarRelationCount4].Tags = dollarRelation9.Tags - r.ProductImages.DollarRelation[dollarRelationCount4].EntityID = dollarRelation9.EntityID - } - } - } - if resp.Type != nil { - r.Type = types.StringValue(string(*resp.Type)) - } else { - r.Type = types.StringNull() - } - } -} diff --git a/internal/provider/product_resource.go b/internal/provider/product_resource.go deleted file mode 100644 index 4d741fc..0000000 --- a/internal/provider/product_resource.go +++ /dev/null @@ -1,718 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - speakeasy_boolplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/boolplanmodifier" - speakeasy_listplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/listplanmodifier" - speakeasy_mapplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/mapplanmodifier" - speakeasy_objectplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/objectplanmodifier" - speakeasy_stringplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/stringplanmodifier" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/operations" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/validators" - speakeasy_objectvalidators "github.com/epilot-dev/terraform-provider-epilot-product/internal/validators/objectvalidators" - "github.com/hashicorp/terraform-plugin-framework-validators/listvalidator" - "github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator" - "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" - "github.com/hashicorp/terraform-plugin-framework/path" - "github.com/hashicorp/terraform-plugin-framework/resource" - "github.com/hashicorp/terraform-plugin-framework/resource/schema" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" - "github.com/hashicorp/terraform-plugin-framework/schema/validator" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ resource.Resource = &ProductResource{} -var _ resource.ResourceWithImportState = &ProductResource{} - -func NewProductResource() resource.Resource { - return &ProductResource{} -} - -// ProductResource defines the resource implementation. -type ProductResource struct { - client *sdk.SDK -} - -// ProductResourceModel describes the resource data model. -type ProductResourceModel struct { - ACL *tfTypes.BaseEntityACL `tfsdk:"acl"` - Active types.Bool `tfsdk:"active"` - Additional map[string]types.String `tfsdk:"additional"` - AvailabilityFiles *tfTypes.BaseRelation `tfsdk:"availability_files"` - Code types.String `tfsdk:"code"` - CreatedAt types.String `tfsdk:"created_at"` - Description types.String `tfsdk:"description"` - Feature []types.String `tfsdk:"feature"` - Files *tfTypes.BaseRelation `tfsdk:"files"` - ID types.String `tfsdk:"id"` - InternalName types.String `tfsdk:"internal_name"` - Manifest []types.String `tfsdk:"manifest"` - Name types.String `tfsdk:"name"` - Org types.String `tfsdk:"org"` - Owners []tfTypes.BaseEntityOwner `tfsdk:"owners"` - PriceOptions *tfTypes.BaseRelation `tfsdk:"price_options"` - ProductDownloads *tfTypes.BaseRelation `tfsdk:"product_downloads"` - ProductImages *tfTypes.BaseRelation `tfsdk:"product_images"` - Purpose []types.String `tfsdk:"purpose"` - Schema types.String `tfsdk:"schema"` - Tags []types.String `tfsdk:"tags"` - Title types.String `tfsdk:"title"` - Type types.String `tfsdk:"type"` - UpdatedAt types.String `tfsdk:"updated_at"` -} - -func (r *ProductResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_product" -} - -func (r *ProductResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "Product Resource", - Attributes: map[string]schema.Attribute{ - "acl": schema.SingleNestedAttribute{ - Computed: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "delete": schema.ListAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "edit": schema.ListAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "view": schema.ListAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - Description: `Access control list (ACL) for an entity. Defines sharing access to external orgs or users.`, - }, - "active": schema.BoolAttribute{ - Required: true, - PlanModifiers: []planmodifier.Bool{ - speakeasy_boolplanmodifier.SuppressDiff(speakeasy_boolplanmodifier.ExplicitSuppress), - }, - }, - "additional": schema.MapAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Map{ - speakeasy_mapplanmodifier.SuppressDiff(speakeasy_mapplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - Description: `Additional fields that are not part of the schema`, - Validators: []validator.Map{ - mapvalidator.ValueStringsAre(validators.IsValidJSON()), - }, - }, - "availability_files": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "code": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `The product code`, - }, - "created_at": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Validators: []validator.String{ - validators.IsRFC3339(), - }, - }, - "description": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `A description of the product. Multi-line supported.`, - }, - "feature": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - Validators: []validator.List{ - listvalidator.ValueStringsAre(validators.IsValidJSON()), - }, - }, - "files": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "id": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "internal_name": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Not visible to customers, only in internal tables`, - }, - "manifest": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - Description: `Manifest ID used to create/update the entity`, - }, - "name": schema.StringAttribute{ - Required: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `The description for the product`, - }, - "org": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Organization Id the entity belongs to`, - }, - "owners": schema.ListNestedAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "org_id": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "user_id": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - }, - }, - }, - "price_options": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "product_downloads": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "product_images": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "purpose": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "schema": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `must be "product"`, - Validators: []validator.String{ - stringvalidator.OneOf("product"), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "title": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "type": schema.StringAttribute{ - Computed: true, - Optional: true, - Default: stringdefault.StaticString("product"), - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - MarkdownDescription: `The type of Product:` + "\n" + - `` + "\n" + - `| type | description |` + "\n" + - `|----| ----|` + "\n" + - `| ` + "`" + `product` + "`" + ` | Represents a physical good |` + "\n" + - `| ` + "`" + `service` + "`" + ` | Represents a service or virtual product |` + "\n" + - `Default: "product"; must be one of ["product", "service"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "product", - "service", - ), - }, - }, - "updated_at": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Validators: []validator.String{ - validators.IsRFC3339(), - }, - }, - }, - } -} - -func (r *ProductResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected Resource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *ProductResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - var data *ProductResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(plan.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - request := *data.ToSharedProductCreate() - res, err := r.client.Product.CreateProduct(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 201 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Product != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedProduct(res.Product) - refreshPlan(ctx, plan, &data, resp.Diagnostics) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *ProductResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - var data *ProductResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - // read.product.hydrateread.product.hydrate impedance mismatch: boolean != classtrace=["Product#create.req"] - var hydrate *bool - var productID string - productID = data.ID.ValueString() - - // read.product.strictread.product.strict impedance mismatch: boolean != classtrace=["Product#create.req"] - var strict *bool - request := operations.GetProductRequest{ - Hydrate: hydrate, - ProductID: productID, - Strict: strict, - } - res, err := r.client.Product.GetProduct(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Product != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedProduct(res.Product) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *ProductResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { - var data *ProductResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - merge(ctx, req, resp, &data) - if resp.Diagnostics.HasError() { - return - } - - productPatch := *data.ToSharedProductPatch() - var productID string - productID = data.ID.ValueString() - - request := operations.PatchProductRequest{ - ProductPatch: productPatch, - ProductID: productID, - } - res, err := r.client.Product.PatchProduct(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Product != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedProduct(res.Product) - refreshPlan(ctx, plan, &data, resp.Diagnostics) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *ProductResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { - var data *ProductResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - var productID string - productID = data.ID.ValueString() - - request := operations.DeleteProductRequest{ - ProductID: productID, - } - res, err := r.client.Product.DeleteProduct(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - -} - -func (r *ProductResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { - resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...) -} diff --git a/internal/provider/product_resource_sdk.go b/internal/provider/product_resource_sdk.go deleted file mode 100644 index 6571396..0000000 --- a/internal/provider/product_resource_sdk.go +++ /dev/null @@ -1,615 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "encoding/json" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" - "time" -) - -func (r *ProductResourceModel) ToSharedProductCreate() *shared.ProductCreate { - additional := make(map[string]interface{}) - for additionalKey, additionalValue := range r.Additional { - var additionalInst interface{} - _ = json.Unmarshal([]byte(additionalValue.ValueString()), &additionalInst) - additional[additionalKey] = additionalInst - } - var availabilityFiles *shared.BaseRelation - if r.AvailabilityFiles != nil { - var dollarRelation []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem := range r.AvailabilityFiles.DollarRelation { - var tags []string = []string{} - for _, tagsItem := range dollarRelationItem.Tags { - tags = append(tags, tagsItem.ValueString()) - } - entityID := new(string) - if !dollarRelationItem.EntityID.IsUnknown() && !dollarRelationItem.EntityID.IsNull() { - *entityID = dollarRelationItem.EntityID.ValueString() - } else { - entityID = nil - } - dollarRelation = append(dollarRelation, shared.DollarRelation{ - Tags: tags, - EntityID: entityID, - }) - } - availabilityFiles = &shared.BaseRelation{ - DollarRelation: dollarRelation, - } - } - var files *shared.BaseRelation - if r.Files != nil { - var dollarRelation1 []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem1 := range r.Files.DollarRelation { - var tags1 []string = []string{} - for _, tagsItem1 := range dollarRelationItem1.Tags { - tags1 = append(tags1, tagsItem1.ValueString()) - } - entityId1 := new(string) - if !dollarRelationItem1.EntityID.IsUnknown() && !dollarRelationItem1.EntityID.IsNull() { - *entityId1 = dollarRelationItem1.EntityID.ValueString() - } else { - entityId1 = nil - } - dollarRelation1 = append(dollarRelation1, shared.DollarRelation{ - Tags: tags1, - EntityID: entityId1, - }) - } - files = &shared.BaseRelation{ - DollarRelation: dollarRelation1, - } - } - var manifest []string = []string{} - for _, manifestItem := range r.Manifest { - manifest = append(manifest, manifestItem.ValueString()) - } - var purpose []string = []string{} - for _, purposeItem := range r.Purpose { - purpose = append(purpose, purposeItem.ValueString()) - } - schema := new(shared.ProductCreateSchema) - if !r.Schema.IsUnknown() && !r.Schema.IsNull() { - *schema = shared.ProductCreateSchema(r.Schema.ValueString()) - } else { - schema = nil - } - var tags2 []string = []string{} - for _, tagsItem2 := range r.Tags { - tags2 = append(tags2, tagsItem2.ValueString()) - } - var active bool - active = r.Active.ValueBool() - - code := new(string) - if !r.Code.IsUnknown() && !r.Code.IsNull() { - *code = r.Code.ValueString() - } else { - code = nil - } - description := new(string) - if !r.Description.IsUnknown() && !r.Description.IsNull() { - *description = r.Description.ValueString() - } else { - description = nil - } - var feature []interface{} = []interface{}{} - for _, featureItem := range r.Feature { - var featureTmp interface{} - _ = json.Unmarshal([]byte(featureItem.ValueString()), &featureTmp) - feature = append(feature, featureTmp) - } - internalName := new(string) - if !r.InternalName.IsUnknown() && !r.InternalName.IsNull() { - *internalName = r.InternalName.ValueString() - } else { - internalName = nil - } - var name string - name = r.Name.ValueString() - - var priceOptions *shared.BaseRelation - if r.PriceOptions != nil { - var dollarRelation2 []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem2 := range r.PriceOptions.DollarRelation { - var tags3 []string = []string{} - for _, tagsItem3 := range dollarRelationItem2.Tags { - tags3 = append(tags3, tagsItem3.ValueString()) - } - entityId2 := new(string) - if !dollarRelationItem2.EntityID.IsUnknown() && !dollarRelationItem2.EntityID.IsNull() { - *entityId2 = dollarRelationItem2.EntityID.ValueString() - } else { - entityId2 = nil - } - dollarRelation2 = append(dollarRelation2, shared.DollarRelation{ - Tags: tags3, - EntityID: entityId2, - }) - } - priceOptions = &shared.BaseRelation{ - DollarRelation: dollarRelation2, - } - } - var productDownloads *shared.BaseRelation - if r.ProductDownloads != nil { - var dollarRelation3 []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem3 := range r.ProductDownloads.DollarRelation { - var tags4 []string = []string{} - for _, tagsItem4 := range dollarRelationItem3.Tags { - tags4 = append(tags4, tagsItem4.ValueString()) - } - entityId3 := new(string) - if !dollarRelationItem3.EntityID.IsUnknown() && !dollarRelationItem3.EntityID.IsNull() { - *entityId3 = dollarRelationItem3.EntityID.ValueString() - } else { - entityId3 = nil - } - dollarRelation3 = append(dollarRelation3, shared.DollarRelation{ - Tags: tags4, - EntityID: entityId3, - }) - } - productDownloads = &shared.BaseRelation{ - DollarRelation: dollarRelation3, - } - } - var productImages *shared.BaseRelation - if r.ProductImages != nil { - var dollarRelation4 []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem4 := range r.ProductImages.DollarRelation { - var tags5 []string = []string{} - for _, tagsItem5 := range dollarRelationItem4.Tags { - tags5 = append(tags5, tagsItem5.ValueString()) - } - entityId4 := new(string) - if !dollarRelationItem4.EntityID.IsUnknown() && !dollarRelationItem4.EntityID.IsNull() { - *entityId4 = dollarRelationItem4.EntityID.ValueString() - } else { - entityId4 = nil - } - dollarRelation4 = append(dollarRelation4, shared.DollarRelation{ - Tags: tags5, - EntityID: entityId4, - }) - } - productImages = &shared.BaseRelation{ - DollarRelation: dollarRelation4, - } - } - typeVar := new(shared.ProductCreateType) - if !r.Type.IsUnknown() && !r.Type.IsNull() { - *typeVar = shared.ProductCreateType(r.Type.ValueString()) - } else { - typeVar = nil - } - out := shared.ProductCreate{ - Additional: additional, - AvailabilityFiles: availabilityFiles, - Files: files, - Manifest: manifest, - Purpose: purpose, - Schema: schema, - Tags: tags2, - Active: active, - Code: code, - Description: description, - Feature: feature, - InternalName: internalName, - Name: name, - PriceOptions: priceOptions, - ProductDownloads: productDownloads, - ProductImages: productImages, - Type: typeVar, - } - return &out -} - -func (r *ProductResourceModel) RefreshFromSharedProduct(resp *shared.Product) { - if resp != nil { - if len(resp.Additional) > 0 { - r.Additional = make(map[string]types.String) - for key, value := range resp.Additional { - result, _ := json.Marshal(value) - r.Additional[key] = types.StringValue(string(result)) - } - } - if resp.ACL == nil { - r.ACL = nil - } else { - r.ACL = &tfTypes.BaseEntityACL{} - r.ACL.Delete = []types.String{} - for _, v := range resp.ACL.Delete { - r.ACL.Delete = append(r.ACL.Delete, types.StringValue(v)) - } - r.ACL.Edit = []types.String{} - for _, v := range resp.ACL.Edit { - r.ACL.Edit = append(r.ACL.Edit, types.StringValue(v)) - } - r.ACL.View = []types.String{} - for _, v := range resp.ACL.View { - r.ACL.View = append(r.ACL.View, types.StringValue(v)) - } - } - if resp.AvailabilityFiles == nil { - r.AvailabilityFiles = nil - } else { - r.AvailabilityFiles = &tfTypes.BaseRelation{} - r.AvailabilityFiles.DollarRelation = []tfTypes.DollarRelation{} - if len(r.AvailabilityFiles.DollarRelation) > len(resp.AvailabilityFiles.DollarRelation) { - r.AvailabilityFiles.DollarRelation = r.AvailabilityFiles.DollarRelation[:len(resp.AvailabilityFiles.DollarRelation)] - } - for dollarRelationCount, dollarRelationItem := range resp.AvailabilityFiles.DollarRelation { - var dollarRelation1 tfTypes.DollarRelation - dollarRelation1.Tags = []types.String{} - for _, v := range dollarRelationItem.Tags { - dollarRelation1.Tags = append(dollarRelation1.Tags, types.StringValue(v)) - } - dollarRelation1.EntityID = types.StringPointerValue(dollarRelationItem.EntityID) - if dollarRelationCount+1 > len(r.AvailabilityFiles.DollarRelation) { - r.AvailabilityFiles.DollarRelation = append(r.AvailabilityFiles.DollarRelation, dollarRelation1) - } else { - r.AvailabilityFiles.DollarRelation[dollarRelationCount].Tags = dollarRelation1.Tags - r.AvailabilityFiles.DollarRelation[dollarRelationCount].EntityID = dollarRelation1.EntityID - } - } - } - if resp.CreatedAt != nil { - r.CreatedAt = types.StringValue(resp.CreatedAt.Format(time.RFC3339Nano)) - } else { - r.CreatedAt = types.StringNull() - } - if resp.Files == nil { - r.Files = nil - } else { - r.Files = &tfTypes.BaseRelation{} - r.Files.DollarRelation = []tfTypes.DollarRelation{} - if len(r.Files.DollarRelation) > len(resp.Files.DollarRelation) { - r.Files.DollarRelation = r.Files.DollarRelation[:len(resp.Files.DollarRelation)] - } - for dollarRelationCount1, dollarRelationItem1 := range resp.Files.DollarRelation { - var dollarRelation3 tfTypes.DollarRelation - dollarRelation3.Tags = []types.String{} - for _, v := range dollarRelationItem1.Tags { - dollarRelation3.Tags = append(dollarRelation3.Tags, types.StringValue(v)) - } - dollarRelation3.EntityID = types.StringPointerValue(dollarRelationItem1.EntityID) - if dollarRelationCount1+1 > len(r.Files.DollarRelation) { - r.Files.DollarRelation = append(r.Files.DollarRelation, dollarRelation3) - } else { - r.Files.DollarRelation[dollarRelationCount1].Tags = dollarRelation3.Tags - r.Files.DollarRelation[dollarRelationCount1].EntityID = dollarRelation3.EntityID - } - } - } - r.ID = types.StringPointerValue(resp.ID) - r.Manifest = []types.String{} - for _, v := range resp.Manifest { - r.Manifest = append(r.Manifest, types.StringValue(v)) - } - r.Org = types.StringValue(resp.Org) - r.Owners = []tfTypes.BaseEntityOwner{} - if len(r.Owners) > len(resp.Owners) { - r.Owners = r.Owners[:len(resp.Owners)] - } - for ownersCount, ownersItem := range resp.Owners { - var owners1 tfTypes.BaseEntityOwner - owners1.OrgID = types.StringValue(ownersItem.OrgID) - owners1.UserID = types.StringPointerValue(ownersItem.UserID) - if ownersCount+1 > len(r.Owners) { - r.Owners = append(r.Owners, owners1) - } else { - r.Owners[ownersCount].OrgID = owners1.OrgID - r.Owners[ownersCount].UserID = owners1.UserID - } - } - r.Purpose = []types.String{} - for _, v := range resp.Purpose { - r.Purpose = append(r.Purpose, types.StringValue(v)) - } - r.Schema = types.StringValue(string(resp.Schema)) - r.Tags = []types.String{} - for _, v := range resp.Tags { - r.Tags = append(r.Tags, types.StringValue(v)) - } - r.Title = types.StringPointerValue(resp.Title) - if resp.UpdatedAt != nil { - r.UpdatedAt = types.StringValue(resp.UpdatedAt.Format(time.RFC3339Nano)) - } else { - r.UpdatedAt = types.StringNull() - } - r.Active = types.BoolValue(resp.Active) - r.Code = types.StringPointerValue(resp.Code) - r.Description = types.StringPointerValue(resp.Description) - r.Feature = nil - for _, featureItem := range resp.Feature { - var feature1 types.String - feature1Result, _ := json.Marshal(featureItem) - feature1 = types.StringValue(string(feature1Result)) - r.Feature = append(r.Feature, feature1) - } - r.InternalName = types.StringPointerValue(resp.InternalName) - r.Name = types.StringValue(resp.Name) - if resp.PriceOptions == nil { - r.PriceOptions = nil - } else { - r.PriceOptions = &tfTypes.BaseRelation{} - r.PriceOptions.DollarRelation = []tfTypes.DollarRelation{} - if len(r.PriceOptions.DollarRelation) > len(resp.PriceOptions.DollarRelation) { - r.PriceOptions.DollarRelation = r.PriceOptions.DollarRelation[:len(resp.PriceOptions.DollarRelation)] - } - for dollarRelationCount2, dollarRelationItem2 := range resp.PriceOptions.DollarRelation { - var dollarRelation5 tfTypes.DollarRelation - dollarRelation5.Tags = []types.String{} - for _, v := range dollarRelationItem2.Tags { - dollarRelation5.Tags = append(dollarRelation5.Tags, types.StringValue(v)) - } - dollarRelation5.EntityID = types.StringPointerValue(dollarRelationItem2.EntityID) - if dollarRelationCount2+1 > len(r.PriceOptions.DollarRelation) { - r.PriceOptions.DollarRelation = append(r.PriceOptions.DollarRelation, dollarRelation5) - } else { - r.PriceOptions.DollarRelation[dollarRelationCount2].Tags = dollarRelation5.Tags - r.PriceOptions.DollarRelation[dollarRelationCount2].EntityID = dollarRelation5.EntityID - } - } - } - if resp.ProductDownloads == nil { - r.ProductDownloads = nil - } else { - r.ProductDownloads = &tfTypes.BaseRelation{} - r.ProductDownloads.DollarRelation = []tfTypes.DollarRelation{} - if len(r.ProductDownloads.DollarRelation) > len(resp.ProductDownloads.DollarRelation) { - r.ProductDownloads.DollarRelation = r.ProductDownloads.DollarRelation[:len(resp.ProductDownloads.DollarRelation)] - } - for dollarRelationCount3, dollarRelationItem3 := range resp.ProductDownloads.DollarRelation { - var dollarRelation7 tfTypes.DollarRelation - dollarRelation7.Tags = []types.String{} - for _, v := range dollarRelationItem3.Tags { - dollarRelation7.Tags = append(dollarRelation7.Tags, types.StringValue(v)) - } - dollarRelation7.EntityID = types.StringPointerValue(dollarRelationItem3.EntityID) - if dollarRelationCount3+1 > len(r.ProductDownloads.DollarRelation) { - r.ProductDownloads.DollarRelation = append(r.ProductDownloads.DollarRelation, dollarRelation7) - } else { - r.ProductDownloads.DollarRelation[dollarRelationCount3].Tags = dollarRelation7.Tags - r.ProductDownloads.DollarRelation[dollarRelationCount3].EntityID = dollarRelation7.EntityID - } - } - } - if resp.ProductImages == nil { - r.ProductImages = nil - } else { - r.ProductImages = &tfTypes.BaseRelation{} - r.ProductImages.DollarRelation = []tfTypes.DollarRelation{} - if len(r.ProductImages.DollarRelation) > len(resp.ProductImages.DollarRelation) { - r.ProductImages.DollarRelation = r.ProductImages.DollarRelation[:len(resp.ProductImages.DollarRelation)] - } - for dollarRelationCount4, dollarRelationItem4 := range resp.ProductImages.DollarRelation { - var dollarRelation9 tfTypes.DollarRelation - dollarRelation9.Tags = []types.String{} - for _, v := range dollarRelationItem4.Tags { - dollarRelation9.Tags = append(dollarRelation9.Tags, types.StringValue(v)) - } - dollarRelation9.EntityID = types.StringPointerValue(dollarRelationItem4.EntityID) - if dollarRelationCount4+1 > len(r.ProductImages.DollarRelation) { - r.ProductImages.DollarRelation = append(r.ProductImages.DollarRelation, dollarRelation9) - } else { - r.ProductImages.DollarRelation[dollarRelationCount4].Tags = dollarRelation9.Tags - r.ProductImages.DollarRelation[dollarRelationCount4].EntityID = dollarRelation9.EntityID - } - } - } - if resp.Type != nil { - r.Type = types.StringValue(string(*resp.Type)) - } else { - r.Type = types.StringNull() - } - } -} - -func (r *ProductResourceModel) ToSharedProductPatch() *shared.ProductPatch { - additional := make(map[string]interface{}) - for additionalKey, additionalValue := range r.Additional { - var additionalInst interface{} - _ = json.Unmarshal([]byte(additionalValue.ValueString()), &additionalInst) - additional[additionalKey] = additionalInst - } - var availabilityFiles *shared.BaseRelation - if r.AvailabilityFiles != nil { - var dollarRelation []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem := range r.AvailabilityFiles.DollarRelation { - var tags []string = []string{} - for _, tagsItem := range dollarRelationItem.Tags { - tags = append(tags, tagsItem.ValueString()) - } - entityID := new(string) - if !dollarRelationItem.EntityID.IsUnknown() && !dollarRelationItem.EntityID.IsNull() { - *entityID = dollarRelationItem.EntityID.ValueString() - } else { - entityID = nil - } - dollarRelation = append(dollarRelation, shared.DollarRelation{ - Tags: tags, - EntityID: entityID, - }) - } - availabilityFiles = &shared.BaseRelation{ - DollarRelation: dollarRelation, - } - } - var files *shared.BaseRelation - if r.Files != nil { - var dollarRelation1 []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem1 := range r.Files.DollarRelation { - var tags1 []string = []string{} - for _, tagsItem1 := range dollarRelationItem1.Tags { - tags1 = append(tags1, tagsItem1.ValueString()) - } - entityId1 := new(string) - if !dollarRelationItem1.EntityID.IsUnknown() && !dollarRelationItem1.EntityID.IsNull() { - *entityId1 = dollarRelationItem1.EntityID.ValueString() - } else { - entityId1 = nil - } - dollarRelation1 = append(dollarRelation1, shared.DollarRelation{ - Tags: tags1, - EntityID: entityId1, - }) - } - files = &shared.BaseRelation{ - DollarRelation: dollarRelation1, - } - } - var manifest []string = []string{} - for _, manifestItem := range r.Manifest { - manifest = append(manifest, manifestItem.ValueString()) - } - var purpose []string = []string{} - for _, purposeItem := range r.Purpose { - purpose = append(purpose, purposeItem.ValueString()) - } - schema := new(shared.ProductPatchSchema) - if !r.Schema.IsUnknown() && !r.Schema.IsNull() { - *schema = shared.ProductPatchSchema(r.Schema.ValueString()) - } else { - schema = nil - } - var tags2 []string = []string{} - for _, tagsItem2 := range r.Tags { - tags2 = append(tags2, tagsItem2.ValueString()) - } - active := new(bool) - if !r.Active.IsUnknown() && !r.Active.IsNull() { - *active = r.Active.ValueBool() - } else { - active = nil - } - code := new(string) - if !r.Code.IsUnknown() && !r.Code.IsNull() { - *code = r.Code.ValueString() - } else { - code = nil - } - description := new(string) - if !r.Description.IsUnknown() && !r.Description.IsNull() { - *description = r.Description.ValueString() - } else { - description = nil - } - var feature []interface{} = []interface{}{} - for _, featureItem := range r.Feature { - var featureTmp interface{} - _ = json.Unmarshal([]byte(featureItem.ValueString()), &featureTmp) - feature = append(feature, featureTmp) - } - internalName := new(string) - if !r.InternalName.IsUnknown() && !r.InternalName.IsNull() { - *internalName = r.InternalName.ValueString() - } else { - internalName = nil - } - name := new(string) - if !r.Name.IsUnknown() && !r.Name.IsNull() { - *name = r.Name.ValueString() - } else { - name = nil - } - var priceOptions *shared.BaseRelation - if r.PriceOptions != nil { - var dollarRelation2 []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem2 := range r.PriceOptions.DollarRelation { - var tags3 []string = []string{} - for _, tagsItem3 := range dollarRelationItem2.Tags { - tags3 = append(tags3, tagsItem3.ValueString()) - } - entityId2 := new(string) - if !dollarRelationItem2.EntityID.IsUnknown() && !dollarRelationItem2.EntityID.IsNull() { - *entityId2 = dollarRelationItem2.EntityID.ValueString() - } else { - entityId2 = nil - } - dollarRelation2 = append(dollarRelation2, shared.DollarRelation{ - Tags: tags3, - EntityID: entityId2, - }) - } - priceOptions = &shared.BaseRelation{ - DollarRelation: dollarRelation2, - } - } - var productDownloads *shared.BaseRelation - if r.ProductDownloads != nil { - var dollarRelation3 []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem3 := range r.ProductDownloads.DollarRelation { - var tags4 []string = []string{} - for _, tagsItem4 := range dollarRelationItem3.Tags { - tags4 = append(tags4, tagsItem4.ValueString()) - } - entityId3 := new(string) - if !dollarRelationItem3.EntityID.IsUnknown() && !dollarRelationItem3.EntityID.IsNull() { - *entityId3 = dollarRelationItem3.EntityID.ValueString() - } else { - entityId3 = nil - } - dollarRelation3 = append(dollarRelation3, shared.DollarRelation{ - Tags: tags4, - EntityID: entityId3, - }) - } - productDownloads = &shared.BaseRelation{ - DollarRelation: dollarRelation3, - } - } - var productImages *shared.BaseRelation - if r.ProductImages != nil { - var dollarRelation4 []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem4 := range r.ProductImages.DollarRelation { - var tags5 []string = []string{} - for _, tagsItem5 := range dollarRelationItem4.Tags { - tags5 = append(tags5, tagsItem5.ValueString()) - } - entityId4 := new(string) - if !dollarRelationItem4.EntityID.IsUnknown() && !dollarRelationItem4.EntityID.IsNull() { - *entityId4 = dollarRelationItem4.EntityID.ValueString() - } else { - entityId4 = nil - } - dollarRelation4 = append(dollarRelation4, shared.DollarRelation{ - Tags: tags5, - EntityID: entityId4, - }) - } - productImages = &shared.BaseRelation{ - DollarRelation: dollarRelation4, - } - } - typeVar := new(shared.ProductPatchType) - if !r.Type.IsUnknown() && !r.Type.IsNull() { - *typeVar = shared.ProductPatchType(r.Type.ValueString()) - } else { - typeVar = nil - } - out := shared.ProductPatch{ - Additional: additional, - AvailabilityFiles: availabilityFiles, - Files: files, - Manifest: manifest, - Purpose: purpose, - Schema: schema, - Tags: tags2, - Active: active, - Code: code, - Description: description, - Feature: feature, - InternalName: internalName, - Name: name, - PriceOptions: priceOptions, - ProductDownloads: productDownloads, - ProductImages: productImages, - Type: typeVar, - } - return &out -} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index d964638..79d21bf 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -87,10 +87,13 @@ func (p *EpilotProductProvider) Configure(ctx context.Context, req provider.Conf EpilotOrg: epilotOrg, } + httpClient := http.DefaultClient + httpClient.Transport = NewLoggingHTTPTransport(http.DefaultTransport) + opts := []sdk.SDKOption{ sdk.WithServerURL(ServerURL), sdk.WithSecurity(security), - sdk.WithClient(http.DefaultClient), + sdk.WithClient(httpClient), } client := sdk.New(opts...) @@ -99,19 +102,11 @@ func (p *EpilotProductProvider) Configure(ctx context.Context, req provider.Conf } func (p *EpilotProductProvider) Resources(ctx context.Context) []func() resource.Resource { - return []func() resource.Resource{ - NewPriceResource, - NewProductResource, - NewTaxResource, - } + return []func() resource.Resource{} } func (p *EpilotProductProvider) DataSources(ctx context.Context) []func() datasource.DataSource { - return []func() datasource.DataSource{ - NewPriceDataSource, - NewProductDataSource, - NewTaxDataSource, - } + return []func() datasource.DataSource{} } func New(version string) func() provider.Provider { diff --git a/internal/provider/reflect/helpers.go b/internal/provider/reflect/helpers.go index b17719d..8085789 100644 --- a/internal/provider/reflect/helpers.go +++ b/internal/provider/reflect/helpers.go @@ -46,7 +46,7 @@ func commaSeparatedString(in []string) string { // getStructTags returns a map of Terraform field names to their position in // the tags of the struct `in`. `in` must be a struct. -func getStructTags(_ context.Context, in reflect.Value, path path.Path, opts Options) (map[string]int, error) { +func getStructTags(_ context.Context, in reflect.Value, path path.Path, _ Options) (map[string]int, error) { tags := map[string]int{} typ := trueReflectValue(in).Type() if typ.Kind() != reflect.Struct { diff --git a/internal/provider/tax_data_source.go b/internal/provider/tax_data_source.go deleted file mode 100644 index 4568e1c..0000000 --- a/internal/provider/tax_data_source.go +++ /dev/null @@ -1,262 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/operations" - "github.com/hashicorp/terraform-plugin-framework/datasource" - "github.com/hashicorp/terraform-plugin-framework/datasource/schema" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ datasource.DataSource = &TaxDataSource{} -var _ datasource.DataSourceWithConfigure = &TaxDataSource{} - -func NewTaxDataSource() datasource.DataSource { - return &TaxDataSource{} -} - -// TaxDataSource is the data source implementation. -type TaxDataSource struct { - client *sdk.SDK -} - -// TaxDataSourceModel describes the data model. -type TaxDataSourceModel struct { - ACL *tfTypes.BaseEntityACL `tfsdk:"acl"` - Active types.Bool `tfsdk:"active"` - Additional map[string]types.String `tfsdk:"additional"` - CreatedAt types.String `tfsdk:"created_at"` - Description types.String `tfsdk:"description"` - Files *tfTypes.BaseRelation `tfsdk:"files"` - Hydrate types.Bool `tfsdk:"hydrate"` - ID types.String `tfsdk:"id"` - Manifest []types.String `tfsdk:"manifest"` - Org types.String `tfsdk:"org"` - Owners []tfTypes.BaseEntityOwner `tfsdk:"owners"` - Rate types.String `tfsdk:"rate"` - Region types.String `tfsdk:"region"` - Schema types.String `tfsdk:"schema"` - Strict types.Bool `tfsdk:"strict"` - Tags []types.String `tfsdk:"tags"` - Title types.String `tfsdk:"title"` - Type types.String `tfsdk:"type"` - UpdatedAt types.String `tfsdk:"updated_at"` -} - -// Metadata returns the data source type name. -func (r *TaxDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_tax" -} - -// Schema defines the schema for the data source. -func (r *TaxDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "Tax DataSource", - - Attributes: map[string]schema.Attribute{ - "acl": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "delete": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "edit": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "view": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - Description: `Access control list (ACL) for an entity. Defines sharing access to external orgs or users.`, - }, - "active": schema.BoolAttribute{ - Computed: true, - }, - "additional": schema.MapAttribute{ - Computed: true, - ElementType: types.StringType, - Description: `Additional fields that are not part of the schema`, - }, - "created_at": schema.StringAttribute{ - Computed: true, - }, - "description": schema.StringAttribute{ - Computed: true, - }, - "files": schema.SingleNestedAttribute{ - Computed: true, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "hydrate": schema.BoolAttribute{ - Computed: true, - Optional: true, - Description: `Hydrates entities in relations when passed true`, - }, - "id": schema.StringAttribute{ - Computed: true, - }, - "manifest": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - Description: `Manifest ID used to create/update the entity`, - }, - "org": schema.StringAttribute{ - Computed: true, - Description: `Organization Id the entity belongs to`, - }, - "owners": schema.ListNestedAttribute{ - Computed: true, - NestedObject: schema.NestedAttributeObject{ - Attributes: map[string]schema.Attribute{ - "org_id": schema.StringAttribute{ - Computed: true, - }, - "user_id": schema.StringAttribute{ - Computed: true, - }, - }, - }, - }, - "rate": schema.StringAttribute{ - Computed: true, - }, - "region": schema.StringAttribute{ - Computed: true, - }, - "schema": schema.StringAttribute{ - Computed: true, - }, - "strict": schema.BoolAttribute{ - Computed: true, - Optional: true, - Description: `When passed true, the response will contain only fields that match the schema, with non-matching fields included in ` + "`" + `__additional` + "`" + ``, - }, - "tags": schema.ListAttribute{ - Computed: true, - ElementType: types.StringType, - }, - "title": schema.StringAttribute{ - Computed: true, - }, - "type": schema.StringAttribute{ - Computed: true, - }, - "updated_at": schema.StringAttribute{ - Computed: true, - }, - }, - } -} - -func (r *TaxDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected DataSource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *TaxDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { - var data *TaxDataSourceModel - var item types.Object - - resp.Diagnostics.Append(req.Config.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - hydrate := new(bool) - if !data.Hydrate.IsUnknown() && !data.Hydrate.IsNull() { - *hydrate = data.Hydrate.ValueBool() - } else { - hydrate = nil - } - strict := new(bool) - if !data.Strict.IsUnknown() && !data.Strict.IsNull() { - *strict = data.Strict.ValueBool() - } else { - strict = nil - } - var taxID string - taxID = data.ID.ValueString() - - request := operations.GetTaxRequest{ - Hydrate: hydrate, - Strict: strict, - TaxID: taxID, - } - res, err := r.client.Tax.GetTax(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Tax != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedTax(res.Tax) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} diff --git a/internal/provider/tax_data_source_sdk.go b/internal/provider/tax_data_source_sdk.go deleted file mode 100644 index 963c28d..0000000 --- a/internal/provider/tax_data_source_sdk.go +++ /dev/null @@ -1,105 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "encoding/json" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" - "time" -) - -func (r *TaxDataSourceModel) RefreshFromSharedTax(resp *shared.Tax) { - if resp != nil { - if len(resp.Additional) > 0 { - r.Additional = make(map[string]types.String) - for key, value := range resp.Additional { - result, _ := json.Marshal(value) - r.Additional[key] = types.StringValue(string(result)) - } - } - if resp.ACL == nil { - r.ACL = nil - } else { - r.ACL = &tfTypes.BaseEntityACL{} - r.ACL.Delete = []types.String{} - for _, v := range resp.ACL.Delete { - r.ACL.Delete = append(r.ACL.Delete, types.StringValue(v)) - } - r.ACL.Edit = []types.String{} - for _, v := range resp.ACL.Edit { - r.ACL.Edit = append(r.ACL.Edit, types.StringValue(v)) - } - r.ACL.View = []types.String{} - for _, v := range resp.ACL.View { - r.ACL.View = append(r.ACL.View, types.StringValue(v)) - } - } - if resp.CreatedAt != nil { - r.CreatedAt = types.StringValue(resp.CreatedAt.Format(time.RFC3339Nano)) - } else { - r.CreatedAt = types.StringNull() - } - if resp.Files == nil { - r.Files = nil - } else { - r.Files = &tfTypes.BaseRelation{} - r.Files.DollarRelation = []tfTypes.DollarRelation{} - if len(r.Files.DollarRelation) > len(resp.Files.DollarRelation) { - r.Files.DollarRelation = r.Files.DollarRelation[:len(resp.Files.DollarRelation)] - } - for dollarRelationCount, dollarRelationItem := range resp.Files.DollarRelation { - var dollarRelation1 tfTypes.DollarRelation - dollarRelation1.Tags = []types.String{} - for _, v := range dollarRelationItem.Tags { - dollarRelation1.Tags = append(dollarRelation1.Tags, types.StringValue(v)) - } - dollarRelation1.EntityID = types.StringPointerValue(dollarRelationItem.EntityID) - if dollarRelationCount+1 > len(r.Files.DollarRelation) { - r.Files.DollarRelation = append(r.Files.DollarRelation, dollarRelation1) - } else { - r.Files.DollarRelation[dollarRelationCount].Tags = dollarRelation1.Tags - r.Files.DollarRelation[dollarRelationCount].EntityID = dollarRelation1.EntityID - } - } - } - r.ID = types.StringPointerValue(resp.ID) - r.Manifest = []types.String{} - for _, v := range resp.Manifest { - r.Manifest = append(r.Manifest, types.StringValue(v)) - } - r.Org = types.StringValue(resp.Org) - r.Owners = []tfTypes.BaseEntityOwner{} - if len(r.Owners) > len(resp.Owners) { - r.Owners = r.Owners[:len(resp.Owners)] - } - for ownersCount, ownersItem := range resp.Owners { - var owners1 tfTypes.BaseEntityOwner - owners1.OrgID = types.StringValue(ownersItem.OrgID) - owners1.UserID = types.StringPointerValue(ownersItem.UserID) - if ownersCount+1 > len(r.Owners) { - r.Owners = append(r.Owners, owners1) - } else { - r.Owners[ownersCount].OrgID = owners1.OrgID - r.Owners[ownersCount].UserID = owners1.UserID - } - } - r.Schema = types.StringValue(string(resp.Schema)) - r.Tags = []types.String{} - for _, v := range resp.Tags { - r.Tags = append(r.Tags, types.StringValue(v)) - } - r.Title = types.StringPointerValue(resp.Title) - if resp.UpdatedAt != nil { - r.UpdatedAt = types.StringValue(resp.UpdatedAt.Format(time.RFC3339Nano)) - } else { - r.UpdatedAt = types.StringNull() - } - r.Active = types.BoolValue(resp.Active) - r.Description = types.StringPointerValue(resp.Description) - r.Rate = types.StringValue(resp.Rate) - r.Region = types.StringValue(resp.Region) - r.Type = types.StringValue(string(resp.Type)) - } -} diff --git a/internal/provider/tax_resource.go b/internal/provider/tax_resource.go deleted file mode 100644 index 4e92d89..0000000 --- a/internal/provider/tax_resource.go +++ /dev/null @@ -1,506 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "context" - "fmt" - speakeasy_boolplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/boolplanmodifier" - speakeasy_listplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/listplanmodifier" - speakeasy_mapplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/mapplanmodifier" - speakeasy_objectplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/objectplanmodifier" - speakeasy_stringplanmodifier "github.com/epilot-dev/terraform-provider-epilot-product/internal/planmodifiers/stringplanmodifier" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/operations" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/validators" - speakeasy_objectvalidators "github.com/epilot-dev/terraform-provider-epilot-product/internal/validators/objectvalidators" - "github.com/hashicorp/terraform-plugin-framework-validators/mapvalidator" - "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" - "github.com/hashicorp/terraform-plugin-framework/path" - "github.com/hashicorp/terraform-plugin-framework/resource" - "github.com/hashicorp/terraform-plugin-framework/resource/schema" - "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" - "github.com/hashicorp/terraform-plugin-framework/schema/validator" - "github.com/hashicorp/terraform-plugin-framework/types" - "github.com/hashicorp/terraform-plugin-framework/types/basetypes" -) - -// Ensure provider defined types fully satisfy framework interfaces. -var _ resource.Resource = &TaxResource{} -var _ resource.ResourceWithImportState = &TaxResource{} - -func NewTaxResource() resource.Resource { - return &TaxResource{} -} - -// TaxResource defines the resource implementation. -type TaxResource struct { - client *sdk.SDK -} - -// TaxResourceModel describes the resource data model. -type TaxResourceModel struct { - ACL *tfTypes.BaseEntityACL `tfsdk:"acl"` - Active types.Bool `tfsdk:"active"` - Additional map[string]types.String `tfsdk:"additional"` - CreatedAt types.String `tfsdk:"created_at"` - Description types.String `tfsdk:"description"` - Files *tfTypes.BaseRelation `tfsdk:"files"` - ID types.String `tfsdk:"id"` - Manifest []types.String `tfsdk:"manifest"` - Org types.String `tfsdk:"org"` - Owners []tfTypes.BaseEntityOwner `tfsdk:"owners"` - Rate types.String `tfsdk:"rate"` - Region types.String `tfsdk:"region"` - Schema types.String `tfsdk:"schema"` - Tags []types.String `tfsdk:"tags"` - Title types.String `tfsdk:"title"` - Type types.String `tfsdk:"type"` - UpdatedAt types.String `tfsdk:"updated_at"` -} - -func (r *TaxResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { - resp.TypeName = req.ProviderTypeName + "_tax" -} - -func (r *TaxResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { - resp.Schema = schema.Schema{ - MarkdownDescription: "Tax Resource", - Attributes: map[string]schema.Attribute{ - "acl": schema.SingleNestedAttribute{ - Computed: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "delete": schema.ListAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "edit": schema.ListAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "view": schema.ListAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - Description: `Access control list (ACL) for an entity. Defines sharing access to external orgs or users.`, - }, - "active": schema.BoolAttribute{ - Required: true, - PlanModifiers: []planmodifier.Bool{ - speakeasy_boolplanmodifier.SuppressDiff(speakeasy_boolplanmodifier.ExplicitSuppress), - }, - }, - "additional": schema.MapAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Map{ - speakeasy_mapplanmodifier.SuppressDiff(speakeasy_mapplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - Description: `Additional fields that are not part of the schema`, - Validators: []validator.Map{ - mapvalidator.ValueStringsAre(validators.IsValidJSON()), - }, - }, - "created_at": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Validators: []validator.String{ - validators.IsRFC3339(), - }, - }, - "description": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "files": schema.SingleNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "dollar_relation": schema.ListNestedAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - Validators: []validator.Object{ - speakeasy_objectvalidators.NotNull(), - }, - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "entity_id": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - }, - }, - }, - }, - }, - "id": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "manifest": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - Description: `Manifest ID used to create/update the entity`, - }, - "org": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `Organization Id the entity belongs to`, - }, - "owners": schema.ListNestedAttribute{ - Computed: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - NestedObject: schema.NestedAttributeObject{ - PlanModifiers: []planmodifier.Object{ - speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), - }, - Attributes: map[string]schema.Attribute{ - "org_id": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "user_id": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - }, - }, - }, - "rate": schema.StringAttribute{ - Required: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "region": schema.StringAttribute{ - Required: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "schema": schema.StringAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `must be "tax"`, - Validators: []validator.String{ - stringvalidator.OneOf("tax"), - }, - }, - "tags": schema.ListAttribute{ - Computed: true, - Optional: true, - PlanModifiers: []planmodifier.List{ - speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), - }, - ElementType: types.StringType, - }, - "title": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - }, - "type": schema.StringAttribute{ - Required: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Description: `must be one of ["VAT", "Custom"]`, - Validators: []validator.String{ - stringvalidator.OneOf( - "VAT", - "Custom", - ), - }, - }, - "updated_at": schema.StringAttribute{ - Computed: true, - PlanModifiers: []planmodifier.String{ - speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), - }, - Validators: []validator.String{ - validators.IsRFC3339(), - }, - }, - }, - } -} - -func (r *TaxResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { - // Prevent panic if the provider has not been configured. - if req.ProviderData == nil { - return - } - - client, ok := req.ProviderData.(*sdk.SDK) - - if !ok { - resp.Diagnostics.AddError( - "Unexpected Resource Configure Type", - fmt.Sprintf("Expected *sdk.SDK, got: %T. Please report this issue to the provider developers.", req.ProviderData), - ) - - return - } - - r.client = client -} - -func (r *TaxResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { - var data *TaxResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(plan.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - request := *data.ToSharedTaxCreate() - res, err := r.client.Tax.CreateTax(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 201 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Tax != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedTax(res.Tax) - refreshPlan(ctx, plan, &data, resp.Diagnostics) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *TaxResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { - var data *TaxResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - // read.tax.hydrateread.tax.hydrate impedance mismatch: boolean != classtrace=["Tax#create.req"] - var hydrate *bool - // read.tax.strictread.tax.strict impedance mismatch: boolean != classtrace=["Tax#create.req"] - var strict *bool - var taxID string - taxID = data.ID.ValueString() - - request := operations.GetTaxRequest{ - Hydrate: hydrate, - Strict: strict, - TaxID: taxID, - } - res, err := r.client.Tax.GetTax(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode == 404 { - resp.State.RemoveResource(ctx) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Tax != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedTax(res.Tax) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *TaxResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { - var data *TaxResourceModel - var plan types.Object - - resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) - if resp.Diagnostics.HasError() { - return - } - - merge(ctx, req, resp, &data) - if resp.Diagnostics.HasError() { - return - } - - taxPatch := *data.ToSharedTaxPatch() - var taxID string - taxID = data.ID.ValueString() - - request := operations.PatchTaxRequest{ - TaxPatch: taxPatch, - TaxID: taxID, - } - res, err := r.client.Tax.PatchTax(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - if !(res.Tax != nil) { - resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) - return - } - data.RefreshFromSharedTax(res.Tax) - refreshPlan(ctx, plan, &data, resp.Diagnostics) - - // Save updated data into Terraform state - resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) -} - -func (r *TaxResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { - var data *TaxResourceModel - var item types.Object - - resp.Diagnostics.Append(req.State.Get(ctx, &item)...) - if resp.Diagnostics.HasError() { - return - } - - resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ - UnhandledNullAsEmpty: true, - UnhandledUnknownAsEmpty: true, - })...) - - if resp.Diagnostics.HasError() { - return - } - - var taxID string - taxID = data.ID.ValueString() - - request := operations.DeleteTaxRequest{ - TaxID: taxID, - } - res, err := r.client.Tax.DeleteTax(ctx, request) - if err != nil { - resp.Diagnostics.AddError("failure to invoke API", err.Error()) - if res != nil && res.RawResponse != nil { - resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) - } - return - } - if res == nil { - resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) - return - } - if res.StatusCode != 200 { - resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) - return - } - -} - -func (r *TaxResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { - resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...) -} diff --git a/internal/provider/tax_resource_sdk.go b/internal/provider/tax_resource_sdk.go deleted file mode 100644 index 4257de0..0000000 --- a/internal/provider/tax_resource_sdk.go +++ /dev/null @@ -1,269 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package provider - -import ( - "encoding/json" - tfTypes "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/types" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/shared" - "github.com/hashicorp/terraform-plugin-framework/types" - "time" -) - -func (r *TaxResourceModel) ToSharedTaxCreate() *shared.TaxCreate { - additional := make(map[string]interface{}) - for additionalKey, additionalValue := range r.Additional { - var additionalInst interface{} - _ = json.Unmarshal([]byte(additionalValue.ValueString()), &additionalInst) - additional[additionalKey] = additionalInst - } - var files *shared.BaseRelation - if r.Files != nil { - var dollarRelation []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem := range r.Files.DollarRelation { - var tags []string = []string{} - for _, tagsItem := range dollarRelationItem.Tags { - tags = append(tags, tagsItem.ValueString()) - } - entityID := new(string) - if !dollarRelationItem.EntityID.IsUnknown() && !dollarRelationItem.EntityID.IsNull() { - *entityID = dollarRelationItem.EntityID.ValueString() - } else { - entityID = nil - } - dollarRelation = append(dollarRelation, shared.DollarRelation{ - Tags: tags, - EntityID: entityID, - }) - } - files = &shared.BaseRelation{ - DollarRelation: dollarRelation, - } - } - var manifest []string = []string{} - for _, manifestItem := range r.Manifest { - manifest = append(manifest, manifestItem.ValueString()) - } - schema := new(shared.TaxCreateSchema) - if !r.Schema.IsUnknown() && !r.Schema.IsNull() { - *schema = shared.TaxCreateSchema(r.Schema.ValueString()) - } else { - schema = nil - } - var tags1 []string = []string{} - for _, tagsItem1 := range r.Tags { - tags1 = append(tags1, tagsItem1.ValueString()) - } - var active bool - active = r.Active.ValueBool() - - description := new(string) - if !r.Description.IsUnknown() && !r.Description.IsNull() { - *description = r.Description.ValueString() - } else { - description = nil - } - var rate string - rate = r.Rate.ValueString() - - var region string - region = r.Region.ValueString() - - typeVar := shared.TaxCreateType(r.Type.ValueString()) - out := shared.TaxCreate{ - Additional: additional, - Files: files, - Manifest: manifest, - Schema: schema, - Tags: tags1, - Active: active, - Description: description, - Rate: rate, - Region: region, - Type: typeVar, - } - return &out -} - -func (r *TaxResourceModel) RefreshFromSharedTax(resp *shared.Tax) { - if resp != nil { - if len(resp.Additional) > 0 { - r.Additional = make(map[string]types.String) - for key, value := range resp.Additional { - result, _ := json.Marshal(value) - r.Additional[key] = types.StringValue(string(result)) - } - } - if resp.ACL == nil { - r.ACL = nil - } else { - r.ACL = &tfTypes.BaseEntityACL{} - r.ACL.Delete = []types.String{} - for _, v := range resp.ACL.Delete { - r.ACL.Delete = append(r.ACL.Delete, types.StringValue(v)) - } - r.ACL.Edit = []types.String{} - for _, v := range resp.ACL.Edit { - r.ACL.Edit = append(r.ACL.Edit, types.StringValue(v)) - } - r.ACL.View = []types.String{} - for _, v := range resp.ACL.View { - r.ACL.View = append(r.ACL.View, types.StringValue(v)) - } - } - if resp.CreatedAt != nil { - r.CreatedAt = types.StringValue(resp.CreatedAt.Format(time.RFC3339Nano)) - } else { - r.CreatedAt = types.StringNull() - } - if resp.Files == nil { - r.Files = nil - } else { - r.Files = &tfTypes.BaseRelation{} - r.Files.DollarRelation = []tfTypes.DollarRelation{} - if len(r.Files.DollarRelation) > len(resp.Files.DollarRelation) { - r.Files.DollarRelation = r.Files.DollarRelation[:len(resp.Files.DollarRelation)] - } - for dollarRelationCount, dollarRelationItem := range resp.Files.DollarRelation { - var dollarRelation1 tfTypes.DollarRelation - dollarRelation1.Tags = []types.String{} - for _, v := range dollarRelationItem.Tags { - dollarRelation1.Tags = append(dollarRelation1.Tags, types.StringValue(v)) - } - dollarRelation1.EntityID = types.StringPointerValue(dollarRelationItem.EntityID) - if dollarRelationCount+1 > len(r.Files.DollarRelation) { - r.Files.DollarRelation = append(r.Files.DollarRelation, dollarRelation1) - } else { - r.Files.DollarRelation[dollarRelationCount].Tags = dollarRelation1.Tags - r.Files.DollarRelation[dollarRelationCount].EntityID = dollarRelation1.EntityID - } - } - } - r.ID = types.StringPointerValue(resp.ID) - r.Manifest = []types.String{} - for _, v := range resp.Manifest { - r.Manifest = append(r.Manifest, types.StringValue(v)) - } - r.Org = types.StringValue(resp.Org) - r.Owners = []tfTypes.BaseEntityOwner{} - if len(r.Owners) > len(resp.Owners) { - r.Owners = r.Owners[:len(resp.Owners)] - } - for ownersCount, ownersItem := range resp.Owners { - var owners1 tfTypes.BaseEntityOwner - owners1.OrgID = types.StringValue(ownersItem.OrgID) - owners1.UserID = types.StringPointerValue(ownersItem.UserID) - if ownersCount+1 > len(r.Owners) { - r.Owners = append(r.Owners, owners1) - } else { - r.Owners[ownersCount].OrgID = owners1.OrgID - r.Owners[ownersCount].UserID = owners1.UserID - } - } - r.Schema = types.StringValue(string(resp.Schema)) - r.Tags = []types.String{} - for _, v := range resp.Tags { - r.Tags = append(r.Tags, types.StringValue(v)) - } - r.Title = types.StringPointerValue(resp.Title) - if resp.UpdatedAt != nil { - r.UpdatedAt = types.StringValue(resp.UpdatedAt.Format(time.RFC3339Nano)) - } else { - r.UpdatedAt = types.StringNull() - } - r.Active = types.BoolValue(resp.Active) - r.Description = types.StringPointerValue(resp.Description) - r.Rate = types.StringValue(resp.Rate) - r.Region = types.StringValue(resp.Region) - r.Type = types.StringValue(string(resp.Type)) - } -} - -func (r *TaxResourceModel) ToSharedTaxPatch() *shared.TaxPatch { - additional := make(map[string]interface{}) - for additionalKey, additionalValue := range r.Additional { - var additionalInst interface{} - _ = json.Unmarshal([]byte(additionalValue.ValueString()), &additionalInst) - additional[additionalKey] = additionalInst - } - var files *shared.BaseRelation - if r.Files != nil { - var dollarRelation []shared.DollarRelation = []shared.DollarRelation{} - for _, dollarRelationItem := range r.Files.DollarRelation { - var tags []string = []string{} - for _, tagsItem := range dollarRelationItem.Tags { - tags = append(tags, tagsItem.ValueString()) - } - entityID := new(string) - if !dollarRelationItem.EntityID.IsUnknown() && !dollarRelationItem.EntityID.IsNull() { - *entityID = dollarRelationItem.EntityID.ValueString() - } else { - entityID = nil - } - dollarRelation = append(dollarRelation, shared.DollarRelation{ - Tags: tags, - EntityID: entityID, - }) - } - files = &shared.BaseRelation{ - DollarRelation: dollarRelation, - } - } - var manifest []string = []string{} - for _, manifestItem := range r.Manifest { - manifest = append(manifest, manifestItem.ValueString()) - } - schema := new(shared.TaxPatchSchema) - if !r.Schema.IsUnknown() && !r.Schema.IsNull() { - *schema = shared.TaxPatchSchema(r.Schema.ValueString()) - } else { - schema = nil - } - var tags1 []string = []string{} - for _, tagsItem1 := range r.Tags { - tags1 = append(tags1, tagsItem1.ValueString()) - } - active := new(bool) - if !r.Active.IsUnknown() && !r.Active.IsNull() { - *active = r.Active.ValueBool() - } else { - active = nil - } - description := new(string) - if !r.Description.IsUnknown() && !r.Description.IsNull() { - *description = r.Description.ValueString() - } else { - description = nil - } - rate := new(string) - if !r.Rate.IsUnknown() && !r.Rate.IsNull() { - *rate = r.Rate.ValueString() - } else { - rate = nil - } - region := new(string) - if !r.Region.IsUnknown() && !r.Region.IsNull() { - *region = r.Region.ValueString() - } else { - region = nil - } - typeVar := new(shared.TaxPatchType) - if !r.Type.IsUnknown() && !r.Type.IsNull() { - *typeVar = shared.TaxPatchType(r.Type.ValueString()) - } else { - typeVar = nil - } - out := shared.TaxPatch{ - Additional: additional, - Files: files, - Manifest: manifest, - Schema: schema, - Tags: tags1, - Active: active, - Description: description, - Rate: rate, - Region: region, - Type: typeVar, - } - return &out -} diff --git a/internal/provider/types/base_entity_acl.go b/internal/provider/types/base_entity_acl.go deleted file mode 100644 index ea0f5f9..0000000 --- a/internal/provider/types/base_entity_acl.go +++ /dev/null @@ -1,11 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -import "github.com/hashicorp/terraform-plugin-framework/types" - -type BaseEntityACL struct { - Delete []types.String `tfsdk:"delete"` - Edit []types.String `tfsdk:"edit"` - View []types.String `tfsdk:"view"` -} diff --git a/internal/provider/types/base_entity_owner.go b/internal/provider/types/base_entity_owner.go deleted file mode 100644 index 10d217d..0000000 --- a/internal/provider/types/base_entity_owner.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -import "github.com/hashicorp/terraform-plugin-framework/types" - -type BaseEntityOwner struct { - OrgID types.String `tfsdk:"org_id"` - UserID types.String `tfsdk:"user_id"` -} diff --git a/internal/provider/types/base_relation.go b/internal/provider/types/base_relation.go deleted file mode 100644 index dd9aceb..0000000 --- a/internal/provider/types/base_relation.go +++ /dev/null @@ -1,7 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -type BaseRelation struct { - DollarRelation []DollarRelation `tfsdk:"dollar_relation"` -} diff --git a/internal/provider/types/dollar_relation.go b/internal/provider/types/dollar_relation.go deleted file mode 100644 index 83dd1c4..0000000 --- a/internal/provider/types/dollar_relation.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -import "github.com/hashicorp/terraform-plugin-framework/types" - -type DollarRelation struct { - Tags []types.String `tfsdk:"tags"` - EntityID types.String `tfsdk:"entity_id"` -} diff --git a/internal/provider/types/price_component_relation.go b/internal/provider/types/price_component_relation.go deleted file mode 100644 index 4289fbf..0000000 --- a/internal/provider/types/price_component_relation.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -import "github.com/hashicorp/terraform-plugin-framework/types" - -type PriceComponentRelation struct { - Tags []types.String `tfsdk:"tags"` - EntityID types.String `tfsdk:"entity_id"` -} diff --git a/internal/provider/types/price_create_price_components.go b/internal/provider/types/price_create_price_components.go deleted file mode 100644 index 8058dd8..0000000 --- a/internal/provider/types/price_create_price_components.go +++ /dev/null @@ -1,7 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -type PriceCreatePriceComponents struct { - DollarRelation []PriceComponentRelation `tfsdk:"dollar_relation"` -} diff --git a/internal/provider/types/price_tier.go b/internal/provider/types/price_tier.go deleted file mode 100644 index 56b4f50..0000000 --- a/internal/provider/types/price_tier.go +++ /dev/null @@ -1,14 +0,0 @@ -// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. - -package types - -import "github.com/hashicorp/terraform-plugin-framework/types" - -type PriceTier struct { - DisplayMode types.String `tfsdk:"display_mode"` - FlatFeeAmount types.Number `tfsdk:"flat_fee_amount"` - FlatFeeAmountDecimal types.String `tfsdk:"flat_fee_amount_decimal"` - UnitAmount types.Number `tfsdk:"unit_amount"` - UnitAmountDecimal types.String `tfsdk:"unit_amount_decimal"` - UpTo types.Number `tfsdk:"up_to"` -} diff --git a/internal/provider/utils.go b/internal/provider/utils.go index 00927b5..7884ae2 100644 --- a/internal/provider/utils.go +++ b/internal/provider/utils.go @@ -3,17 +3,25 @@ package provider import ( + "bufio" + "bytes" "context" "encoding/json" + "errors" "fmt" tfReflect "github.com/epilot-dev/terraform-provider-epilot-product/internal/provider/reflect" + "github.com/hashicorp/go-uuid" "github.com/hashicorp/terraform-plugin-framework/diag" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + "io" "net/http" "net/http/httputil" + "net/textproto" "reflect" + "strings" ) func debugResponse(response *http.Response) string { @@ -94,3 +102,180 @@ func refreshPlan(ctx context.Context, plan types.Object, target interface{}, dia SourceType: tfReflect.SourceTypePlan, }, path.Empty())...) } + +// Note: this is taken as a more minimal/specific version of https://github.com/hashicorp/terraform-plugin-sdk/blob/main/helper/logging/logging_http_transport.go +func NewLoggingHTTPTransport(t http.RoundTripper) *loggingHttpTransport { + return &loggingHttpTransport{t} +} + +const ( + FieldHttpOperationType = "tf_http_op_type" + OperationHttpRequest = "request" + OperationHttpResponse = "response" + FieldHttpRequestMethod = "tf_http_req_method" + FieldHttpRequestUri = "tf_http_req_uri" + FieldHttpRequestProtoVersion = "tf_http_req_version" + FieldHttpRequestBody = "tf_http_req_body" + FieldHttpResponseProtoVersion = "tf_http_res_version" + FieldHttpResponseStatusCode = "tf_http_res_status_code" + FieldHttpResponseStatusReason = "tf_http_res_status_reason" + FieldHttpResponseBody = "tf_http_res_body" + FieldHttpTransactionId = "tf_http_trans_id" +) + +type loggingHttpTransport struct { + transport http.RoundTripper +} + +func (t *loggingHttpTransport) RoundTrip(req *http.Request) (*http.Response, error) { + ctx := req.Context() + ctx = t.addTransactionIdField(ctx) + + // Decompose the request bytes in a message (HTTP body) and fields (HTTP headers), then log it + fields, err := decomposeRequestForLogging(req) + if err != nil { + tflog.Error(ctx, "Failed to parse request bytes for logging", []map[string]interface{}{map[string]interface{}{ + "error": err, + }}...) + } else { + tflog.Debug(ctx, "Sending HTTP Request", []map[string]interface{}{fields}...) + } + + // Invoke the wrapped RoundTrip now + res, err := t.transport.RoundTrip(req) + if err != nil { + return res, err + } + + // Decompose the response bytes in a message (HTTP body) and fields (HTTP headers), then log it + fields, err = decomposeResponseForLogging(res) + if err != nil { + tflog.Error(ctx, "Failed to parse response bytes for logging", []map[string]interface{}{map[string]interface{}{ + "error": err, + }}...) + } else { + tflog.Debug(ctx, "Received HTTP Response", []map[string]interface{}{fields}...) + } + + return res, nil +} + +func (t *loggingHttpTransport) addTransactionIdField(ctx context.Context) context.Context { + tId, err := uuid.GenerateUUID() + + if err != nil { + tId = "Unable to assign Transaction ID: " + err.Error() + } + + return tflog.SetField(ctx, FieldHttpTransactionId, tId) +} + +func decomposeRequestForLogging(req *http.Request) (map[string]interface{}, error) { + fields := make(map[string]interface{}, len(req.Header)+4) + fields[FieldHttpOperationType] = OperationHttpRequest + + fields[FieldHttpRequestMethod] = req.Method + fields[FieldHttpRequestUri] = req.URL.RequestURI() + fields[FieldHttpRequestProtoVersion] = req.Proto + + // Get the full body of the request, including headers appended by http.Transport: + // this is necessary because the http.Request at this stage doesn't contain + // all the headers that will be eventually sent. + // We rely on `httputil.DumpRequestOut` to obtain the actual bytes that will be sent out. + reqBytes, err := httputil.DumpRequestOut(req, true) + if err != nil { + return nil, err + } + + // Create a reader around the request full body + reqReader := textproto.NewReader(bufio.NewReader(bytes.NewReader(reqBytes))) + + err = fieldHeadersFromRequestReader(reqReader, fields) + if err != nil { + return nil, err + } + + // Read the rest of the body content + fields[FieldHttpRequestBody] = bodyFromRestOfRequestReader(reqReader) + return fields, nil +} + +func fieldHeadersFromRequestReader(reader *textproto.Reader, fields map[string]interface{}) error { + // Ignore the first line: it contains non-header content + // that we have already captured. + // Skipping this step, would cause the following call to `ReadMIMEHeader()` + // to fail as it cannot parse the first line. + _, err := reader.ReadLine() + if err != nil { + return err + } + + // Read the MIME-style headers + mimeHeader, err := reader.ReadMIMEHeader() + if err != nil { + return err + } + + // Set the headers as fields to log + for k, v := range mimeHeader { + if len(v) == 1 { + fields[k] = v[0] + } else { + fields[k] = v + } + } + if _, ok := fields["Authorization"]; ok { + fields["Authorization"] = "(sensitive)" + } + if _, ok := fields["x-epilot-org-id"]; ok { + fields["x-epilot-org-id"] = "(sensitive)" + } + + return nil +} + +func bodyFromRestOfRequestReader(reader *textproto.Reader) string { + var builder strings.Builder + for { + line, err := reader.ReadContinuedLine() + if errors.Is(err, io.EOF) { + break + } + builder.WriteString(line) + } + + return builder.String() +} + +func decomposeResponseForLogging(res *http.Response) (map[string]interface{}, error) { + fields := make(map[string]interface{}, len(res.Header)+4) + fields[FieldHttpOperationType] = OperationHttpResponse + + fields[FieldHttpResponseProtoVersion] = res.Proto + fields[FieldHttpResponseStatusCode] = res.StatusCode + fields[FieldHttpResponseStatusReason] = res.Status + + // Set the headers as fields to log + for k, v := range res.Header { + if len(v) == 1 { + fields[k] = v[0] + } else { + fields[k] = v + } + } + + // Read the whole response body + resBody, err := io.ReadAll(res.Body) + if err != nil { + return nil, err + } + + // Wrap the bytes from the response body, back into an io.ReadCloser, + // to respect the interface of http.Response, as expected by users of the + // http.Client + res.Body = io.NopCloser(bytes.NewBuffer(resBody)) + + fields[FieldHttpResponseBody] = string(resBody) + + return fields, nil +} diff --git a/internal/sdk/internal/utils/retries.go b/internal/sdk/internal/utils/retries.go index acdb648..53dd861 100644 --- a/internal/sdk/internal/utils/retries.go +++ b/internal/sdk/internal/utils/retries.go @@ -6,8 +6,9 @@ import ( "context" "errors" "fmt" - "github.com/cenkalti/backoff/v4" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/retry" + "math" + "math/rand" "net/http" "net/url" "strconv" @@ -15,8 +16,6 @@ import ( "time" ) -var errRequestFailed = errors.New("request failed") - // Deprecated: Use retry.BackoffStrategy instead. type BackoffStrategy = retry.BackoffStrategy @@ -28,34 +27,27 @@ type Retries struct { StatusCodes []string } -func Retry(ctx context.Context, r Retries, action func() (*http.Response, error)) (*http.Response, error) { +func Retry(ctx context.Context, r Retries, operation func() (*http.Response, error)) (*http.Response, error) { switch r.Config.Strategy { case "backoff": if r.Config.Backoff == nil { - return action() + return operation() } - config := backoff.NewExponentialBackOff() - config.InitialInterval = time.Duration(r.Config.Backoff.InitialInterval) * time.Millisecond - config.MaxInterval = time.Duration(r.Config.Backoff.MaxInterval) * time.Millisecond - config.Multiplier = r.Config.Backoff.Exponent - config.MaxElapsedTime = time.Duration(r.Config.Backoff.MaxElapsedTime) * time.Millisecond - config.Reset() - var resp *http.Response - err := backoff.Retry(func() error { + err := retryWithBackoff(ctx, r.Config.Backoff, func() error { if resp != nil { resp.Body.Close() } select { case <-ctx.Done(): - return backoff.Permanent(ctx.Err()) + return retry.Permanent(ctx.Err()) default: } - res, err := action() + res, err := operation() if err != nil { urlError := new(url.Error) if errors.As(err, &urlError) { @@ -64,7 +56,7 @@ func Retry(ctx context.Context, r Retries, action func() (*http.Response, error) } } - return backoff.Permanent(err) + return retry.Permanent(err) } resp = res if res == nil { @@ -81,7 +73,7 @@ func Retry(ctx context.Context, r Retries, action func() (*http.Response, error) s := res.StatusCode / 100 if s >= codeRange && s < codeRange+1 { - return errRequestFailed + return retry.TemporaryFromResponse("request failed", res) } } else { parsedCode, err := strconv.Atoi(code) @@ -90,7 +82,7 @@ func Retry(ctx context.Context, r Retries, action func() (*http.Response, error) } if res.StatusCode == parsedCode { - return errRequestFailed + return retry.TemporaryFromResponse("request failed", res) } } } @@ -98,13 +90,131 @@ func Retry(ctx context.Context, r Retries, action func() (*http.Response, error) resp = res return nil - }, config) - if err != nil && !errors.Is(err, errRequestFailed) { + }) + + var tempErr *retry.TemporaryError + if err != nil && !errors.As(err, &tempErr) { return nil, err } return resp, nil default: - return action() + return operation() + } +} + +func retryWithBackoff(ctx context.Context, s *retry.BackoffStrategy, operation func() error) error { + var ( + err error + next time.Duration + attempt int + start = time.Now() + maxElapsedTime = time.Duration(s.MaxElapsedTime) * time.Millisecond + ) + + timer := &defaultTimer{} + defer func() { + timer.Stop() + }() + + for { + err = operation() + if err == nil { + return nil + } + + var permanent *retry.PermanentError + if errors.As(err, &permanent) { + return permanent.Unwrap() + } + + if time.Since(start) >= maxElapsedTime { + return err + } + + var temporary *retry.TemporaryError + if errors.As(err, &temporary) { + next = temporary.RetryAfter() + } + + if next <= 0 { + next = nextInterval(s, attempt) + } + + timer.Start(next) + + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C(): + } + + attempt += 1 } } + +type Timer interface { + Start(duration time.Duration) + Stop() + C() <-chan time.Time +} + +// defaultTimer implements Timer interface using time.Timer +type defaultTimer struct { + timer *time.Timer +} + +// C returns the timers channel which receives the current time when the timer fires. +func (t *defaultTimer) C() <-chan time.Time { + return t.timer.C +} + +// Start starts the timer to fire after the given duration +func (t *defaultTimer) Start(duration time.Duration) { + if t.timer == nil { + t.timer = time.NewTimer(duration) + return + } + + if !t.timer.Stop() { + select { + case <-t.timer.C: + default: + } + } + + t.timer.Reset(duration) +} + +// Stop is called when the timer is not used anymore and resources may be freed. +func (t *defaultTimer) Stop() { + if t.timer != nil { + t.timer.Stop() + } +} + +func nextInterval(s *retry.BackoffStrategy, attempt int) time.Duration { + initialInterval := float64(time.Duration(s.InitialInterval) * time.Millisecond) + maxInterval := float64(time.Duration(s.MaxInterval) * time.Millisecond) + exponent := s.Exponent + jitterFactor := float64(0.25) + + interval := initialInterval * math.Pow(float64(attempt+1), exponent) + + jitter := rand.Float64() * jitterFactor * interval + if rand.Float64() < 0.5 { + jitter = -1 * jitter + } + + interval = interval + jitter + + if interval <= 0 { + interval = initialInterval + } + + if interval > maxInterval { + interval = maxInterval + } + + return time.Duration(interval) +} diff --git a/internal/sdk/price.go b/internal/sdk/price.go index 4aa0565..b468165 100644 --- a/internal/sdk/price.go +++ b/internal/sdk/price.go @@ -6,13 +6,11 @@ import ( "bytes" "context" "fmt" - "github.com/cenkalti/backoff/v4" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/internal/hooks" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/internal/utils" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/errors" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/operations" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/shared" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/retry" "net/http" "net/url" ) @@ -40,7 +38,6 @@ func (s *Price) CreatePrice(ctx context.Context, request shared.PriceCreate, opt o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -84,94 +81,32 @@ func (s *Price) CreatePrice(ctx context.Context, request shared.PriceCreate, opt return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -269,7 +204,6 @@ func (s *Price) DeletePrice(ctx context.Context, request operations.DeletePriceR o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -307,95 +241,33 @@ func (s *Price) DeletePrice(ctx context.Context, request operations.DeletePriceR return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + } else if _httpRes != nil { + httpRes = _httpRes } } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) if err != nil { return nil, err } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } } res := &operations.DeletePriceResponse{ @@ -492,7 +364,6 @@ func (s *Price) GetPrice(ctx context.Context, request operations.GetPriceRequest o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -534,94 +405,32 @@ func (s *Price) GetPrice(ctx context.Context, request operations.GetPriceRequest return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -719,7 +528,6 @@ func (s *Price) PatchPrice(ctx context.Context, request operations.PatchPriceReq o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -763,94 +571,32 @@ func (s *Price) PatchPrice(ctx context.Context, request operations.PatchPriceReq return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -948,7 +694,6 @@ func (s *Price) UpdatePrice(ctx context.Context, request operations.UpdatePriceR o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -992,94 +737,32 @@ func (s *Price) UpdatePrice(ctx context.Context, request operations.UpdatePriceR return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } diff --git a/internal/sdk/product.go b/internal/sdk/product.go index c69149b..58fa9b3 100644 --- a/internal/sdk/product.go +++ b/internal/sdk/product.go @@ -6,13 +6,11 @@ import ( "bytes" "context" "fmt" - "github.com/cenkalti/backoff/v4" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/internal/hooks" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/internal/utils" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/errors" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/operations" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/shared" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/retry" "net/http" "net/url" ) @@ -40,7 +38,6 @@ func (s *Product) CreateProduct(ctx context.Context, request shared.ProductCreat o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -84,94 +81,32 @@ func (s *Product) CreateProduct(ctx context.Context, request shared.ProductCreat return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -269,7 +204,6 @@ func (s *Product) DeleteProduct(ctx context.Context, request operations.DeletePr o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -307,95 +241,33 @@ func (s *Product) DeleteProduct(ctx context.Context, request operations.DeletePr return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + } else if _httpRes != nil { + httpRes = _httpRes } } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) if err != nil { return nil, err } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } } res := &operations.DeleteProductResponse{ @@ -492,7 +364,6 @@ func (s *Product) GetProduct(ctx context.Context, request operations.GetProductR o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -534,94 +405,32 @@ func (s *Product) GetProduct(ctx context.Context, request operations.GetProductR return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -719,7 +528,6 @@ func (s *Product) PatchProduct(ctx context.Context, request operations.PatchProd o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -763,94 +571,32 @@ func (s *Product) PatchProduct(ctx context.Context, request operations.PatchProd return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -948,7 +694,6 @@ func (s *Product) UpdateProduct(ctx context.Context, request operations.UpdatePr o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -992,94 +737,32 @@ func (s *Product) UpdateProduct(ctx context.Context, request operations.UpdatePr return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } diff --git a/internal/sdk/retry/config.go b/internal/sdk/retry/config.go index c051b0a..aa4b334 100644 --- a/internal/sdk/retry/config.go +++ b/internal/sdk/retry/config.go @@ -2,6 +2,15 @@ package retry +import ( + "errors" + "net/http" + "strconv" + "time" +) + +// BackoffStrategy defines the parameters for exponential backoff. This can be +// used to drive a retry loop for example. type BackoffStrategy struct { InitialInterval int MaxInterval int @@ -9,8 +18,128 @@ type BackoffStrategy struct { MaxElapsedTime int } +// Config configures a retry policy. type Config struct { Strategy string Backoff *BackoffStrategy RetryConnectionErrors bool } + +// PermanentError is an error that signals that some operation has terminally +// failed and should not be retried. +type PermanentError struct { + cause error +} + +// Permanent creates a PermanentError that signals to a retry loop that it +// should stop retrying an operation and return the underlying error. +func Permanent(cause error) error { + if IsPermanentError(cause) { + return cause + } + + return &PermanentError{ + cause: cause, + } +} + +func (e *PermanentError) Error() string { + return e.cause.Error() +} + +func (e *PermanentError) Unwrap() error { + return e.cause +} + +// TemporaryError represents a retryable error and signals to a retry loop that +// an operation may be retried with an optional wait interval. +type TemporaryError struct { + wait time.Duration + message string +} + +// Temporary creates a TemporaryError that signals to a retry loop that an +// operation can be retried. The error may also carry details about how long to +// wait before retrying. This wait interval may be used to override the retry +// policy in use. +func Temporary(message string) error { + return &TemporaryError{ + message: message, + } +} + +// TemporaryFromResponse creates a TemporaryError similar to Temporary but +// additionally parses the Retry-After header from a response to determine the +// wait interval before the next retry attempt. +func TemporaryFromResponse(message string, res *http.Response) error { + return &TemporaryError{ + wait: retryIntervalFromResponse(res), + message: message, + } +} + +func (e *TemporaryError) Error() string { + return e.message +} + +// RetryAfter returns the time to wait before retrying the request. The zero +// value should be interpreted by retry loops to mean they should fallback on +// their default policy whether expenonential, constant backoff or something +// else. It does not mean that an operation should be retried immediately. +func (e *TemporaryError) RetryAfter() time.Duration { + return e.wait +} + +func retryIntervalFromResponse(res *http.Response) time.Duration { + if res == nil { + return 0 + } + + retryVal := res.Header.Get("retry-after") + if retryVal == "" { + return 0 + } + + parsedNumber, err := strconv.ParseInt(retryVal, 10, 64) + if err == nil { + if parsedNumber < 0 { + return 0 + } else { + return time.Duration(parsedNumber) * time.Second + } + } + + parsedDate, err := time.Parse(time.RFC1123, retryVal) + if err == nil { + delta := parsedDate.Sub(time.Now()) + if delta < 0 { + return 0 + } else { + return delta + } + } + + return 0 +} + +// IsPermanentError returns true if an error value is or contains a +// PermanentError in its chain of errors. +func IsPermanentError(err error) bool { + if err == nil { + return false + } + + var pe *PermanentError + return errors.As(err, &pe) +} + +// IsTemporaryError returns true if an error value is or contains a +// TemporaryError in its chain of errors. +func IsTemporaryError(err error) bool { + if err == nil { + return false + } + + var pe *TemporaryError + return errors.As(err, &pe) +} diff --git a/internal/sdk/sdk.go b/internal/sdk/sdk.go index a6287cf..f1d80b9 100644 --- a/internal/sdk/sdk.go +++ b/internal/sdk/sdk.go @@ -15,6 +15,7 @@ import ( // ServerList contains the list of servers available to the SDK var ServerList = []string{ + "https://product.sls.epilot.io", // Production server "https://product.sls.epilot.io", } @@ -153,8 +154,8 @@ func New(opts ...SDKOption) *SDK { Language: "go", OpenAPIDocVersion: "1.0.0", SDKVersion: "0.0.1", - GenVersion: "2.438.15", - UserAgent: "speakeasy-sdk/go 0.0.1 2.438.15 1.0.0 github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk", + GenVersion: "2.461.4", + UserAgent: "speakeasy-sdk/go 0.0.1 2.461.4 1.0.0 github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk", Hooks: hooks.New(), }, } diff --git a/internal/sdk/tax.go b/internal/sdk/tax.go index 1883053..6eb4c3d 100644 --- a/internal/sdk/tax.go +++ b/internal/sdk/tax.go @@ -6,13 +6,11 @@ import ( "bytes" "context" "fmt" - "github.com/cenkalti/backoff/v4" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/internal/hooks" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/internal/utils" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/errors" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/operations" "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/models/shared" - "github.com/epilot-dev/terraform-provider-epilot-product/internal/sdk/retry" "net/http" "net/url" ) @@ -40,7 +38,6 @@ func (s *Tax) CreateTax(ctx context.Context, request shared.TaxCreate, opts ...o o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -84,94 +81,32 @@ func (s *Tax) CreateTax(ctx context.Context, request shared.TaxCreate, opts ...o return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -269,7 +204,6 @@ func (s *Tax) DeleteTax(ctx context.Context, request operations.DeleteTaxRequest o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -307,95 +241,33 @@ func (s *Tax) DeleteTax(ctx context.Context, request operations.DeleteTaxRequest return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + } else if _httpRes != nil { + httpRes = _httpRes } } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) if err != nil { return nil, err } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } - } } res := &operations.DeleteTaxResponse{ @@ -492,7 +364,6 @@ func (s *Tax) GetTax(ctx context.Context, request operations.GetTaxRequest, opts o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -534,94 +405,32 @@ func (s *Tax) GetTax(ctx context.Context, request operations.GetTaxRequest, opts return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -719,7 +528,6 @@ func (s *Tax) PatchTax(ctx context.Context, request operations.PatchTaxRequest, o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -763,94 +571,32 @@ func (s *Tax) PatchTax(ctx context.Context, request operations.PatchTaxRequest, return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } } @@ -948,7 +694,6 @@ func (s *Tax) UpdateTax(ctx context.Context, request operations.UpdateTaxRequest o := operations.Options{} supportedOptions := []string{ - operations.SupportedOptionRetries, operations.SupportedOptionTimeout, } @@ -992,94 +737,32 @@ func (s *Tax) UpdateTax(ctx context.Context, request operations.UpdateTaxRequest return nil, err } - globalRetryConfig := s.sdkConfiguration.RetryConfig - retryConfig := o.Retries - if retryConfig == nil { - if globalRetryConfig != nil { - retryConfig = globalRetryConfig - } else { - retryConfig = &retry.Config{ - Strategy: "backoff", Backoff: &retry.BackoffStrategy{ - InitialInterval: 5000, - MaxInterval: 60000, - Exponent: 1.5, - MaxElapsedTime: 3600000, - }, - RetryConnectionErrors: true, - } - } + req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err } - var httpRes *http.Response - if retryConfig != nil { - httpRes, err = utils.Retry(ctx, utils.Retries{ - Config: retryConfig, - StatusCodes: []string{ - "5XX", - }, - }, func() (*http.Response, error) { - if req.Body != nil { - copyBody, err := req.GetBody() - if err != nil { - return nil, err - } - req.Body = copyBody - } - - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) - if err != nil { - return nil, backoff.Permanent(err) - } - - httpRes, err := s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) - } - return httpRes, err - }) - + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { if err != nil { - return nil, err + err = fmt.Errorf("error sending request: %w", err) } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } + err = fmt.Errorf("error sending request: no response") } - } else { - req, err = s.sdkConfiguration.Hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + + _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) if err != nil { return nil, err + } else if _httpRes != nil { + httpRes = _httpRes } - - httpRes, err = s.sdkConfiguration.Client.Do(req) - if err != nil || httpRes == nil { - if err != nil { - err = fmt.Errorf("error sending request: %w", err) - } else { - err = fmt.Errorf("error sending request: no response") - } - - _, err = s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + } else { + httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { return nil, err - } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { - _httpRes, err := s.sdkConfiguration.Hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) - if err != nil { - return nil, err - } else if _httpRes != nil { - httpRes = _httpRes - } - } else { - httpRes, err = s.sdkConfiguration.Hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) - if err != nil { - return nil, err - } } }