diff --git a/template_variables/.gitattributes b/template_variables/.gitattributes new file mode 100644 index 000000000..4d75d5900 --- /dev/null +++ b/template_variables/.gitattributes @@ -0,0 +1,2 @@ +# This allows generated code to be indexed correctly +*.py linguist-generated=false \ No newline at end of file diff --git a/template_variables/.gitignore b/template_variables/.gitignore new file mode 100644 index 000000000..3cdf33802 --- /dev/null +++ b/template_variables/.gitignore @@ -0,0 +1,6 @@ +venv/ +src/*.egg-info/ +__pycache__/ +.pytest_cache/ +.python-version +.DS_Store diff --git a/template_variables/.speakeasy/gen.lock b/template_variables/.speakeasy/gen.lock new file mode 100755 index 000000000..6a0fed22a --- /dev/null +++ b/template_variables/.speakeasy/gen.lock @@ -0,0 +1,96 @@ +lockVersion: 2.0.0 +id: 9306259b-9cd1-49a4-8473-692a5bc5b2af +management: + docChecksum: 9efe370082758b9cf2fd0a2bcf412e38 + docVersion: 1.0.0 + speakeasyVersion: 1.252.0 + generationVersion: 2.306.0 + releaseVersion: 1.3.0 + configChecksum: 9f1ab4d8be504a3cb037f30c21dcf4e7 + repoURL: https://github.com/epilot-dev/sdk-python.git + repoSubDirectory: template_variables + installationURL: https://github.com/epilot-dev/sdk-python.git#subdirectory=template_variables +features: + python: + constsAndDefaults: 0.1.3 + core: 4.6.4 + flattening: 2.81.1 + globalSecurity: 2.83.5 + globalServerURLs: 2.82.2 + responseFormat: 0.1.0 +generatedFiles: + - src/epilot/sdkconfiguration.py + - src/epilot/custom_variables.py + - src/epilot/variables.py + - src/epilot/sdk.py + - py.typed + - pylintrc + - setup.py + - src/epilot/__init__.py + - src/epilot/utils/__init__.py + - src/epilot/utils/retries.py + - src/epilot/utils/utils.py + - src/epilot/models/errors/sdkerror.py + - tests/helpers.py + - src/epilot/models/operations/createcustomvariable.py + - src/epilot/models/operations/deletecustomvariable.py + - src/epilot/models/operations/getblueprinttableconfig.py + - src/epilot/models/operations/getcustomvariable.py + - src/epilot/models/operations/getcustomvariables.py + - src/epilot/models/operations/updatecustomvariable.py + - src/epilot/models/operations/getcategories.py + - src/epilot/models/operations/getvariablecontext.py + - src/epilot/models/operations/replacetemplates.py + - src/epilot/models/operations/searchvariables.py + - src/epilot/models/components/httpmetadata.py + - src/epilot/models/components/customvariable.py + - src/epilot/models/components/categoryresult.py + - src/epilot/models/components/variablecontext.py + - src/epilot/models/components/variableparameters.py + - src/epilot/models/components/templatetype.py + - src/epilot/models/components/externalcustomvariable.py + - src/epilot/models/components/variableresult.py + - src/epilot/models/components/security.py + - src/epilot/models/__init__.py + - src/epilot/models/errors/__init__.py + - src/epilot/models/operations/__init__.py + - src/epilot/models/components/__init__.py + - docs/models/operations/createcustomvariableresponse.md + - docs/models/operations/deletecustomvariablerequest.md + - docs/models/operations/deletecustomvariableresponse.md + - docs/models/operations/getblueprinttableconfigresponse.md + - docs/models/operations/getcustomvariablerequest.md + - docs/models/operations/getcustomvariableresponse.md + - docs/models/operations/getcustomvariablesresponse.md + - docs/models/operations/updatecustomvariablerequest.md + - docs/models/operations/updatecustomvariableresponse.md + - docs/models/operations/getcategoriesrequest.md + - docs/models/operations/getcategoriesresponse.md + - docs/models/operations/getvariablecontextrequestbody.md + - docs/models/operations/getvariablecontextresponse.md + - docs/models/operations/replacetemplatesrequestbody.md + - docs/models/operations/replacetemplatesresponsebody.md + - docs/models/operations/replacetemplatesresponse.md + - docs/models/operations/searchvariablesrequestbody.md + - docs/models/operations/searchvariablesresponse.md + - docs/models/components/httpmetadata.md + - docs/models/components/config.md + - docs/models/components/type.md + - docs/models/components/customvariable.md + - docs/models/components/categoryresult.md + - docs/models/components/variablecontext.md + - docs/models/components/contextdata.md + - docs/models/components/variableparameters.md + - docs/models/components/templatetype.md + - docs/models/components/externalcustomvariable.md + - docs/models/components/variableresulttype.md + - docs/models/components/variableresult.md + - docs/models/components/security.md + - docs/sdks/epilot/README.md + - docs/sdks/customvariables/README.md + - docs/sdks/variables/README.md + - USAGE.md + - .gitattributes + - src/epilot/_hooks/sdkhooks.py + - src/epilot/_hooks/types.py + - src/epilot/_hooks/__init__.py diff --git a/template_variables/README.md b/template_variables/README.md index 39dbd896e..de024356a 100755 --- a/template_variables/README.md +++ b/template_variables/README.md @@ -1,45 +1,524 @@ # epilot-template-variables - + ## SDK Installation ```bash pip install git+https://github.com/epilot-dev/sdk-python.git#subdirectory=template_variables ``` - + + ## SDK Example Usage - + +### Example + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + +req = components.CustomVariable( + config=components.Config(), + created_at='2022-04-19T12:41:43.662Z', + created_by='100042', + helper_logic='return param1 * param2;', + helper_params=[ + 'param1', + 'param2', + ], + id='rbse777b-3cf8-4bff-bb0c-253fd1123250', + key='my_custom_table', + name='My Custom table', + template=' + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id \'item\')}} + + + {{/if}} + {{#if (eq column.id \'quantity\')}} + + + {{/if}} + {{#if (eq column.id \'tax\')}} + + + {{/if}} + {{#if (eq column.id \'unit_amount\')}} + + + {{/if}} + {{#if (eq column.id \'net_total\')}} + + + {{/if}} + {{#if (eq column.id \'amount_tax\')}} + + + {{/if}} + {{#if (eq column.id \'gross_total\')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config \'net_total\')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type \'recurring\')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+', + type=components.Type.CUSTOM, + updated_at='2022-04-20T12:41:43.662Z', + updated_by='100042', +) + +res = s.custom_variables.create_custom_variable(req) + +if res is not None: + # handle response + pass + +``` + + + +## Available Resources and Operations + +### [custom_variables](docs/sdks/customvariables/README.md) + +* [create_custom_variable](docs/sdks/customvariables/README.md#create_custom_variable) - Create custom variable +* [delete_custom_variable](docs/sdks/customvariables/README.md#delete_custom_variable) - Delete custom variable +* [get_blue_print_table_config](docs/sdks/customvariables/README.md#get_blue_print_table_config) - Get default table config +* [get_custom_variable](docs/sdks/customvariables/README.md#get_custom_variable) - Get custom variable +* [get_custom_variables](docs/sdks/customvariables/README.md#get_custom_variables) - Get custom variables +* [update_custom_variable](docs/sdks/customvariables/README.md#update_custom_variable) - Update custom variable + +### [variables](docs/sdks/variables/README.md) + +* [get_categories](docs/sdks/variables/README.md#get_categories) - getCategories +* [get_variable_context](docs/sdks/variables/README.md#get_variable_context) - getVariableContext +* [replace_templates](docs/sdks/variables/README.md#replace_templates) - replaceTemplates +* [search_variables](docs/sdks/variables/README.md#search_variables) - searchVariables + + + +## Error Handling + +Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an error. If Error objects are specified in your OpenAPI Spec, the SDK will raise the appropriate Error type. + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +### Example + +```python +import epilot +from epilot.models import components, errors + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + +req = components.CustomVariable( + config=components.Config(), + created_at='2022-04-19T12:41:43.662Z', + created_by='100042', + helper_logic='return param1 * param2;', + helper_params=[ + 'param1', + 'param2', + ], + id='rbse777b-3cf8-4bff-bb0c-253fd1123250', + key='my_custom_table', + name='My Custom table', + template=' + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id \'item\')}} + + + {{/if}} + {{#if (eq column.id \'quantity\')}} + + + {{/if}} + {{#if (eq column.id \'tax\')}} + + + {{/if}} + {{#if (eq column.id \'unit_amount\')}} + + + {{/if}} + {{#if (eq column.id \'net_total\')}} + + + {{/if}} + {{#if (eq column.id \'amount_tax\')}} + + + {{/if}} + {{#if (eq column.id \'gross_total\')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config \'net_total\')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type \'recurring\')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+', + type=components.Type.CUSTOM, + updated_at='2022-04-20T12:41:43.662Z', + updated_by='100042', +) + +res = None +try: + res = s.custom_variables.create_custom_variable(req) +except errors.SDKError as e: + # handle exception + raise(e) + +if res is not None: + # handle response + pass + +``` + + + +## Server Selection + +### Select Server by Index + +You can override the default server globally by passing a server index to the `server_idx: int` optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers: + +| # | Server | Variables | +| - | ------ | --------- | +| 0 | `https://template-variables-api.sls.epilot.io` | None | + +#### Example + ```python import epilot -from epilot.models import operations, shared +from epilot.models import components s = epilot.Epilot( - security=shared.Security( - epilot_auth="Bearer YOUR_BEARER_TOKEN_HERE", + server_idx=0, + security=components.Security( + epilot_auth="", ), ) +req = components.CustomVariable( + config=components.Config(), + created_at='2022-04-19T12:41:43.662Z', + created_by='100042', + helper_logic='return param1 * param2;', + helper_params=[ + 'param1', + 'param2', + ], + id='rbse777b-3cf8-4bff-bb0c-253fd1123250', + key='my_custom_table', + name='My Custom table', + template=' + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id \'item\')}} + + + {{/if}} + {{#if (eq column.id \'quantity\')}} + + + {{/if}} + {{#if (eq column.id \'tax\')}} + + + {{/if}} + {{#if (eq column.id \'unit_amount\')}} + + + {{/if}} + {{#if (eq column.id \'net_total\')}} + + + {{/if}} + {{#if (eq column.id \'amount_tax\')}} + + + {{/if}} + {{#if (eq column.id \'gross_total\')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config \'net_total\')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type \'recurring\')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+', + type=components.Type.CUSTOM, + updated_at='2022-04-20T12:41:43.662Z', + updated_by='100042', +) + +res = s.custom_variables.create_custom_variable(req) + +if res is not None: + # handle response + pass + +``` + + +### Override Server URL Per-Client -req = shared.CustomVariable( - config={ - "deserunt": "porro", - "nulla": "id", - "vero": "perspiciatis", - }, - created_at="2022-04-19T12:41:43.662Z", - created_by="100042", - helper_logic="return param1 * param2;", +The default server can also be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example: +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + server_url="https://template-variables-api.sls.epilot.io", + security=components.Security( + epilot_auth="", + ), +) + +req = components.CustomVariable( + config=components.Config(), + created_at='2022-04-19T12:41:43.662Z', + created_by='100042', + helper_logic='return param1 * param2;', helper_params=[ - "nihil", - "fuga", - "facilis", - "eum", + 'param1', + 'param2', ], - id="rbse777b-3cf8-4bff-bb0c-253fd1123250", - key="my_custom_table", - name="My Custom table", - template=" + id='rbse777b-3cf8-4bff-bb0c-253fd1123250', + key='my_custom_table', + name='My Custom table', + template='
{{#each table_config.header.columns as |column|}} @@ -59,7 +538,7 @@ req = shared.CustomVariable( {{/if}} {{#each @root.table_config.header.columns as |column|}} {{#if column.enable}} - {{#if (eq column.id 'item')}} + {{#if (eq column.id \'item\')}} {{/if}} - {{#if (eq column.id 'quantity')}} + {{#if (eq column.id \'quantity\')}} {{/if}} - {{#if (eq column.id 'tax')}} + {{#if (eq column.id \'tax\')}} {{/if}} - {{#if (eq column.id 'unit_amount')}} + {{#if (eq column.id \'unit_amount\')}} {{/if}} - {{#if (eq column.id 'net_total')}} + {{#if (eq column.id \'net_total\')}} {{/if}} - {{#if (eq column.id 'amount_tax')}} + {{#if (eq column.id \'amount_tax\')}} {{/if}} - {{#if (eq column.id 'gross_total')}} + {{#if (eq column.id \'gross_total\')}} {{/if}} - {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if (isColumnEnabled @root.table_config \'net_total\')}} {{#if @root.table_config.footer.net_total.enable}} {{/if}} @@ -145,39 +624,195 @@ req = shared.CustomVariable(
{{#if @root.table_config.body.product_name.enable}} @@ -75,41 +554,41 @@ req = shared.CustomVariable( {{/if}} {{product.price.quantity}} {{product.price.tax_rate}} {{product.price.unit_amount_net}} {{product.price.amount_subtotal}} {{product.price.amount_tax}} {{product.price.amount_total}} {{#if @root.table_config.body.payment_type.enable}} - {{#if (eq product.price.type 'recurring')}} + {{#if (eq product.price.type \'recurring\')}}
{{product.price.billing_period}} {{/if}} @@ -128,7 +607,7 @@ req = shared.CustomVariable( {{#if @root.table_config.footer.payment_type.enable}}
{{item.billing_period}}{{item.amount_subtotal}}
-", - type="order_table", - updated_at="2022-04-20T12:41:43.662Z", - updated_by="100042", +', + type=components.Type.CUSTOM, + updated_at='2022-04-20T12:41:43.662Z', + updated_by='100042', ) - + res = s.custom_variables.create_custom_variable(req) -if res.status_code == 200: +if res is not None: # handle response + pass + ``` - + - -## SDK Available Operations + +## Custom HTTP Client +The Python SDK makes API calls using the [requests](https://pypi.org/project/requests/) HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with a custom `requests.Session` object. -### custom_variables +For example, you could specify a header for every request that this sdk makes as follows: +```python +import epilot +import requests + +http_client = requests.Session() +http_client.headers.update({'x-custom-header': 'someValue'}) +s = epilot.Epilot(client=http_client) +``` + + + +## Authentication + +### Per-Client Security Schemes + +This SDK supports the following security schemes globally: + +| Name | Type | Scheme | +| ------------- | ------------- | ------------- | +| `epilot_auth` | http | HTTP Bearer | +| `epilot_org` | apiKey | API key | + +You can set the security parameters through the `security` optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example: +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + +req = components.CustomVariable( + config=components.Config(), + created_at='2022-04-19T12:41:43.662Z', + created_by='100042', + helper_logic='return param1 * param2;', + helper_params=[ + 'param1', + 'param2', + ], + id='rbse777b-3cf8-4bff-bb0c-253fd1123250', + key='my_custom_table', + name='My Custom table', + template=' + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id \'item\')}} + + + {{/if}} + {{#if (eq column.id \'quantity\')}} + + + {{/if}} + {{#if (eq column.id \'tax\')}} + + + {{/if}} + {{#if (eq column.id \'unit_amount\')}} + + + {{/if}} + {{#if (eq column.id \'net_total\')}} + + + {{/if}} + {{#if (eq column.id \'amount_tax\')}} + + + {{/if}} + {{#if (eq column.id \'gross_total\')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config \'net_total\')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type \'recurring\')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+', + type=components.Type.CUSTOM, + updated_at='2022-04-20T12:41:43.662Z', + updated_by='100042', +) + +res = s.custom_variables.create_custom_variable(req) + +if res is not None: + # handle response + pass + +``` + -* `create_custom_variable` - Create custom variable -* `delete_custom_variable` - Delete custom variable -* `get_blue_print_table_config` - Get default table config -* `get_custom_variable` - Get custom variable -* `get_custom_variables` - Get custom variables -* `update_custom_variable` - Update custom variable + -### variables -* `generate_q_rcode` - generateQRcode -* `get_categories` - getCategories -* `get_variable_context` - getVariableContext -* `replace_templates` - replaceTemplates -* `search_variables` - searchVariables - ### SDK Generated by [Speakeasy](https://docs.speakeasyapi.dev/docs/using-speakeasy/client-sdks) diff --git a/template_variables/RELEASES.md b/template_variables/RELEASES.md index 6b443894d..457213ff9 100644 --- a/template_variables/RELEASES.md +++ b/template_variables/RELEASES.md @@ -34,4 +34,12 @@ Based on: ### Changes Based on: - OpenAPI Doc 1.0.0 https://docs.api.epilot.io/template-variables.yaml -- Speakeasy CLI 1.19.2 (2.16.5) https://github.com/speakeasy-api/speakeasy \ No newline at end of file +- Speakeasy CLI 1.19.2 (2.16.5) https://github.com/speakeasy-api/speakeasy + +## 2024-04-15 02:39:06 +### Changes +Based on: +- OpenAPI Doc 1.0.0 https://docs.api.epilot.io/template-variables.yaml +- Speakeasy CLI 1.252.0 (2.306.0) https://github.com/speakeasy-api/speakeasy +### Generated +- [python v1.3.0] template_variables \ No newline at end of file diff --git a/template_variables/USAGE.md b/template_variables/USAGE.md old mode 100755 new mode 100644 index abcb76fe3..f886b53ea --- a/template_variables/USAGE.md +++ b/template_variables/USAGE.md @@ -1,34 +1,27 @@ - + ```python import epilot -from epilot.models import operations, shared +from epilot.models import components s = epilot.Epilot( - security=shared.Security( - epilot_auth="Bearer YOUR_BEARER_TOKEN_HERE", + security=components.Security( + epilot_auth="", ), ) - -req = shared.CustomVariable( - config={ - "deserunt": "porro", - "nulla": "id", - "vero": "perspiciatis", - }, - created_at="2022-04-19T12:41:43.662Z", - created_by="100042", - helper_logic="return param1 * param2;", +req = components.CustomVariable( + config=components.Config(), + created_at='2022-04-19T12:41:43.662Z', + created_by='100042', + helper_logic='return param1 * param2;', helper_params=[ - "nihil", - "fuga", - "facilis", - "eum", + 'param1', + 'param2', ], - id="rbse777b-3cf8-4bff-bb0c-253fd1123250", - key="my_custom_table", - name="My Custom table", - template=" + id='rbse777b-3cf8-4bff-bb0c-253fd1123250', + key='my_custom_table', + name='My Custom table', + template='
{{#each table_config.header.columns as |column|}} @@ -48,7 +41,7 @@ req = shared.CustomVariable( {{/if}} {{#each @root.table_config.header.columns as |column|}} {{#if column.enable}} - {{#if (eq column.id 'item')}} + {{#if (eq column.id \'item\')}} {{/if}} - {{#if (eq column.id 'quantity')}} + {{#if (eq column.id \'quantity\')}} {{/if}} - {{#if (eq column.id 'tax')}} + {{#if (eq column.id \'tax\')}} {{/if}} - {{#if (eq column.id 'unit_amount')}} + {{#if (eq column.id \'unit_amount\')}} {{/if}} - {{#if (eq column.id 'net_total')}} + {{#if (eq column.id \'net_total\')}} {{/if}} - {{#if (eq column.id 'amount_tax')}} + {{#if (eq column.id \'amount_tax\')}} {{/if}} - {{#if (eq column.id 'gross_total')}} + {{#if (eq column.id \'gross_total\')}} {{/if}} - {{#if (isColumnEnabled @root.table_config 'net_total')}} + {{#if (isColumnEnabled @root.table_config \'net_total\')}} {{#if @root.table_config.footer.net_total.enable}} {{/if}} @@ -134,15 +127,17 @@ req = shared.CustomVariable(
{{#if @root.table_config.body.product_name.enable}} @@ -64,41 +57,41 @@ req = shared.CustomVariable( {{/if}} {{product.price.quantity}} {{product.price.tax_rate}} {{product.price.unit_amount_net}} {{product.price.amount_subtotal}} {{product.price.amount_tax}} {{product.price.amount_total}} {{#if @root.table_config.body.payment_type.enable}} - {{#if (eq product.price.type 'recurring')}} + {{#if (eq product.price.type \'recurring\')}}
{{product.price.billing_period}} {{/if}} @@ -117,7 +110,7 @@ req = shared.CustomVariable( {{#if @root.table_config.footer.payment_type.enable}}
{{item.billing_period}}{{item.amount_subtotal}}
-", - type="order_table", - updated_at="2022-04-20T12:41:43.662Z", - updated_by="100042", +', + type=components.Type.CUSTOM, + updated_at='2022-04-20T12:41:43.662Z', + updated_by='100042', ) - + res = s.custom_variables.create_custom_variable(req) -if res.status_code == 200: +if res is not None: # handle response + pass + ``` - \ No newline at end of file + \ No newline at end of file diff --git a/template_variables/docs/models/components/categoryresult.md b/template_variables/docs/models/components/categoryresult.md new file mode 100644 index 000000000..043c42d1c --- /dev/null +++ b/template_variables/docs/models/components/categoryresult.md @@ -0,0 +1,9 @@ +# CategoryResult + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | +| `category` | *Optional[str]* | :heavy_minus_sign: | N/A | contact | +| `description` | *Optional[str]* | :heavy_minus_sign: | N/A | Contact | \ No newline at end of file diff --git a/template_variables/docs/models/components/config.md b/template_variables/docs/models/components/config.md new file mode 100644 index 000000000..4e902045d --- /dev/null +++ b/template_variables/docs/models/components/config.md @@ -0,0 +1,9 @@ +# Config + +Variable configuration + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/template_variables/docs/models/components/contextdata.md b/template_variables/docs/models/components/contextdata.md new file mode 100644 index 000000000..9e90c08fc --- /dev/null +++ b/template_variables/docs/models/components/contextdata.md @@ -0,0 +1,9 @@ +# ContextData + +If context data is avaialble, this data will be used for variable replace. + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/template_variables/docs/models/components/customvariable.md b/template_variables/docs/models/components/customvariable.md new file mode 100644 index 000000000..54c6e81a9 --- /dev/null +++ b/template_variables/docs/models/components/customvariable.md @@ -0,0 +1,19 @@ +# CustomVariable + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `config` | [Optional[components.Config]](../../models/components/config.md) | :heavy_minus_sign: | Variable configuration | {
"$ref": "#/components/examples/TableConfig/value"
} | +| `created_at` | *Optional[str]* | :heavy_minus_sign: | Creation time | 2022-04-19 12:41:43.662 +0000 UTC | +| `created_by` | *Optional[str]* | :heavy_minus_sign: | Created by | 100042 | +| `helper_logic` | *Optional[str]* | :heavy_minus_sign: | The helper function logic | return param1 * param2; | +| `helper_params` | List[*str*] | :heavy_minus_sign: | The helper function parameter's names | [
"param1",
"param2"
] | +| `id` | *Optional[str]* | :heavy_minus_sign: | ID | rbse777b-3cf8-4bff-bb0c-253fd1123250 | +| `key` | *Optional[str]* | :heavy_minus_sign: | The key which is used for Handlebar variable syntax {{key}} | my_custom_table | +| `name` | *Optional[str]* | :heavy_minus_sign: | Custom variable name | My Custom table | +| `template` | *Optional[str]* | :heavy_minus_sign: | Handlebar template that used to generate the variable content |


{{#each table_config.header.columns as \|column\|}}
{{#if column.enable}}

{{/if}}
{{/each}}




{{#each order.products as \|product\|}}
{{#if @last}}

{{else}}

{{/if}}
{{#each @root.table_config.header.columns as \|column\|}}
{{#if column.enable}}
{{#if (eq column.id 'item')}}


{{/if}}
{{#if (eq column.id 'quantity')}}


{{/if}}
{{#if (eq column.id 'tax')}}


{{/if}}
{{#if (eq column.id 'unit_amount')}}


{{/if}}
{{#if (eq column.id 'net_total')}}


{{/if}}
{{#if (eq column.id 'amount_tax')}}


{{/if}}
{{#if (eq column.id 'gross_total')}}


{{/if}}
{{/if}}
{{/each}}

{{/each}}

{{#if table_config.footer.gross_total.enable}}
{{#each order.total_details.recurrences as \|item\|}}


{{#if @root.table_config.footer.payment_type.enable}}

{{/if}}
{{#if (isColumnEnabled @root.table_config 'net_total')}}
{{#if @root.table_config.footer.net_total.enable}}

{{/if}}
{{/if}}


{{/each}}
{{/if}}


{{column._label}}

{{#if @root.table_config.body.product_name.enable}}
{{product.name}}
{{/if}}
{{#if @root.table_config.body.price_description.enable}}


{{product.price.description}}
{{/if}}
{{#if @root.table_config.body.product_description.enable}}


{{product.description}}
{{/if}}
{{product.price.quantity}}

{{product.price.tax_rate}}

{{product.price.unit_amount_net}}

{{product.price.amount_subtotal}}

{{product.price.amount_tax}}

{{product.price.amount_total}}
{{#if @root.table_config.body.payment_type.enable}}
{{#if (eq product.price.type 'recurring')}}


{{product.price.billing_period}}
{{/if}}
{{/if}}
{{item.billing_period}} {{item.amount_subtotal}} {{item.amount_total}}
{{#if @root.table_config.footer.amount_tax.enable}}


{{item.full_amount_tax}}
{{/if}}

| +| `type` | [Optional[components.Type]](../../models/components/type.md) | :heavy_minus_sign: | Custom variable type | rbse777b-3cf8-4bff-bb0c-253fd1123250 | +| `updated_at` | *Optional[str]* | :heavy_minus_sign: | Last update time | 2022-04-20 12:41:43.662 +0000 UTC | +| `updated_by` | *Optional[str]* | :heavy_minus_sign: | Updated by | 100042 | \ No newline at end of file diff --git a/template_variables/docs/models/components/externalcustomvariable.md b/template_variables/docs/models/components/externalcustomvariable.md new file mode 100644 index 000000000..3d08742ad --- /dev/null +++ b/template_variables/docs/models/components/externalcustomvariable.md @@ -0,0 +1,9 @@ +# ExternalCustomVariable + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| `value` | *Optional[str]* | :heavy_minus_sign: | N/A | https://partner.epilot.cloud/activate-account?user_name=htny.pct%2Btet%40gmail.com&confirmation_code=EdXPRW19 | +| `variable` | *Optional[str]* | :heavy_minus_sign: | N/A | {{craftsmen.invitation_link}} | \ No newline at end of file diff --git a/template_variables/docs/models/components/httpmetadata.md b/template_variables/docs/models/components/httpmetadata.md new file mode 100644 index 000000000..5febcce06 --- /dev/null +++ b/template_variables/docs/models/components/httpmetadata.md @@ -0,0 +1,9 @@ +# HTTPMetadata + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| `response` | [requests.Response](https://requests.readthedocs.io/en/latest/api/#requests.Response) | :heavy_check_mark: | Raw HTTP response; suitable for custom response parsing | +| `request` | [requests.Request](https://requests.readthedocs.io/en/latest/api/#requests.Request) | :heavy_check_mark: | Raw HTTP request; suitable for debugging | \ No newline at end of file diff --git a/template_variables/docs/models/components/security.md b/template_variables/docs/models/components/security.md new file mode 100644 index 000000000..c59fe377f --- /dev/null +++ b/template_variables/docs/models/components/security.md @@ -0,0 +1,9 @@ +# Security + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `epilot_auth` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `epilot_org` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/components/templatetype.md b/template_variables/docs/models/components/templatetype.md new file mode 100644 index 000000000..d6ed07125 --- /dev/null +++ b/template_variables/docs/models/components/templatetype.md @@ -0,0 +1,9 @@ +# TemplateType + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `EMAIL` | email | +| `DOCUMENT` | document | \ No newline at end of file diff --git a/template_variables/docs/models/components/type.md b/template_variables/docs/models/components/type.md new file mode 100644 index 000000000..05dad8853 --- /dev/null +++ b/template_variables/docs/models/components/type.md @@ -0,0 +1,11 @@ +# Type + +Custom variable type + + +## Values + +| Name | Value | +| ------------- | ------------- | +| `ORDER_TABLE` | order_table | +| `CUSTOM` | custom | \ No newline at end of file diff --git a/template_variables/docs/models/components/variablecontext.md b/template_variables/docs/models/components/variablecontext.md new file mode 100644 index 000000000..caa83e2a8 --- /dev/null +++ b/template_variables/docs/models/components/variablecontext.md @@ -0,0 +1,11 @@ +# VariableContext + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +| `brand` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | {
"$ref": "#/components/examples/ExampleBrand/value"
} | +| `contact` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | {
"$ref": "#/components/examples/ExampleContactEntity/value"
} | +| `main` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | {
"$ref": "#/components/examples/ExampleMain/value"
} | +| `unsubscribe_url` | *Optional[str]* | :heavy_minus_sign: | N/A | https://consent.sls.epilot.io/v1/unsubscribe?token=abc123 | \ No newline at end of file diff --git a/template_variables/docs/models/components/variableparameters.md b/template_variables/docs/models/components/variableparameters.md new file mode 100644 index 000000000..5d5491486 --- /dev/null +++ b/template_variables/docs/models/components/variableparameters.md @@ -0,0 +1,18 @@ +# VariableParameters + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `template_type` | [components.TemplateType](../../models/components/templatetype.md) | :heavy_check_mark: | N/A | | +| `brand_id` | *Optional[float]* | :heavy_minus_sign: | Brand ID | 123451 | +| `context_data` | [Optional[components.ContextData]](../../models/components/contextdata.md) | :heavy_minus_sign: | If context data is avaialble, this data will be used for variable replace. | | +| `custom_variables` | List[[components.ExternalCustomVariable](../../models/components/externalcustomvariable.md)] | :heavy_minus_sign: | Custom variables with specified values form other services. | | +| `language` | *Optional[str]* | :heavy_minus_sign: | 2-letter language code (ISO 639-1) | | +| `main_entity_id` | *Optional[str]* | :heavy_minus_sign: | The main entity ID. Use main entity in order to use the variable without schema slug prefix - or just pass directly to other object ID. | 63753437-c9e2-4e83-82bb-b1c666514561 | +| `template_name` | *Optional[str]* | :heavy_minus_sign: | The name of email template | | +| `template_tags` | List[*str*] | :heavy_minus_sign: | The tags of email template | | +| `user_id` | *Optional[str]* | :heavy_minus_sign: | User ID | 50001 | +| `user_org_id` | *Optional[str]* | :heavy_minus_sign: | Organization ID of the user | 729224 | +| `variables_version` | *Optional[str]* | :heavy_minus_sign: | The version of the variables syntax supported. Default is 1.0 | 2 | \ No newline at end of file diff --git a/template_variables/docs/models/components/variableresult.md b/template_variables/docs/models/components/variableresult.md new file mode 100644 index 000000000..97d1d5367 --- /dev/null +++ b/template_variables/docs/models/components/variableresult.md @@ -0,0 +1,12 @@ +# VariableResult + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | Variable description | +| `group` | *Optional[str]* | :heavy_minus_sign: | Variable group | +| `insert` | *Optional[str]* | :heavy_minus_sign: | The value which is used to insert to template | +| `qrdata` | *Optional[str]* | :heavy_minus_sign: | Payload for the QR data | +| `type` | [Optional[components.VariableResultType]](../../models/components/variableresulttype.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/components/variableresulttype.md b/template_variables/docs/models/components/variableresulttype.md new file mode 100644 index 000000000..a4605a78b --- /dev/null +++ b/template_variables/docs/models/components/variableresulttype.md @@ -0,0 +1,9 @@ +# VariableResultType + + +## Values + +| Name | Value | +| --------- | --------- | +| `SIMPLE` | simple | +| `PARTIAL` | partial | \ No newline at end of file diff --git a/template_variables/docs/models/operations/createcustomvariableresponse.md b/template_variables/docs/models/operations/createcustomvariableresponse.md new file mode 100644 index 000000000..b90ee0a2e --- /dev/null +++ b/template_variables/docs/models/operations/createcustomvariableresponse.md @@ -0,0 +1,8 @@ +# CreateCustomVariableResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/operations/deletecustomvariablerequest.md b/template_variables/docs/models/operations/deletecustomvariablerequest.md new file mode 100644 index 000000000..e1d80ec54 --- /dev/null +++ b/template_variables/docs/models/operations/deletecustomvariablerequest.md @@ -0,0 +1,8 @@ +# DeleteCustomVariableRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `id` | *str* | :heavy_check_mark: | Custom vairable ID | \ No newline at end of file diff --git a/template_variables/docs/models/operations/deletecustomvariableresponse.md b/template_variables/docs/models/operations/deletecustomvariableresponse.md new file mode 100644 index 000000000..848240f00 --- /dev/null +++ b/template_variables/docs/models/operations/deletecustomvariableresponse.md @@ -0,0 +1,8 @@ +# DeleteCustomVariableResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/operations/getblueprinttableconfigresponse.md b/template_variables/docs/models/operations/getblueprinttableconfigresponse.md new file mode 100644 index 000000000..f8fb66fb3 --- /dev/null +++ b/template_variables/docs/models/operations/getblueprinttableconfigresponse.md @@ -0,0 +1,9 @@ +# GetBluePrintTableConfigResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `custom_variable` | [Optional[components.CustomVariable]](../../models/components/customvariable.md) | :heavy_minus_sign: | Success | \ No newline at end of file diff --git a/template_variables/docs/models/operations/getcategoriesrequest.md b/template_variables/docs/models/operations/getcategoriesrequest.md new file mode 100644 index 000000000..02e735a7d --- /dev/null +++ b/template_variables/docs/models/operations/getcategoriesrequest.md @@ -0,0 +1,8 @@ +# GetCategoriesRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `lang` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/operations/getcategoriesresponse.md b/template_variables/docs/models/operations/getcategoriesresponse.md new file mode 100644 index 000000000..95b6831ed --- /dev/null +++ b/template_variables/docs/models/operations/getcategoriesresponse.md @@ -0,0 +1,9 @@ +# GetCategoriesResponse + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `classes` | List[[components.CategoryResult](../../models/components/categoryresult.md)] | :heavy_minus_sign: | ok | \ No newline at end of file diff --git a/template_variables/docs/models/operations/getcustomvariablerequest.md b/template_variables/docs/models/operations/getcustomvariablerequest.md new file mode 100644 index 000000000..bbf2995d8 --- /dev/null +++ b/template_variables/docs/models/operations/getcustomvariablerequest.md @@ -0,0 +1,8 @@ +# GetCustomVariableRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `id` | *str* | :heavy_check_mark: | Custom vairable ID | \ No newline at end of file diff --git a/template_variables/docs/models/operations/getcustomvariableresponse.md b/template_variables/docs/models/operations/getcustomvariableresponse.md new file mode 100644 index 000000000..927f8ab28 --- /dev/null +++ b/template_variables/docs/models/operations/getcustomvariableresponse.md @@ -0,0 +1,9 @@ +# GetCustomVariableResponse + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `custom_variable` | [Optional[components.CustomVariable]](../../models/components/customvariable.md) | :heavy_minus_sign: | Success | \ No newline at end of file diff --git a/template_variables/docs/models/operations/getcustomvariablesresponse.md b/template_variables/docs/models/operations/getcustomvariablesresponse.md new file mode 100644 index 000000000..99c50890c --- /dev/null +++ b/template_variables/docs/models/operations/getcustomvariablesresponse.md @@ -0,0 +1,9 @@ +# GetCustomVariablesResponse + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `classes` | List[[components.CustomVariable](../../models/components/customvariable.md)] | :heavy_minus_sign: | Success | \ No newline at end of file diff --git a/template_variables/docs/models/operations/getvariablecontextrequestbody.md b/template_variables/docs/models/operations/getvariablecontextrequestbody.md new file mode 100644 index 000000000..333223d1c --- /dev/null +++ b/template_variables/docs/models/operations/getvariablecontextrequestbody.md @@ -0,0 +1,8 @@ +# GetVariableContextRequestBody + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `parameters` | [Optional[components.VariableParameters]](../../models/components/variableparameters.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/operations/getvariablecontextresponse.md b/template_variables/docs/models/operations/getvariablecontextresponse.md new file mode 100644 index 000000000..8ac3340ed --- /dev/null +++ b/template_variables/docs/models/operations/getvariablecontextresponse.md @@ -0,0 +1,9 @@ +# GetVariableContextResponse + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `variable_context` | [Optional[components.VariableContext]](../../models/components/variablecontext.md) | :heavy_minus_sign: | ok | \ No newline at end of file diff --git a/template_variables/docs/models/operations/replacetemplatesrequestbody.md b/template_variables/docs/models/operations/replacetemplatesrequestbody.md new file mode 100644 index 000000000..1f118f1f7 --- /dev/null +++ b/template_variables/docs/models/operations/replacetemplatesrequestbody.md @@ -0,0 +1,9 @@ +# ReplaceTemplatesRequestBody + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `inputs` | List[*str*] | :heavy_minus_sign: | N/A | +| `parameters` | [Optional[components.VariableParameters]](../../models/components/variableparameters.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/operations/replacetemplatesresponse.md b/template_variables/docs/models/operations/replacetemplatesresponse.md new file mode 100644 index 000000000..a1bd27d5d --- /dev/null +++ b/template_variables/docs/models/operations/replacetemplatesresponse.md @@ -0,0 +1,9 @@ +# ReplaceTemplatesResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `object` | [Optional[operations.ReplaceTemplatesResponseBody]](../../models/operations/replacetemplatesresponsebody.md) | :heavy_minus_sign: | ok | \ No newline at end of file diff --git a/template_variables/docs/models/operations/replacetemplatesresponsebody.md b/template_variables/docs/models/operations/replacetemplatesresponsebody.md new file mode 100644 index 000000000..a247a94ff --- /dev/null +++ b/template_variables/docs/models/operations/replacetemplatesresponsebody.md @@ -0,0 +1,10 @@ +# ReplaceTemplatesResponseBody + +ok + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `outputs` | List[*str*] | :heavy_minus_sign: | N/A | "[Brand Name GmbH] Order confirmation",
"Hello Customer Name

Brand Name GmbH
Brand Name
imprint
"]
| \ No newline at end of file diff --git a/template_variables/docs/models/operations/searchvariablesrequestbody.md b/template_variables/docs/models/operations/searchvariablesrequestbody.md new file mode 100644 index 000000000..d9cf3e05a --- /dev/null +++ b/template_variables/docs/models/operations/searchvariablesrequestbody.md @@ -0,0 +1,13 @@ +# SearchVariablesRequestBody + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `query` | *str* | :heavy_check_mark: | Search string | logo | +| `template_type` | [components.TemplateType](../../models/components/templatetype.md) | :heavy_check_mark: | N/A | | +| `entity_schemas` | List[*str*] | :heavy_minus_sign: | N/A | | +| `from_` | *Optional[int]* | :heavy_minus_sign: | N/A | | +| `lang` | *Optional[str]* | :heavy_minus_sign: | 2-letter language code (ISO 639-1) | | +| `size` | *Optional[int]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/template_variables/docs/models/operations/searchvariablesresponse.md b/template_variables/docs/models/operations/searchvariablesresponse.md new file mode 100644 index 000000000..678aafb72 --- /dev/null +++ b/template_variables/docs/models/operations/searchvariablesresponse.md @@ -0,0 +1,9 @@ +# SearchVariablesResponse + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | +| `classes` | List[[components.VariableResult](../../models/components/variableresult.md)] | :heavy_minus_sign: | ok | \ No newline at end of file diff --git a/template_variables/docs/models/operations/updatecustomvariablerequest.md b/template_variables/docs/models/operations/updatecustomvariablerequest.md new file mode 100644 index 000000000..4dfe6aa05 --- /dev/null +++ b/template_variables/docs/models/operations/updatecustomvariablerequest.md @@ -0,0 +1,9 @@ +# UpdateCustomVariableRequest + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | Custom variable ID | +| `custom_variable` | [Optional[components.CustomVariable]](../../models/components/customvariable.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/template_variables/docs/models/operations/updatecustomvariableresponse.md b/template_variables/docs/models/operations/updatecustomvariableresponse.md new file mode 100644 index 000000000..f3a974eee --- /dev/null +++ b/template_variables/docs/models/operations/updatecustomvariableresponse.md @@ -0,0 +1,8 @@ +# UpdateCustomVariableResponse + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | +| `http_meta` | [components.HTTPMetadata](../../models/components/httpmetadata.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/template_variables/docs/sdks/customvariables/README.md b/template_variables/docs/sdks/customvariables/README.md new file mode 100644 index 000000000..c7266b389 --- /dev/null +++ b/template_variables/docs/sdks/customvariables/README.md @@ -0,0 +1,491 @@ +# CustomVariables +(*custom_variables*) + +### Available Operations + +* [create_custom_variable](#create_custom_variable) - Create custom variable +* [delete_custom_variable](#delete_custom_variable) - Delete custom variable +* [get_blue_print_table_config](#get_blue_print_table_config) - Get default table config +* [get_custom_variable](#get_custom_variable) - Get custom variable +* [get_custom_variables](#get_custom_variables) - Get custom variables +* [update_custom_variable](#update_custom_variable) - Update custom variable + +## create_custom_variable + +Create custom variable + +### Example Usage + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + +req = components.CustomVariable( + config=components.Config(), + created_at='2022-04-19T12:41:43.662Z', + created_by='100042', + helper_logic='return param1 * param2;', + helper_params=[ + 'param1', + 'param2', + ], + id='rbse777b-3cf8-4bff-bb0c-253fd1123250', + key='my_custom_table', + name='My Custom table', + template=' + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id \'item\')}} + + + {{/if}} + {{#if (eq column.id \'quantity\')}} + + + {{/if}} + {{#if (eq column.id \'tax\')}} + + + {{/if}} + {{#if (eq column.id \'unit_amount\')}} + + + {{/if}} + {{#if (eq column.id \'net_total\')}} + + + {{/if}} + {{#if (eq column.id \'amount_tax\')}} + + + {{/if}} + {{#if (eq column.id \'gross_total\')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config \'net_total\')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type \'recurring\')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+', + type=components.Type.CUSTOM, + updated_at='2022-04-20T12:41:43.662Z', + updated_by='100042', +) + +res = s.custom_variables.create_custom_variable(req) + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `request` | [components.CustomVariable](../../models/components/customvariable.md) | :heavy_check_mark: | The request object to use for the request. | + + +### Response + +**[operations.CreateCustomVariableResponse](../../models/operations/createcustomvariableresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +## delete_custom_variable + +Immediately and permanently deletes a custom variable + +### Example Usage + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + + +res = s.custom_variables.delete_custom_variable(id='') + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `id` | *str* | :heavy_check_mark: | Custom vairable ID | + + +### Response + +**[operations.DeleteCustomVariableResponse](../../models/operations/deletecustomvariableresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +## get_blue_print_table_config + +Get default table config + +### Example Usage + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + + +res = s.custom_variables.get_blue_print_table_config() + +if res.custom_variable is not None: + # handle response + pass + +``` + + +### Response + +**[operations.GetBluePrintTableConfigResponse](../../models/operations/getblueprinttableconfigresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +## get_custom_variable + +Get custom variable + +### Example Usage + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + + +res = s.custom_variables.get_custom_variable(id='') + +if res.custom_variable is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `id` | *str* | :heavy_check_mark: | Custom vairable ID | + + +### Response + +**[operations.GetCustomVariableResponse](../../models/operations/getcustomvariableresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +## get_custom_variables + +Get all custom variables of organization + +### Example Usage + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + + +res = s.custom_variables.get_custom_variables() + +if res.classes is not None: + # handle response + pass + +``` + + +### Response + +**[operations.GetCustomVariablesResponse](../../models/operations/getcustomvariablesresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +## update_custom_variable + +Update custom variable + +### Example Usage + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + + +res = s.custom_variables.update_custom_variable(id='', custom_variable=components.CustomVariable( + config=components.Config(), + created_at='2022-04-19T12:41:43.662Z', + created_by='100042', + helper_logic='return param1 * param2;', + helper_params=[ + 'param1', + 'param2', + ], + id='rbse777b-3cf8-4bff-bb0c-253fd1123250', + key='my_custom_table', + name='My Custom table', + template=' + + + {{#each table_config.header.columns as |column|}} + {{#if column.enable}} + + {{/if}} + {{/each}} + + + + + {{#each order.products as |product|}} + {{#if @last}} + + {{else}} + + {{/if}} + {{#each @root.table_config.header.columns as |column|}} + {{#if column.enable}} + {{#if (eq column.id \'item\')}} + + + {{/if}} + {{#if (eq column.id \'quantity\')}} + + + {{/if}} + {{#if (eq column.id \'tax\')}} + + + {{/if}} + {{#if (eq column.id \'unit_amount\')}} + + + {{/if}} + {{#if (eq column.id \'net_total\')}} + + + {{/if}} + {{#if (eq column.id \'amount_tax\')}} + + + {{/if}} + {{#if (eq column.id \'gross_total\')}} + + + {{/if}} + {{/if}} + {{/each}} + + {{/each}} + + {{#if table_config.footer.gross_total.enable}} + {{#each order.total_details.recurrences as |item|}} + + + {{#if @root.table_config.footer.payment_type.enable}} + + {{/if}} + {{#if (isColumnEnabled @root.table_config \'net_total\')}} + {{#if @root.table_config.footer.net_total.enable}} + + {{/if}} + {{/if}} + + + {{/each}} + {{/if}} + + +
{{column._label}}
+ {{#if @root.table_config.body.product_name.enable}} + {{product.name}} + {{/if}} + {{#if @root.table_config.body.price_description.enable}} +
+ {{product.price.description}} + {{/if}} + {{#if @root.table_config.body.product_description.enable}} +
+ {{product.description}} + {{/if}} +
{{product.price.quantity}} + + {{product.price.tax_rate}} + + {{product.price.unit_amount_net}} + + {{product.price.amount_subtotal}} + + {{product.price.amount_tax}} + + {{product.price.amount_total}} + {{#if @root.table_config.body.payment_type.enable}} + {{#if (eq product.price.type \'recurring\')}} +
+ {{product.price.billing_period}} + {{/if}} + {{/if}} +
{{item.billing_period}}{{item.amount_subtotal}}{{item.amount_total}} + {{#if @root.table_config.footer.amount_tax.enable}} +
+ {{item.full_amount_tax}} + {{/if}} +
+', + type=components.Type.CUSTOM, + updated_at='2022-04-20T12:41:43.662Z', + updated_by='100042', +)) + +if res is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | Custom variable ID | +| `custom_variable` | [Optional[components.CustomVariable]](../../models/components/customvariable.md) | :heavy_minus_sign: | N/A | + + +### Response + +**[operations.UpdateCustomVariableResponse](../../models/operations/updatecustomvariableresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | diff --git a/template_variables/docs/sdks/epilot/README.md b/template_variables/docs/sdks/epilot/README.md new file mode 100644 index 000000000..06007ebbc --- /dev/null +++ b/template_variables/docs/sdks/epilot/README.md @@ -0,0 +1,9 @@ +# Epilot SDK + + +## Overview + +Template Variables API: API to provide variables for email and document templates. + +### Available Operations + diff --git a/template_variables/docs/sdks/variables/README.md b/template_variables/docs/sdks/variables/README.md new file mode 100644 index 000000000..f318dc54d --- /dev/null +++ b/template_variables/docs/sdks/variables/README.md @@ -0,0 +1,189 @@ +# Variables +(*variables*) + +## Overview + +Variables + +### Available Operations + +* [get_categories](#get_categories) - getCategories +* [get_variable_context](#get_variable_context) - getVariableContext +* [replace_templates](#replace_templates) - replaceTemplates +* [search_variables](#search_variables) - searchVariables + +## get_categories + +Get all template variable categories + +### Example Usage + +```python +import epilot +from epilot.models import components + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + + +res = s.variables.get_categories(lang='de') + +if res.classes is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `lang` | *Optional[str]* | :heavy_minus_sign: | N/A | + + +### Response + +**[operations.GetCategoriesResponse](../../models/operations/getcategoriesresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +## get_variable_context + +Get full variable context + +Calls Entity API, User API, Brand API and others to construct full context object used for template variable replace + + +### Example Usage + +```python +import epilot +from epilot.models import components, operations + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + +req = operations.GetVariableContextRequestBody() + +res = s.variables.get_variable_context(req) + +if res.variable_context is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetVariableContextRequestBody](../../models/operations/getvariablecontextrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | + + +### Response + +**[operations.GetVariableContextResponse](../../models/operations/getvariablecontextresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +## replace_templates + +Replace variables in handlebars templates + +Takes in an array of input templates and outputs the output text with replaced variables + + +### Example Usage + +```python +import epilot +from epilot.models import components, operations + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + +req = operations.ReplaceTemplatesRequestBody() + +res = s.variables.replace_templates(req) + +if res.object is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `request` | [operations.ReplaceTemplatesRequestBody](../../models/operations/replacetemplatesrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | + + +### Response + +**[operations.ReplaceTemplatesResponse](../../models/operations/replacetemplatesresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | + +## search_variables + +Search variables + +### Example Usage + +```python +import epilot +from epilot.models import components, operations + +s = epilot.Epilot( + security=components.Security( + epilot_auth="", + ), +) + +req = operations.SearchVariablesRequestBody( + query='logo', + template_type=components.TemplateType.DOCUMENT, +) + +res = s.variables.search_variables(req) + +if res.classes is not None: + # handle response + pass + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `request` | [operations.SearchVariablesRequestBody](../../models/operations/searchvariablesrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | + + +### Response + +**[operations.SearchVariablesResponse](../../models/operations/searchvariablesresponse.md)** +### Errors + +| Error Object | Status Code | Content Type | +| --------------- | --------------- | --------------- | +| errors.SDKError | 4xx-5xx | */* | diff --git a/template_variables/gen.yaml b/template_variables/gen.yaml index e2cd3c1a9..3fda38987 100644 --- a/template_variables/gen.yaml +++ b/template_variables/gen.yaml @@ -1,16 +1,37 @@ -configVersion: 1.0.0 -management: - docChecksum: 14e2961bd134888671409e73ce503882 - docVersion: 1.0.0 - speakeasyVersion: 1.19.2 - generationVersion: 2.16.5 +configVersion: 2.0.0 generation: - telemetryEnabled: false sdkClassName: epilot + usageSnippets: + optionalPropertyRendering: withExample + fixes: + nameResolutionDec2023: false + parameterOrderingFeb2024: false + requestResponseComponentNamesFeb2024: false + auth: + oAuth2ClientCredentialsEnabled: false sdkFlattening: true - singleTagPerOp: false + telemetryEnabled: false python: - version: 1.2.2 + version: 1.3.0 + additionalDependencies: + dependencies: {} + extraDependencies: + dev: {} author: epilot + clientServerStatusCodesAsErrors: true description: Python Client SDK for Epilot + flattenGlobalSecurity: true + imports: + option: openapi + paths: + callbacks: models/callbacks + errors: models/errors + operations: models/operations + shared: models/components + webhooks: models/webhooks + inputModelSuffix: input + maxMethodParams: 4 + outputModelSuffix: output packageName: epilot-template-variables + projectUrls: {} + responseFormat: envelope-http diff --git a/template_variables/py.typed b/template_variables/py.typed new file mode 100644 index 000000000..3e38f1a92 --- /dev/null +++ b/template_variables/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The package enables type hints. diff --git a/template_variables/pylintrc b/template_variables/pylintrc old mode 100755 new mode 100644 index 79b8008d0..6a1c3fc06 --- a/template_variables/pylintrc +++ b/template_variables/pylintrc @@ -88,7 +88,7 @@ persistent=yes # Minimum Python version to use for version dependent checks. Will default to # the version used to run pylint. -py-version=3.9 +py-version=3.8 # Discover python modules and packages in the file system subtree. recursive=no @@ -116,20 +116,15 @@ argument-naming-style=snake_case #argument-rgx= # Naming style matching correct attribute names. -attr-naming-style=snake_case +#attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. If left empty, attribute names will be checked with the set naming # style. -#attr-rgx= +attr-rgx=[^\W\d][^\W]*|__.*__$ # Bad variable names which should always be refused, separated by a comma. -bad-names=foo, - bar, - baz, - toto, - tutu, - tata +bad-names= # Bad variable names regexes, separated by a comma. If names match any regex, # they will always be refused @@ -185,6 +180,7 @@ good-names=i, ex, Run, _, + e, id # Good variable names regexes, separated by a comma. If names match any regex, @@ -439,7 +435,15 @@ disable=raw-checker-failed, trailing-newlines, too-many-public-methods, too-many-locals, - too-many-lines + too-many-lines, + using-constant-test, + too-many-statements, + cyclic-import, + too-many-nested-blocks, + too-many-boolean-expressions, + no-else-raise, + bare-except, + broad-exception-caught # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option @@ -620,7 +624,7 @@ additional-builtins= allow-global-unused-variables=yes # List of names allowed to shadow builtins -allowed-redefined-builtins= +allowed-redefined-builtins=id,object # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. diff --git a/template_variables/setup.py b/template_variables/setup.py old mode 100755 new mode 100644 index 59b02d846..89b30833a --- a/template_variables/setup.py +++ b/template_variables/setup.py @@ -1,39 +1,55 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" import setuptools +import re try: - with open("README.md", "r") as fh: + with open('README.md', 'r') as fh: long_description = fh.read() + GITHUB_URL = 'https://github.com/epilot-dev/sdk-python.git' + GITHUB_URL = GITHUB_URL[: -len('.git')] if GITHUB_URL.endswith('.git') else GITHUB_URL + # links on PyPI should have absolute URLs + long_description = re.sub( + r'(\[[^\]]+\]\()((?!https?:)[^\)]+)(\))', + lambda m: m.group(1) + GITHUB_URL + '/blob/master/' + m.group(2) + m.group(3), + long_description, + ) except FileNotFoundError: - long_description = "" + long_description = '' setuptools.setup( - name="epilot-template-variables", - version="1.2.2", - author="epilot", - description="Python Client SDK for Epilot", + name='epilot-template-variables', + version='1.3.0', + author='epilot', + description='Python Client SDK for Epilot', + url='https://github.com/epilot-dev/sdk-python.git', long_description=long_description, - long_description_content_type="text/markdown", - packages=setuptools.find_packages(where="src"), + long_description_content_type='text/markdown', + packages=setuptools.find_packages(where='src'), install_requires=[ - "certifi==2022.12.07", - "charset-normalizer==2.1.1", - "dataclasses-json-speakeasy==0.5.8", - "idna==3.3", - "marshmallow==3.17.1", - "marshmallow-enum==1.5.1", - "mypy-extensions==0.4.3", - "packaging==21.3", - "pyparsing==3.0.9", - "python-dateutil==2.8.2", - "requests==2.28.1", - "six==1.16.0", - "typing-inspect==0.8.0", - "typing_extensions==4.3.0", - "urllib3==1.26.12", - "pylint==2.16.2", + "certifi>=2023.7.22", + "charset-normalizer>=3.2.0", + "dataclasses-json>=0.6.4", + "idna>=3.4", + "jsonpath-python>=1.0.6", + "marshmallow>=3.19.0", + "mypy-extensions>=1.0.0", + "packaging>=23.1", + "python-dateutil>=2.8.2", + "requests>=2.31.0", + "six>=1.16.0", + "typing-inspect>=0.9.0", + "typing_extensions>=4.7.1", + "urllib3>=1.26.18", ], + extras_require={ + "dev": [ + "pylint==3.1.0", + ], + }, package_dir={'': 'src'}, - python_requires='>=3.9' + python_requires='>=3.8', + package_data={ + 'epilot-template-variables': ['py.typed'] + }, ) diff --git a/template_variables/src/epilot/__init__.py b/template_variables/src/epilot/__init__.py old mode 100755 new mode 100644 index b9e232018..e6c0deeb6 --- a/template_variables/src/epilot/__init__.py +++ b/template_variables/src/epilot/__init__.py @@ -1,3 +1,4 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" from .sdk import * +from .sdkconfiguration import * diff --git a/template_variables/src/epilot/_hooks/__init__.py b/template_variables/src/epilot/_hooks/__init__.py new file mode 100644 index 000000000..5fd985a8a --- /dev/null +++ b/template_variables/src/epilot/_hooks/__init__.py @@ -0,0 +1,5 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from .sdkhooks import * +from .types import * +from .registration import * diff --git a/template_variables/src/epilot/_hooks/registration.py b/template_variables/src/epilot/_hooks/registration.py new file mode 100644 index 000000000..1db6a5293 --- /dev/null +++ b/template_variables/src/epilot/_hooks/registration.py @@ -0,0 +1,13 @@ +from .types import Hooks + + +# This file is only ever generated once on the first generation and then is free to be modified. +# Any hooks you wish to add should be registered in the init_hooks function. Feel free to define them +# in this file or in separate files in the hooks folder. + + +def init_hooks(hooks: Hooks): + # pylint: disable=unused-argument + """Add hooks by calling hooks.register{sdk_init/before_request/after_success/after_error}Hook + with an instance of a hook that implements that specific Hook interface + Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance""" diff --git a/template_variables/src/epilot/_hooks/sdkhooks.py b/template_variables/src/epilot/_hooks/sdkhooks.py new file mode 100644 index 000000000..17750b62c --- /dev/null +++ b/template_variables/src/epilot/_hooks/sdkhooks.py @@ -0,0 +1,57 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +import requests +from .types import SDKInitHook, BeforeRequestContext, BeforeRequestHook, AfterSuccessContext, AfterSuccessHook, AfterErrorContext, AfterErrorHook, Hooks +from .registration import init_hooks +from typing import List, Optional, Tuple + + +class SDKHooks(Hooks): + def __init__(self): + self.sdk_init_hooks: List[SDKInitHook] = [] + self.before_request_hooks: List[BeforeRequestHook] = [] + self.after_success_hooks: List[AfterSuccessHook] = [] + self.after_error_hooks: List[AfterErrorHook] = [] + init_hooks(self) + + def register_sdk_init_hook(self, hook: SDKInitHook) -> None: + self.sdk_init_hooks.append(hook) + + def register_before_request_hook(self, hook: BeforeRequestHook) -> None: + self.before_request_hooks.append(hook) + + def register_after_success_hook(self, hook: AfterSuccessHook) -> None: + self.after_success_hooks.append(hook) + + def register_after_error_hook(self, hook: AfterErrorHook) -> None: + self.after_error_hooks.append(hook) + + def sdk_init(self, base_url: str, client: requests.Session) -> Tuple[str, requests.Session]: + for hook in self.sdk_init_hooks: + base_url, client = hook.sdk_init(base_url, client) + return base_url, client + + def before_request(self, hook_ctx: BeforeRequestContext, request: requests.PreparedRequest) -> requests.PreparedRequest: + for hook in self.before_request_hooks: + out = hook.before_request(hook_ctx, request) + if isinstance(out, Exception): + raise out + request = out + + return request + + def after_success(self, hook_ctx: AfterSuccessContext, response: requests.Response) -> requests.Response: + for hook in self.after_success_hooks: + out = hook.after_success(hook_ctx, response) + if isinstance(out, Exception): + raise out + response = out + return response + + def after_error(self, hook_ctx: AfterErrorContext, response: Optional[requests.Response], error: Optional[Exception]) -> Tuple[Optional[requests.Response], Optional[Exception]]: + for hook in self.after_error_hooks: + result = hook.after_error(hook_ctx, response, error) + if isinstance(result, Exception): + raise result + response, error = result + return response, error diff --git a/template_variables/src/epilot/_hooks/types.py b/template_variables/src/epilot/_hooks/types.py new file mode 100644 index 000000000..b24c14146 --- /dev/null +++ b/template_variables/src/epilot/_hooks/types.py @@ -0,0 +1,74 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +import requests as requests_http +from abc import ABC, abstractmethod +from typing import Any, Callable, List, Optional, Tuple, Union + + +class HookContext: + operation_id: str + oauth2_scopes: Optional[List[str]] = None + security_source: Optional[Union[Any, Callable[[], Any]]] = None + + def __init__(self, operation_id: str, oauth2_scopes: Optional[List[str]], security_source: Optional[Union[Any, Callable[[], Any]]]): + self.operation_id = operation_id + self.oauth2_scopes = oauth2_scopes + self.security_source = security_source + + +class BeforeRequestContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source) + + +class AfterSuccessContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source) + + + +class AfterErrorContext(HookContext): + def __init__(self, hook_ctx: HookContext): + super().__init__(hook_ctx.operation_id, hook_ctx.oauth2_scopes, hook_ctx.security_source) + + +class SDKInitHook(ABC): + @abstractmethod + def sdk_init(self, base_url: str, client: requests_http.Session) -> Tuple[str, requests_http.Session]: + pass + + +class BeforeRequestHook(ABC): + @abstractmethod + def before_request(self, hook_ctx: BeforeRequestContext, request: requests_http.PreparedRequest) -> Union[requests_http.PreparedRequest, Exception]: + pass + + +class AfterSuccessHook(ABC): + @abstractmethod + def after_success(self, hook_ctx: AfterSuccessContext, response: requests_http.Response) -> Union[requests_http.Response, Exception]: + pass + + +class AfterErrorHook(ABC): + @abstractmethod + def after_error(self, hook_ctx: AfterErrorContext, response: Optional[requests_http.Response], error: Optional[Exception]) -> Union[Tuple[Optional[requests_http.Response], Optional[Exception]], Exception]: + pass + + +class Hooks(ABC): + @abstractmethod + def register_sdk_init_hook(self, hook: SDKInitHook): + pass + + @abstractmethod + def register_before_request_hook(self, hook: BeforeRequestHook): + pass + + @abstractmethod + def register_after_success_hook(self, hook: AfterSuccessHook): + pass + + @abstractmethod + def register_after_error_hook(self, hook: AfterErrorHook): + pass diff --git a/template_variables/src/epilot/custom_variables.py b/template_variables/src/epilot/custom_variables.py old mode 100755 new mode 100644 index 694b42779..e01b5e1ac --- a/template_variables/src/epilot/custom_variables.py +++ b/template_variables/src/epilot/custom_variables.py @@ -1,170 +1,357 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" import requests as requests_http -from . import utils -from epilot.models import operations, shared -from typing import Optional +from .sdkconfiguration import SDKConfiguration +from epilot import utils +from epilot._hooks import AfterErrorContext, AfterSuccessContext, BeforeRequestContext, HookContext +from epilot.models import components, errors, operations +from typing import List, Optional class CustomVariables: - _client: requests_http.Session - _security_client: requests_http.Session - _server_url: str - _language: str - _sdk_version: str - _gen_version: str - - def __init__(self, client: requests_http.Session, security_client: requests_http.Session, server_url: str, language: str, sdk_version: str, gen_version: str) -> None: - self._client = client - self._security_client = security_client - self._server_url = server_url - self._language = language - self._sdk_version = sdk_version - self._gen_version = gen_version - - def create_custom_variable(self, request: shared.CustomVariable) -> operations.CreateCustomVariableResponse: + sdk_configuration: SDKConfiguration + + def __init__(self, sdk_config: SDKConfiguration) -> None: + self.sdk_configuration = sdk_config + + + + def create_custom_variable(self, request: Optional[components.CustomVariable]) -> operations.CreateCustomVariableResponse: r"""Create custom variable Create custom variable """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='createCustomVariable', oauth2_scopes=[], security_source=self.sdk_configuration.security) + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = base_url.removesuffix('/') + '/v1/custom-variables' + url = base_url + '/v1/custom-variables' - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "request", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - client = self._security_client + req_content_type, data, form = utils.serialize_request_body(request, Optional[components.CustomVariable], "request", False, True, 'json') + if req_content_type is not None and req_content_type not in ('multipart/form-data', 'multipart/mixed'): + headers['content-type'] = req_content_type + headers['Accept'] = '*/*' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('POST', url, params=query_params, data=data, files=form, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.CreateCustomVariableResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['403','4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + - if http_res.status_code in [201, 403]: + + res = operations.CreateCustomVariableResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) + + if http_res.status_code == 201: pass + elif http_res.status_code == 403 or http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res - def delete_custom_variable(self, request: operations.DeleteCustomVariableRequest) -> operations.DeleteCustomVariableResponse: + + + def delete_custom_variable(self, id: str) -> operations.DeleteCustomVariableResponse: r"""Delete custom variable Immediately and permanently deletes a custom variable """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='deleteCustomVariable', oauth2_scopes=[], security_source=self.sdk_configuration.security) + request = operations.DeleteCustomVariableRequest( + id=id, + ) + + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = utils.generate_url(operations.DeleteCustomVariableRequest, base_url, '/v1/custom-variables/{id}', request) + url = utils.generate_url(base_url, '/v1/custom-variables/{id}', request) + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - client = self._security_client + headers['Accept'] = '*/*' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('DELETE', url) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('DELETE', url, params=query_params, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.DeleteCustomVariableResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['403','4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + - if http_res.status_code in [204, 403]: + + res = operations.DeleteCustomVariableResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) + + if http_res.status_code == 204: pass + elif http_res.status_code == 403 or http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res + + def get_blue_print_table_config(self) -> operations.GetBluePrintTableConfigResponse: r"""Get default table config Get default table config """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='getBluePrintTableConfig', oauth2_scopes=[], security_source=self.sdk_configuration.security) + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = base_url.removesuffix('/') + '/v1/custom-variables/order-table-blueprint' + url = base_url + '/v1/custom-variables/order-table-blueprint' + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - client = self._security_client + headers['Accept'] = 'application/json' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('GET', url) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('GET', url, params=query_params, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.GetBluePrintTableConfigResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['403','4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + + + + res = operations.GetBluePrintTableConfigResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[shared.CustomVariable]) + if utils.match_content_type(http_res.headers.get('Content-Type') or '', 'application/json'): + out = utils.unmarshal_json(http_res.text, Optional[components.CustomVariable]) res.custom_variable = out - elif http_res.status_code == 403: - pass + else: + content_type = http_res.headers.get('Content-Type') + raise errors.SDKError(f'unknown content-type received: {content_type}', http_res.status_code, http_res.text, http_res) + elif http_res.status_code == 403 or http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res - def get_custom_variable(self, request: operations.GetCustomVariableRequest) -> operations.GetCustomVariableResponse: + + + def get_custom_variable(self, id: str) -> operations.GetCustomVariableResponse: r"""Get custom variable Get custom variable """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='getCustomVariable', oauth2_scopes=[], security_source=self.sdk_configuration.security) + request = operations.GetCustomVariableRequest( + id=id, + ) + + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = utils.generate_url(operations.GetCustomVariableRequest, base_url, '/v1/custom-variables/{id}', request) + url = utils.generate_url(base_url, '/v1/custom-variables/{id}', request) + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - client = self._security_client + headers['Accept'] = 'application/json' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('GET', url) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('GET', url, params=query_params, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.GetCustomVariableResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['403','404','4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + + + + res = operations.GetCustomVariableResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[shared.CustomVariable]) + if utils.match_content_type(http_res.headers.get('Content-Type') or '', 'application/json'): + out = utils.unmarshal_json(http_res.text, Optional[components.CustomVariable]) res.custom_variable = out - elif http_res.status_code in [403, 404]: - pass + else: + content_type = http_res.headers.get('Content-Type') + raise errors.SDKError(f'unknown content-type received: {content_type}', http_res.status_code, http_res.text, http_res) + elif http_res.status_code == 403 or http_res.status_code == 404 or http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res + + def get_custom_variables(self) -> operations.GetCustomVariablesResponse: r"""Get custom variables Get all custom variables of organization """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='getCustomVariables', oauth2_scopes=[], security_source=self.sdk_configuration.security) + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = base_url.removesuffix('/') + '/v1/custom-variables' + url = base_url + '/v1/custom-variables' + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - client = self._security_client + headers['Accept'] = 'application/json' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('GET', url) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('GET', url, params=query_params, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.GetCustomVariablesResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['403','4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + + + + res = operations.GetCustomVariablesResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[list[shared.CustomVariable]]) - res.custom_variables = out - elif http_res.status_code == 403: - pass + if utils.match_content_type(http_res.headers.get('Content-Type') or '', 'application/json'): + out = utils.unmarshal_json(http_res.text, Optional[List[components.CustomVariable]]) + res.classes = out + else: + content_type = http_res.headers.get('Content-Type') + raise errors.SDKError(f'unknown content-type received: {content_type}', http_res.status_code, http_res.text, http_res) + elif http_res.status_code == 403 or http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res - def update_custom_variable(self, request: operations.UpdateCustomVariableRequest) -> operations.UpdateCustomVariableResponse: + + + def update_custom_variable(self, id: str, custom_variable: Optional[components.CustomVariable] = None) -> operations.UpdateCustomVariableResponse: r"""Update custom variable Update custom variable """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='updateCustomVariable', oauth2_scopes=[], security_source=self.sdk_configuration.security) + request = operations.UpdateCustomVariableRequest( + id=id, + custom_variable=custom_variable, + ) - url = utils.generate_url(operations.UpdateCustomVariableRequest, base_url, '/v1/custom-variables/{id}', request) + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "custom_variable", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type + url = utils.generate_url(base_url, '/v1/custom-variables/{id}', request) - client = self._security_client + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - http_res = client.request('PUT', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') + req_content_type, data, form = utils.serialize_request_body(request, operations.UpdateCustomVariableRequest, "custom_variable", False, True, 'json') + if req_content_type is not None and req_content_type not in ('multipart/form-data', 'multipart/mixed'): + headers['content-type'] = req_content_type + headers['Accept'] = '*/*' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client + + try: + req = client.prepare_request(requests_http.Request('PUT', url, params=query_params, data=data, files=form, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.UpdateCustomVariableResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['403','4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + + - if http_res.status_code in [200, 403]: + res = operations.UpdateCustomVariableResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) + + if http_res.status_code == 200: pass + elif http_res.status_code == 403 or http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res - \ No newline at end of file + + diff --git a/template_variables/src/epilot/models/__init__.py b/template_variables/src/epilot/models/__init__.py old mode 100755 new mode 100644 index 889f8adcf..722bb9982 --- a/template_variables/src/epilot/models/__init__.py +++ b/template_variables/src/epilot/models/__init__.py @@ -1,2 +1,4 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +# package diff --git a/template_variables/src/epilot/models/shared/__init__.py b/template_variables/src/epilot/models/components/__init__.py old mode 100755 new mode 100644 similarity index 51% rename from template_variables/src/epilot/models/shared/__init__.py rename to template_variables/src/epilot/models/components/__init__.py index ec472dceb..97d5f2583 --- a/template_variables/src/epilot/models/shared/__init__.py +++ b/template_variables/src/epilot/models/components/__init__.py @@ -3,10 +3,11 @@ from .categoryresult import * from .customvariable import * from .externalcustomvariable import * +from .httpmetadata import * from .security import * -from .templatetype_enum import * +from .templatetype import * from .variablecontext import * from .variableparameters import * from .variableresult import * -__all__ = ["CategoryResult","CustomVariable","CustomVariableTypeEnum","ExternalCustomVariable","Security","TemplateTypeEnum","VariableContext","VariableParameters","VariableParametersLanguageEnum","VariableResult","VariableResultTypeEnum"] +__all__ = ["CategoryResult","Config","ContextData","CustomVariable","ExternalCustomVariable","HTTPMetadata","Security","TemplateType","Type","VariableContext","VariableParameters","VariableResult","VariableResultType"] diff --git a/template_variables/src/epilot/models/shared/categoryresult.py b/template_variables/src/epilot/models/components/categoryresult.py old mode 100755 new mode 100644 similarity index 83% rename from template_variables/src/epilot/models/shared/categoryresult.py rename to template_variables/src/epilot/models/components/categoryresult.py index 77ca5f503..7be1841dd --- a/template_variables/src/epilot/models/shared/categoryresult.py +++ b/template_variables/src/epilot/models/components/categoryresult.py @@ -10,7 +10,7 @@ @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class CategoryResult: + category: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('category'), 'exclude': lambda f: f is None }}) + description: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('description'), 'exclude': lambda f: f is None }}) - category: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('category'), 'exclude': lambda f: f is None }}) - description: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('description'), 'exclude': lambda f: f is None }}) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/shared/customvariable.py b/template_variables/src/epilot/models/components/customvariable.py old mode 100755 new mode 100644 similarity index 68% rename from template_variables/src/epilot/models/shared/customvariable.py rename to template_variables/src/epilot/models/components/customvariable.py index 77da1887f..9ac1d3195 --- a/template_variables/src/epilot/models/shared/customvariable.py +++ b/template_variables/src/epilot/models/components/customvariable.py @@ -5,41 +5,47 @@ from dataclasses_json import Undefined, dataclass_json from enum import Enum from epilot import utils -from typing import Any, Optional +from typing import List, Optional -class CustomVariableTypeEnum(str, Enum): + +@dataclasses.dataclass +class Config: + r"""Variable configuration""" + + + +class Type(str, Enum): r"""Custom variable type""" - ORDER_TABLE = "order_table" - CUSTOM = "custom" + ORDER_TABLE = 'order_table' + CUSTOM = 'custom' @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class CustomVariable: - r"""Success""" - - config: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('config'), 'exclude': lambda f: f is None }}) - r"""Variable configuration""" + config: Optional[Config] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('config'), 'exclude': lambda f: f is None }}) + r"""Variable configuration""" created_at: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('created_at'), 'exclude': lambda f: f is None }}) - r"""Creation time""" + r"""Creation time""" created_by: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('created_by'), 'exclude': lambda f: f is None }}) - r"""Created by""" + r"""Created by""" helper_logic: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('helper_logic'), 'exclude': lambda f: f is None }}) - r"""The helper function logic""" - helper_params: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('helper_params'), 'exclude': lambda f: f is None }}) - r"""The helper function parameter's names""" + r"""The helper function logic""" + helper_params: Optional[List[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('helper_params'), 'exclude': lambda f: f is None }}) + r"""The helper function parameter's names""" id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('id'), 'exclude': lambda f: f is None }}) - r"""ID""" + r"""ID""" key: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('key'), 'exclude': lambda f: f is None }}) - r"""The key which is used for Handlebar variable syntax {{key}}""" + r"""The key which is used for Handlebar variable syntax {{\"{{\"}}key}}""" name: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('name'), 'exclude': lambda f: f is None }}) - r"""Custom variable name""" + r"""Custom variable name""" template: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template'), 'exclude': lambda f: f is None }}) - r"""Handlebar template that used to generate the variable content""" - type: Optional[CustomVariableTypeEnum] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('type'), 'exclude': lambda f: f is None }}) - r"""Custom variable type""" + r"""Handlebar template that used to generate the variable content""" + type: Optional[Type] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('type'), 'exclude': lambda f: f is None }}) + r"""Custom variable type""" updated_at: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('updated_at'), 'exclude': lambda f: f is None }}) - r"""Last update time""" + r"""Last update time""" updated_by: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('updated_by'), 'exclude': lambda f: f is None }}) - r"""Updated by""" - \ No newline at end of file + r"""Updated by""" + + diff --git a/template_variables/src/epilot/models/shared/externalcustomvariable.py b/template_variables/src/epilot/models/components/externalcustomvariable.py old mode 100755 new mode 100644 similarity index 85% rename from template_variables/src/epilot/models/shared/externalcustomvariable.py rename to template_variables/src/epilot/models/components/externalcustomvariable.py index fe478c518..f2fd0bac7 --- a/template_variables/src/epilot/models/shared/externalcustomvariable.py +++ b/template_variables/src/epilot/models/components/externalcustomvariable.py @@ -10,7 +10,7 @@ @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class ExternalCustomVariable: + value: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('value'), 'exclude': lambda f: f is None }}) + variable: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('variable'), 'exclude': lambda f: f is None }}) - value: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('value'), 'exclude': lambda f: f is None }}) - variable: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('variable'), 'exclude': lambda f: f is None }}) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/components/httpmetadata.py b/template_variables/src/epilot/models/components/httpmetadata.py new file mode 100644 index 000000000..5a87cb4ef --- /dev/null +++ b/template_variables/src/epilot/models/components/httpmetadata.py @@ -0,0 +1,17 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from __future__ import annotations +import dataclasses +import requests as requests_http +from dataclasses_json import Undefined, dataclass_json + + +@dataclass_json(undefined=Undefined.EXCLUDE) +@dataclasses.dataclass +class HTTPMetadata: + response: requests_http.Response = dataclasses.field(metadata={'dataclasses_json': { 'exclude': lambda f: True }}) + r"""Raw HTTP response; suitable for custom response parsing""" + request: requests_http.Request = dataclasses.field(metadata={'dataclasses_json': { 'exclude': lambda f: True }}) + r"""Raw HTTP request; suitable for debugging""" + + diff --git a/template_variables/src/epilot/models/components/security.py b/template_variables/src/epilot/models/components/security.py new file mode 100644 index 000000000..19c194bc2 --- /dev/null +++ b/template_variables/src/epilot/models/components/security.py @@ -0,0 +1,13 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from __future__ import annotations +import dataclasses +from typing import Optional + + +@dataclasses.dataclass +class Security: + epilot_auth: Optional[str] = dataclasses.field(default=None, metadata={'security': { 'scheme': True, 'type': 'http', 'sub_type': 'bearer', 'field_name': 'Authorization' }}) + epilot_org: Optional[str] = dataclasses.field(default=None, metadata={'security': { 'scheme': True, 'type': 'apiKey', 'sub_type': 'header', 'field_name': 'x-ivy-org-id' }}) + + diff --git a/template_variables/src/epilot/models/shared/templatetype_enum.py b/template_variables/src/epilot/models/components/templatetype.py old mode 100755 new mode 100644 similarity index 62% rename from template_variables/src/epilot/models/shared/templatetype_enum.py rename to template_variables/src/epilot/models/components/templatetype.py index b584f7dcb..a86659010 --- a/template_variables/src/epilot/models/shared/templatetype_enum.py +++ b/template_variables/src/epilot/models/components/templatetype.py @@ -3,6 +3,6 @@ from __future__ import annotations from enum import Enum -class TemplateTypeEnum(str, Enum): - EMAIL = "email" - DOCUMENT = "document" +class TemplateType(str, Enum): + EMAIL = 'email' + DOCUMENT = 'document' diff --git a/template_variables/src/epilot/models/shared/variablecontext.py b/template_variables/src/epilot/models/components/variablecontext.py old mode 100755 new mode 100644 similarity index 56% rename from template_variables/src/epilot/models/shared/variablecontext.py rename to template_variables/src/epilot/models/components/variablecontext.py index c1b1dfb92..2efede057 --- a/template_variables/src/epilot/models/shared/variablecontext.py +++ b/template_variables/src/epilot/models/components/variablecontext.py @@ -4,16 +4,15 @@ import dataclasses from dataclasses_json import Undefined, dataclass_json from epilot import utils -from typing import Any, Optional +from typing import Any, Dict, Optional @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class VariableContext: - r"""ok""" + brand: Optional[Dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('brand'), 'exclude': lambda f: f is None }}) + contact: Optional[Dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('contact'), 'exclude': lambda f: f is None }}) + main: Optional[Dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('main'), 'exclude': lambda f: f is None }}) + unsubscribe_url: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('unsubscribe_url'), 'exclude': lambda f: f is None }}) - brand: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('brand'), 'exclude': lambda f: f is None }}) - contact: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('contact'), 'exclude': lambda f: f is None }}) - main: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('main'), 'exclude': lambda f: f is None }}) - unsubscribe_url: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('unsubscribe_url'), 'exclude': lambda f: f is None }}) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/components/variableparameters.py b/template_variables/src/epilot/models/components/variableparameters.py new file mode 100644 index 000000000..62f563243 --- /dev/null +++ b/template_variables/src/epilot/models/components/variableparameters.py @@ -0,0 +1,45 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from __future__ import annotations +import dataclasses +from .externalcustomvariable import ExternalCustomVariable +from .templatetype import TemplateType +from dataclasses_json import Undefined, dataclass_json +from epilot import utils +from typing import List, Optional + + +@dataclasses.dataclass +class ContextData: + r"""If context data is avaialble, this data will be used for variable replace.""" + + + + +@dataclass_json(undefined=Undefined.EXCLUDE) +@dataclasses.dataclass +class VariableParameters: + UNSET='__SPEAKEASY_UNSET__' + template_type: TemplateType = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_type') }}) + brand_id: Optional[float] = dataclasses.field(default=UNSET, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('brand_id'), 'exclude': lambda f: f is VariableParameters.UNSET }}) + r"""Brand ID""" + context_data: Optional[ContextData] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('context_data'), 'exclude': lambda f: f is None }}) + r"""If context data is avaialble, this data will be used for variable replace.""" + custom_variables: Optional[List[ExternalCustomVariable]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('custom_variables'), 'exclude': lambda f: f is None }}) + r"""Custom variables with specified values form other services.""" + language: Optional[str] = dataclasses.field(default='de', metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('language'), 'exclude': lambda f: f is None }}) + r"""2-letter language code (ISO 639-1)""" + main_entity_id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('main_entity_id'), 'exclude': lambda f: f is None }}) + r"""The main entity ID. Use main entity in order to use the variable without schema slug prefix - or just pass directly to other object ID.""" + template_name: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_name'), 'exclude': lambda f: f is None }}) + r"""The name of email template""" + template_tags: Optional[List[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_tags'), 'exclude': lambda f: f is None }}) + r"""The tags of email template""" + user_id: Optional[str] = dataclasses.field(default=UNSET, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('user_id'), 'exclude': lambda f: f is VariableParameters.UNSET }}) + r"""User ID""" + user_org_id: Optional[str] = dataclasses.field(default=UNSET, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('user_org_id'), 'exclude': lambda f: f is VariableParameters.UNSET }}) + r"""Organization ID of the user""" + variables_version: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('variables_version'), 'exclude': lambda f: f is None }}) + r"""The version of the variables syntax supported. Default is 1.0""" + + diff --git a/template_variables/src/epilot/models/shared/variableresult.py b/template_variables/src/epilot/models/components/variableresult.py old mode 100755 new mode 100644 similarity index 70% rename from template_variables/src/epilot/models/shared/variableresult.py rename to template_variables/src/epilot/models/components/variableresult.py index d616a0d89..912b297bf --- a/template_variables/src/epilot/models/shared/variableresult.py +++ b/template_variables/src/epilot/models/components/variableresult.py @@ -7,22 +7,22 @@ from epilot import utils from typing import Optional -class VariableResultTypeEnum(str, Enum): - SIMPLE = "simple" - PARTIAL = "partial" +class VariableResultType(str, Enum): + SIMPLE = 'simple' + PARTIAL = 'partial' @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class VariableResult: - description: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('description'), 'exclude': lambda f: f is None }}) - r"""Variable description""" + r"""Variable description""" group: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('group'), 'exclude': lambda f: f is None }}) - r"""Variable group""" + r"""Variable group""" insert: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('insert'), 'exclude': lambda f: f is None }}) - r"""The value which is used to insert to template""" + r"""The value which is used to insert to template""" qrdata: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('qrdata'), 'exclude': lambda f: f is None }}) - r"""Payload for the QR data""" - type: Optional[VariableResultTypeEnum] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('type'), 'exclude': lambda f: f is None }}) - \ No newline at end of file + r"""Payload for the QR data""" + type: Optional[VariableResultType] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('type'), 'exclude': lambda f: f is None }}) + + diff --git a/template_variables/src/epilot/models/errors/__init__.py b/template_variables/src/epilot/models/errors/__init__.py new file mode 100644 index 000000000..88d091693 --- /dev/null +++ b/template_variables/src/epilot/models/errors/__init__.py @@ -0,0 +1,5 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +from .sdkerror import * + +__all__ = ["SDKError"] diff --git a/template_variables/src/epilot/models/errors/sdkerror.py b/template_variables/src/epilot/models/errors/sdkerror.py new file mode 100644 index 000000000..6bb02bbd6 --- /dev/null +++ b/template_variables/src/epilot/models/errors/sdkerror.py @@ -0,0 +1,24 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +import requests as requests_http + + +class SDKError(Exception): + """Represents an error returned by the API.""" + message: str + status_code: int + body: str + raw_response: requests_http.Response + + def __init__(self, message: str, status_code: int, body: str, raw_response: requests_http.Response): + self.message = message + self.status_code = status_code + self.body = body + self.raw_response = raw_response + + def __str__(self): + body = '' + if len(self.body) > 0: + body = f'\n{self.body}' + + return f'{self.message}: Status {self.status_code}{body}' diff --git a/template_variables/src/epilot/models/operations/__init__.py b/template_variables/src/epilot/models/operations/__init__.py old mode 100755 new mode 100644 index 7a3197048..1d694018f --- a/template_variables/src/epilot/models/operations/__init__.py +++ b/template_variables/src/epilot/models/operations/__init__.py @@ -2,7 +2,6 @@ from .createcustomvariable import * from .deletecustomvariable import * -from .generateqrcode import * from .getblueprinttableconfig import * from .getcategories import * from .getcustomvariable import * @@ -12,4 +11,4 @@ from .searchvariables import * from .updatecustomvariable import * -__all__ = ["CreateCustomVariableResponse","DeleteCustomVariableRequest","DeleteCustomVariableResponse","GenerateQRcodeRequest","GenerateQRcodeResponse","GetBluePrintTableConfigResponse","GetCategoriesLangEnum","GetCategoriesRequest","GetCategoriesResponse","GetCustomVariableRequest","GetCustomVariableResponse","GetCustomVariablesResponse","GetVariableContextRequestBody","GetVariableContextResponse","ReplaceTemplates200ApplicationJSON","ReplaceTemplatesRequestBody","ReplaceTemplatesResponse","SearchVariablesRequestBody","SearchVariablesRequestBodyLangEnum","SearchVariablesResponse","UpdateCustomVariableRequest","UpdateCustomVariableResponse"] +__all__ = ["CreateCustomVariableResponse","DeleteCustomVariableRequest","DeleteCustomVariableResponse","GetBluePrintTableConfigResponse","GetCategoriesRequest","GetCategoriesResponse","GetCustomVariableRequest","GetCustomVariableResponse","GetCustomVariablesResponse","GetVariableContextRequestBody","GetVariableContextResponse","ReplaceTemplatesRequestBody","ReplaceTemplatesResponse","ReplaceTemplatesResponseBody","SearchVariablesRequestBody","SearchVariablesResponse","UpdateCustomVariableRequest","UpdateCustomVariableResponse"] diff --git a/template_variables/src/epilot/models/operations/createcustomvariable.py b/template_variables/src/epilot/models/operations/createcustomvariable.py old mode 100755 new mode 100644 index 8adbc8008..b59b5f15d --- a/template_variables/src/epilot/models/operations/createcustomvariable.py +++ b/template_variables/src/epilot/models/operations/createcustomvariable.py @@ -2,14 +2,11 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from typing import Optional +from ...models.components import httpmetadata as components_httpmetadata @dataclasses.dataclass class CreateCustomVariableResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/operations/deletecustomvariable.py b/template_variables/src/epilot/models/operations/deletecustomvariable.py old mode 100755 new mode 100644 index 9915f50a3..48899392d --- a/template_variables/src/epilot/models/operations/deletecustomvariable.py +++ b/template_variables/src/epilot/models/operations/deletecustomvariable.py @@ -2,21 +2,19 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from typing import Optional +from ...models.components import httpmetadata as components_httpmetadata @dataclasses.dataclass class DeleteCustomVariableRequest: - id: str = dataclasses.field(metadata={'path_param': { 'field_name': 'id', 'style': 'simple', 'explode': False }}) - r"""Custom vairable ID""" + r"""Custom vairable ID""" + + @dataclasses.dataclass class DeleteCustomVariableResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/operations/generateqrcode.py b/template_variables/src/epilot/models/operations/generateqrcode.py deleted file mode 100755 index 8e360c885..000000000 --- a/template_variables/src/epilot/models/operations/generateqrcode.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -import requests as requests_http -from typing import Optional - - -@dataclasses.dataclass -class GenerateQRcodeRequest: - - qrdata: Optional[str] = dataclasses.field(default=None, metadata={'query_param': { 'field_name': 'qrdata', 'style': 'form', 'explode': True }}) - r"""Payload of the QR code""" - - -@dataclasses.dataclass -class GenerateQRcodeResponse: - - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/operations/getblueprinttableconfig.py b/template_variables/src/epilot/models/operations/getblueprinttableconfig.py old mode 100755 new mode 100644 index 25afa8caf..04c6176a2 --- a/template_variables/src/epilot/models/operations/getblueprinttableconfig.py +++ b/template_variables/src/epilot/models/operations/getblueprinttableconfig.py @@ -2,17 +2,15 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from ..shared import customvariable as shared_customvariable +from ...models.components import customvariable as components_customvariable +from ...models.components import httpmetadata as components_httpmetadata from typing import Optional @dataclasses.dataclass class GetBluePrintTableConfigResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() + custom_variable: Optional[components_customvariable.CustomVariable] = dataclasses.field(default=None) + r"""Success""" - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - custom_variable: Optional[shared_customvariable.CustomVariable] = dataclasses.field(default=None) - r"""Success""" - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/operations/getcategories.py b/template_variables/src/epilot/models/operations/getcategories.py old mode 100755 new mode 100644 index 2dd603e8e..3986c4efd --- a/template_variables/src/epilot/models/operations/getcategories.py +++ b/template_variables/src/epilot/models/operations/getcategories.py @@ -2,30 +2,22 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from ..shared import categoryresult as shared_categoryresult -from enum import Enum -from typing import Optional - -class GetCategoriesLangEnum(str, Enum): - r"""Language""" - EN = "en" - DE = "de" +from ...models.components import categoryresult as components_categoryresult +from ...models.components import httpmetadata as components_httpmetadata +from typing import List, Optional @dataclasses.dataclass class GetCategoriesRequest: + lang: Optional[str] = dataclasses.field(default='de', metadata={'query_param': { 'field_name': 'lang', 'style': 'form', 'explode': True }}) - lang: Optional[GetCategoriesLangEnum] = dataclasses.field(default=None, metadata={'query_param': { 'field_name': 'lang', 'style': 'form', 'explode': True }}) - r"""Language""" - + + @dataclasses.dataclass class GetCategoriesResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() + classes: Optional[List[components_categoryresult.CategoryResult]] = dataclasses.field(default=None) + r"""ok""" - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - category_results: Optional[list[shared_categoryresult.CategoryResult]] = dataclasses.field(default=None) - r"""ok""" - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/operations/getcustomvariable.py b/template_variables/src/epilot/models/operations/getcustomvariable.py old mode 100755 new mode 100644 index 7478f617a..17a8bedf2 --- a/template_variables/src/epilot/models/operations/getcustomvariable.py +++ b/template_variables/src/epilot/models/operations/getcustomvariable.py @@ -2,24 +2,23 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from ..shared import customvariable as shared_customvariable +from ...models.components import customvariable as components_customvariable +from ...models.components import httpmetadata as components_httpmetadata from typing import Optional @dataclasses.dataclass class GetCustomVariableRequest: - id: str = dataclasses.field(metadata={'path_param': { 'field_name': 'id', 'style': 'simple', 'explode': False }}) - r"""Custom vairable ID""" + r"""Custom vairable ID""" + + @dataclasses.dataclass class GetCustomVariableResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() + custom_variable: Optional[components_customvariable.CustomVariable] = dataclasses.field(default=None) + r"""Success""" - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - custom_variable: Optional[shared_customvariable.CustomVariable] = dataclasses.field(default=None) - r"""Success""" - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/operations/getcustomvariables.py b/template_variables/src/epilot/models/operations/getcustomvariables.py old mode 100755 new mode 100644 index e3c0c1017..fb01c0180 --- a/template_variables/src/epilot/models/operations/getcustomvariables.py +++ b/template_variables/src/epilot/models/operations/getcustomvariables.py @@ -2,17 +2,15 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from ..shared import customvariable as shared_customvariable -from typing import Optional +from ...models.components import customvariable as components_customvariable +from ...models.components import httpmetadata as components_httpmetadata +from typing import List, Optional @dataclasses.dataclass class GetCustomVariablesResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() + classes: Optional[List[components_customvariable.CustomVariable]] = dataclasses.field(default=None) + r"""Success""" - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - custom_variables: Optional[list[shared_customvariable.CustomVariable]] = dataclasses.field(default=None) - r"""Success""" - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/operations/getvariablecontext.py b/template_variables/src/epilot/models/operations/getvariablecontext.py old mode 100755 new mode 100644 index 2583cc584..359cb2f31 --- a/template_variables/src/epilot/models/operations/getvariablecontext.py +++ b/template_variables/src/epilot/models/operations/getvariablecontext.py @@ -2,9 +2,9 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from ..shared import variablecontext as shared_variablecontext -from ..shared import variableparameters as shared_variableparameters +from ...models.components import httpmetadata as components_httpmetadata +from ...models.components import variablecontext as components_variablecontext +from ...models.components import variableparameters as components_variableparameters from dataclasses_json import Undefined, dataclass_json from epilot import utils from typing import Optional @@ -13,16 +13,15 @@ @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class GetVariableContextRequestBody: + parameters: Optional[components_variableparameters.VariableParameters] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('parameters'), 'exclude': lambda f: f is None }}) - parameters: Optional[shared_variableparameters.VariableParameters] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('parameters'), 'exclude': lambda f: f is None }}) - + + @dataclasses.dataclass class GetVariableContextResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() + variable_context: Optional[components_variablecontext.VariableContext] = dataclasses.field(default=None) + r"""ok""" - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - variable_context: Optional[shared_variablecontext.VariableContext] = dataclasses.field(default=None) - r"""ok""" - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/operations/replacetemplates.py b/template_variables/src/epilot/models/operations/replacetemplates.py old mode 100755 new mode 100644 index c8a02e00c..f6afb7c1e --- a/template_variables/src/epilot/models/operations/replacetemplates.py +++ b/template_variables/src/epilot/models/operations/replacetemplates.py @@ -2,35 +2,35 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from ..shared import variableparameters as shared_variableparameters +from ...models.components import httpmetadata as components_httpmetadata +from ...models.components import variableparameters as components_variableparameters from dataclasses_json import Undefined, dataclass_json from epilot import utils -from typing import Optional +from typing import List, Optional @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class ReplaceTemplatesRequestBody: + inputs: Optional[List[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('inputs'), 'exclude': lambda f: f is None }}) + parameters: Optional[components_variableparameters.VariableParameters] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('parameters'), 'exclude': lambda f: f is None }}) - inputs: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('inputs'), 'exclude': lambda f: f is None }}) - parameters: Optional[shared_variableparameters.VariableParameters] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('parameters'), 'exclude': lambda f: f is None }}) - + + @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass -class ReplaceTemplates200ApplicationJSON: +class ReplaceTemplatesResponseBody: r"""ok""" - - outputs: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('outputs'), 'exclude': lambda f: f is None }}) + outputs: Optional[List[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('outputs'), 'exclude': lambda f: f is None }}) + + @dataclasses.dataclass class ReplaceTemplatesResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() + object: Optional[ReplaceTemplatesResponseBody] = dataclasses.field(default=None) + r"""ok""" - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - replace_templates_200_application_json_object: Optional[ReplaceTemplates200ApplicationJSON] = dataclasses.field(default=None) - r"""ok""" - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/operations/searchvariables.py b/template_variables/src/epilot/models/operations/searchvariables.py old mode 100755 new mode 100644 index 26ceb11e9..ff01aaec8 --- a/template_variables/src/epilot/models/operations/searchvariables.py +++ b/template_variables/src/epilot/models/operations/searchvariables.py @@ -2,38 +2,33 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from ..shared import templatetype_enum as shared_templatetype_enum -from ..shared import variableresult as shared_variableresult +from ...models.components import httpmetadata as components_httpmetadata +from ...models.components import templatetype as components_templatetype +from ...models.components import variableresult as components_variableresult from dataclasses_json import Undefined, dataclass_json -from enum import Enum from epilot import utils -from typing import Optional - -class SearchVariablesRequestBodyLangEnum(str, Enum): - EN = "en" - DE = "de" +from typing import List, Optional @dataclass_json(undefined=Undefined.EXCLUDE) @dataclasses.dataclass class SearchVariablesRequestBody: - query: str = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('query') }}) - r"""Search string""" - template_type: shared_templatetype_enum.TemplateTypeEnum = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_type') }}) - entity_schemas: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('entity_schemas'), 'exclude': lambda f: f is None }}) - from_: Optional[int] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('from'), 'exclude': lambda f: f is None }}) - lang: Optional[SearchVariablesRequestBodyLangEnum] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('lang'), 'exclude': lambda f: f is None }}) - size: Optional[int] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('size'), 'exclude': lambda f: f is None }}) + r"""Search string""" + template_type: components_templatetype.TemplateType = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_type') }}) + entity_schemas: Optional[List[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('entity_schemas'), 'exclude': lambda f: f is None }}) + from_: Optional[int] = dataclasses.field(default=0, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('from'), 'exclude': lambda f: f is None }}) + lang: Optional[str] = dataclasses.field(default='de', metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('lang'), 'exclude': lambda f: f is None }}) + r"""2-letter language code (ISO 639-1)""" + size: Optional[int] = dataclasses.field(default=25, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('size'), 'exclude': lambda f: f is None }}) + + @dataclasses.dataclass class SearchVariablesResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() + classes: Optional[List[components_variableresult.VariableResult]] = dataclasses.field(default=None) + r"""ok""" - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - variable_results: Optional[list[shared_variableresult.VariableResult]] = dataclasses.field(default=None) - r"""ok""" - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/operations/updatecustomvariable.py b/template_variables/src/epilot/models/operations/updatecustomvariable.py old mode 100755 new mode 100644 index ddc0124e0..c36a2345f --- a/template_variables/src/epilot/models/operations/updatecustomvariable.py +++ b/template_variables/src/epilot/models/operations/updatecustomvariable.py @@ -2,23 +2,22 @@ from __future__ import annotations import dataclasses -import requests as requests_http -from ..shared import customvariable as shared_customvariable +from ...models.components import customvariable as components_customvariable +from ...models.components import httpmetadata as components_httpmetadata from typing import Optional @dataclasses.dataclass class UpdateCustomVariableRequest: - id: str = dataclasses.field(metadata={'path_param': { 'field_name': 'id', 'style': 'simple', 'explode': False }}) - r"""Custom variable ID""" - custom_variable: Optional[shared_customvariable.CustomVariable] = dataclasses.field(default=None, metadata={'request': { 'media_type': 'application/json' }}) + r"""Custom variable ID""" + custom_variable: Optional[components_customvariable.CustomVariable] = dataclasses.field(default=None, metadata={'request': { 'media_type': 'application/json' }}) + + @dataclasses.dataclass class UpdateCustomVariableResponse: + http_meta: components_httpmetadata.HTTPMetadata = dataclasses.field() - content_type: str = dataclasses.field() - status_code: int = dataclasses.field() - raw_response: Optional[requests_http.Response] = dataclasses.field(default=None) - \ No newline at end of file + diff --git a/template_variables/src/epilot/models/shared/security.py b/template_variables/src/epilot/models/shared/security.py deleted file mode 100755 index cca0d01c8..000000000 --- a/template_variables/src/epilot/models/shared/security.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses - - -@dataclasses.dataclass -class Security: - - epilot_auth: str = dataclasses.field(metadata={'security': { 'scheme': True, 'type': 'http', 'sub_type': 'bearer', 'field_name': 'Authorization' }}) - \ No newline at end of file diff --git a/template_variables/src/epilot/models/shared/variableparameters.py b/template_variables/src/epilot/models/shared/variableparameters.py deleted file mode 100755 index 46b36be3f..000000000 --- a/template_variables/src/epilot/models/shared/variableparameters.py +++ /dev/null @@ -1,37 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" - -from __future__ import annotations -import dataclasses -from ..shared import externalcustomvariable as shared_externalcustomvariable -from ..shared import templatetype_enum as shared_templatetype_enum -from dataclasses_json import Undefined, dataclass_json -from enum import Enum -from epilot import utils -from typing import Any, Optional - -class VariableParametersLanguageEnum(str, Enum): - EN = "en" - DE = "de" - - -@dataclass_json(undefined=Undefined.EXCLUDE) -@dataclasses.dataclass -class VariableParameters: - - template_type: shared_templatetype_enum.TemplateTypeEnum = dataclasses.field(metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_type') }}) - brand_id: Optional[float] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('brand_id'), 'exclude': lambda f: f is None }}) - r"""Brand ID""" - context_data: Optional[dict[str, Any]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('context_data'), 'exclude': lambda f: f is None }}) - r"""If context data is avaialble, this data will be used for variable replace.""" - custom_variables: Optional[list[shared_externalcustomvariable.ExternalCustomVariable]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('custom_variables'), 'exclude': lambda f: f is None }}) - r"""Custom variables with specified values form other services.""" - language: Optional[VariableParametersLanguageEnum] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('language'), 'exclude': lambda f: f is None }}) - main_entity_id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('main_entity_id'), 'exclude': lambda f: f is None }}) - r"""The main entity ID. Use main entity in order to use the variable without schema slug prefix - or just pass directly to other object ID.""" - template_name: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_name'), 'exclude': lambda f: f is None }}) - r"""The name of email template""" - template_tags: Optional[list[str]] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('template_tags'), 'exclude': lambda f: f is None }}) - r"""The tags of email template""" - user_id: Optional[str] = dataclasses.field(default=None, metadata={'dataclasses_json': { 'letter_case': utils.get_field_name('user_id'), 'exclude': lambda f: f is None }}) - r"""User ID""" - \ No newline at end of file diff --git a/template_variables/src/epilot/sdk.py b/template_variables/src/epilot/sdk.py old mode 100755 new mode 100644 index 53ea97cd1..decd78754 --- a/template_variables/src/epilot/sdk.py +++ b/template_variables/src/epilot/sdk.py @@ -1,80 +1,75 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" import requests as requests_http -from . import utils from .custom_variables import CustomVariables +from .sdkconfiguration import SDKConfiguration +from .utils.retries import RetryConfig from .variables import Variables -from epilot.models import shared - -SERVERS = [ - "https://template-variables-api.sls.epilot.io", -] -"""Contains the list of servers available to the SDK""" +from epilot import utils +from epilot._hooks import SDKHooks +from epilot.models import components +from typing import Callable, Dict, Optional, Union class Epilot: - r"""API to provide variables for email and document templates.""" + r"""Template Variables API: API to provide variables for email and document templates.""" custom_variables: CustomVariables variables: Variables r"""Variables""" - _client: requests_http.Session - _security_client: requests_http.Session - _server_url: str = SERVERS[0] - _language: str = "python" - _sdk_version: str = "1.2.2" - _gen_version: str = "2.16.5" + sdk_configuration: SDKConfiguration def __init__(self, - security: shared.Security = None, - server_url: str = None, - url_params: dict[str, str] = None, - client: requests_http.Session = None + security: Union[components.Security,Callable[[], components.Security]] = None, + server_idx: Optional[int] = None, + server_url: Optional[str] = None, + url_params: Optional[Dict[str, str]] = None, + client: Optional[requests_http.Session] = None, + retry_config: Optional[RetryConfig] = None ) -> None: """Instantiates the SDK configuring it with the provided parameters. - + :param security: The security details required for authentication - :type security: shared.Security + :type security: Union[components.Security,Callable[[], components.Security]] + :param server_idx: The index of the server to use for all operations + :type server_idx: int :param server_url: The server URL to use for all operations :type server_url: str :param url_params: Parameters to optionally template the server URL with - :type url_params: dict[str, str] + :type url_params: Dict[str, str] :param client: The requests.Session HTTP client to use for all operations - :type client: requests_http.Session + :type client: requests_http.Session + :param retry_config: The utils.RetryConfig to use globally + :type retry_config: RetryConfig """ - self._client = requests_http.Session() - - + if client is None: + client = requests_http.Session() + if server_url is not None: if url_params is not None: - self._server_url = utils.template_url(server_url, url_params) - else: - self._server_url = server_url + server_url = utils.template_url(server_url, url_params) + + + self.sdk_configuration = SDKConfiguration( + client, + security, + server_url, + server_idx, + retry_config=retry_config + ) + + hooks = SDKHooks() - if client is not None: - self._client = client - - self._security_client = utils.configure_security_client(self._client, security) - + current_server_url, *_ = self.sdk_configuration.get_server_details() + server_url, self.sdk_configuration.client = hooks.sdk_init(current_server_url, self.sdk_configuration.client) + if current_server_url != server_url: + self.sdk_configuration.server_url = server_url + + # pylint: disable=protected-access + self.sdk_configuration.__dict__['_hooks'] = hooks self._init_sdks() - + + def _init_sdks(self): - self.custom_variables = CustomVariables( - self._client, - self._security_client, - self._server_url, - self._language, - self._sdk_version, - self._gen_version - ) - - self.variables = Variables( - self._client, - self._security_client, - self._server_url, - self._language, - self._sdk_version, - self._gen_version - ) - - \ No newline at end of file + self.custom_variables = CustomVariables(self.sdk_configuration) + self.variables = Variables(self.sdk_configuration) diff --git a/template_variables/src/epilot/sdkconfiguration.py b/template_variables/src/epilot/sdkconfiguration.py new file mode 100644 index 000000000..dd92875c9 --- /dev/null +++ b/template_variables/src/epilot/sdkconfiguration.py @@ -0,0 +1,44 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + + +import requests as requests_http +from ._hooks import SDKHooks +from .utils import utils +from .utils.retries import RetryConfig +from dataclasses import dataclass +from epilot.models import components +from typing import Callable, Dict, Optional, Tuple, Union + + +SERVERS = [ + 'https://template-variables-api.sls.epilot.io', +] +"""Contains the list of servers available to the SDK""" + +@dataclass +class SDKConfiguration: + client: requests_http.Session + security: Union[components.Security,Callable[[], components.Security]] = None + server_url: Optional[str] = '' + server_idx: Optional[int] = 0 + language: str = 'python' + openapi_doc_version: str = '1.0.0' + sdk_version: str = '1.3.0' + gen_version: str = '2.306.0' + user_agent: str = 'speakeasy-sdk/python 1.3.0 2.306.0 1.0.0 epilot-template-variables' + retry_config: Optional[RetryConfig] = None + + def __post_init__(self): + self._hooks = SDKHooks() + + def get_server_details(self) -> Tuple[str, Dict[str, str]]: + if self.server_url is not None and self.server_url != '': + return utils.remove_suffix(self.server_url, '/'), {} + if self.server_idx is None: + self.server_idx = 0 + + return SERVERS[self.server_idx], {} + + + def get_hooks(self) -> SDKHooks: + return self._hooks diff --git a/template_variables/src/epilot/utils/__init__.py b/template_variables/src/epilot/utils/__init__.py old mode 100755 new mode 100644 diff --git a/template_variables/src/epilot/utils/retries.py b/template_variables/src/epilot/utils/retries.py old mode 100755 new mode 100644 index c6251d948..c40fc413c --- a/template_variables/src/epilot/utils/retries.py +++ b/template_variables/src/epilot/utils/retries.py @@ -2,6 +2,7 @@ import random import time +from typing import List import requests @@ -24,16 +25,17 @@ class RetryConfig: backoff: BackoffStrategy retry_connection_errors: bool - def __init__(self, strategy: str, retry_connection_errors: bool): + def __init__(self, strategy: str, backoff: BackoffStrategy, retry_connection_errors: bool): self.strategy = strategy + self.backoff = backoff self.retry_connection_errors = retry_connection_errors class Retries: config: RetryConfig - status_codes: list[str] + status_codes: List[str] - def __init__(self, config: RetryConfig, status_codes: list[str]): + def __init__(self, config: RetryConfig, status_codes: List[str]): self.config = config self.status_codes = status_codes @@ -73,12 +75,12 @@ def do_request(): if res.status_code == parsed_code: raise TemporaryError(res) except requests.exceptions.ConnectionError as exception: - if not retries.config.config.retry_connection_errors: + if retries.config.retry_connection_errors: raise raise PermanentError(exception) from exception except requests.exceptions.Timeout as exception: - if not retries.config.config.retry_connection_errors: + if retries.config.retry_connection_errors: raise raise PermanentError(exception) from exception @@ -112,7 +114,6 @@ def retry_with_backoff(func, initial_interval=500, max_interval=60000, exponent= raise sleep = ((initial_interval/1000) * exponent**retries + random.uniform(0, 1)) - if sleep > max_interval/1000: - sleep = max_interval/1000 + sleep = min(sleep, max_interval / 1000) time.sleep(sleep) retries += 1 diff --git a/template_variables/src/epilot/utils/utils.py b/template_variables/src/epilot/utils/utils.py old mode 100755 new mode 100644 index 9d4fba324..b238ff2f1 --- a/template_variables/src/epilot/utils/utils.py +++ b/template_variables/src/epilot/utils/utils.py @@ -3,37 +3,35 @@ import base64 import json import re -from dataclasses import Field, dataclass, fields, is_dataclass, make_dataclass +import sys +from dataclasses import Field, fields, is_dataclass, make_dataclass from datetime import date, datetime +from decimal import Decimal from email.message import Message from enum import Enum -from typing import Any, Callable, Optional, Tuple, Union, get_args, get_origin +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Tuple, + Union, + get_args, + get_origin, +) from xmlrpc.client import boolean - +from typing_inspect import is_optional_type import dateutil.parser -import requests from dataclasses_json import DataClassJsonMixin -class SecurityClient: - client: requests.Session - query_params: dict[str, str] = {} - - def __init__(self, client: requests.Session): - self.client = client - - def request(self, method, url, **kwargs): - params = kwargs.get('params', {}) - kwargs["params"] = self.query_params | params - - return self.client.request(method, url, **kwargs) - - -def configure_security_client(client: requests.Session, security: dataclass): - client = SecurityClient(client) +def get_security(security: Any) -> Tuple[Dict[str, str], Dict[str, str]]: + headers: Dict[str, str] = {} + query_params: Dict[str, str] = {} if security is None: - return client + return headers, query_params sec_fields: Tuple[Field, ...] = fields(security) for sec_field in sec_fields: @@ -41,267 +39,380 @@ def configure_security_client(client: requests.Session, security: dataclass): if value is None: continue - metadata = sec_field.metadata.get('security') + metadata = sec_field.metadata.get("security") if metadata is None: continue - if metadata.get('option'): - _parse_security_option(client, value) - return client - if metadata.get('scheme'): + if metadata.get("option"): + _parse_security_option(headers, query_params, value) + return headers, query_params + if metadata.get("scheme"): # Special case for basic auth which could be a flattened struct if metadata.get("sub_type") == "basic" and not is_dataclass(value): - _parse_security_scheme(client, metadata, security) + _parse_security_scheme(headers, query_params, metadata, security) else: - _parse_security_scheme(client, metadata, value) + _parse_security_scheme(headers, query_params, metadata, value) - return client + return headers, query_params -def _parse_security_option(client: SecurityClient, option: dataclass): +def _parse_security_option( + headers: Dict[str, str], query_params: Dict[str, str], option: Any +): opt_fields: Tuple[Field, ...] = fields(option) for opt_field in opt_fields: - metadata = opt_field.metadata.get('security') - if metadata is None or metadata.get('scheme') is None: + metadata = opt_field.metadata.get("security") + if metadata is None or metadata.get("scheme") is None: continue _parse_security_scheme( - client, metadata, getattr(option, opt_field.name)) + headers, query_params, metadata, getattr(option, opt_field.name) + ) -def _parse_security_scheme(client: SecurityClient, scheme_metadata: dict, scheme: any): - scheme_type = scheme_metadata.get('type') - sub_type = scheme_metadata.get('sub_type') +def _parse_security_scheme( + headers: Dict[str, str], + query_params: Dict[str, str], + scheme_metadata: Dict, + scheme: Any, +): + scheme_type = scheme_metadata.get("type") + sub_type = scheme_metadata.get("sub_type") if is_dataclass(scheme): - if scheme_type == 'http' and sub_type == 'basic': - _parse_basic_auth_scheme(client, scheme) + if scheme_type == "http" and sub_type == "basic": + _parse_basic_auth_scheme(headers, scheme) return scheme_fields: Tuple[Field, ...] = fields(scheme) for scheme_field in scheme_fields: - metadata = scheme_field.metadata.get('security') - if metadata is None or metadata.get('field_name') is None: + metadata = scheme_field.metadata.get("security") + if metadata is None or metadata.get("field_name") is None: continue value = getattr(scheme, scheme_field.name) _parse_security_scheme_value( - client, scheme_metadata, metadata, value) + headers, query_params, scheme_metadata, metadata, value + ) else: _parse_security_scheme_value( - client, scheme_metadata, scheme_metadata, scheme) + headers, query_params, scheme_metadata, scheme_metadata, scheme + ) -def _parse_security_scheme_value(client: SecurityClient, scheme_metadata: dict, security_metadata: dict, value: any): - scheme_type = scheme_metadata.get('type') - sub_type = scheme_metadata.get('sub_type') +def _parse_security_scheme_value( + headers: Dict[str, str], + query_params: Dict[str, str], + scheme_metadata: Dict, + security_metadata: Dict, + value: Any, +): + scheme_type = scheme_metadata.get("type") + sub_type = scheme_metadata.get("sub_type") - header_name = security_metadata.get('field_name') + header_name = str(security_metadata.get("field_name")) if scheme_type == "apiKey": - if sub_type == 'header': - client.client.headers[header_name] = value - elif sub_type == 'query': - client.query_params[header_name] = value - elif sub_type == 'cookie': - client.client.cookies[header_name] = value + if sub_type == "header": + headers[header_name] = value + elif sub_type == "query": + query_params[header_name] = value else: - raise Exception('not supported') + raise Exception("not supported") elif scheme_type == "openIdConnect": - client.client.headers[header_name] = value - elif scheme_type == 'oauth2': - client.client.headers[header_name] = value - elif scheme_type == 'http': - if sub_type == 'bearer': - client.client.headers[header_name] = value + headers[header_name] = _apply_bearer(value) + elif scheme_type == "oauth2": + if sub_type != "client_credentials": + headers[header_name] = _apply_bearer(value) + elif scheme_type == "http": + if sub_type == "bearer": + headers[header_name] = _apply_bearer(value) else: - raise Exception('not supported') + raise Exception("not supported") else: - raise Exception('not supported') + raise Exception("not supported") + + +def _apply_bearer(token: str) -> str: + return token.lower().startswith("bearer ") and token or f"Bearer {token}" -def _parse_basic_auth_scheme(client: SecurityClient, scheme: dataclass): +def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any): username = "" password = "" scheme_fields: Tuple[Field, ...] = fields(scheme) for scheme_field in scheme_fields: - metadata = scheme_field.metadata.get('security') - if metadata is None or metadata.get('field_name') is None: + metadata = scheme_field.metadata.get("security") + if metadata is None or metadata.get("field_name") is None: continue - field_name = metadata.get('field_name') + field_name = metadata.get("field_name") value = getattr(scheme, scheme_field.name) - if field_name == 'username': + if field_name == "username": username = value - if field_name == 'password': + if field_name == "password": password = value - data = f'{username}:{password}'.encode() - client.client.headers['Authorization'] = f'Basic {base64.b64encode(data).decode()}' + data = f"{username}:{password}".encode() + headers["Authorization"] = f"Basic {base64.b64encode(data).decode()}" -def generate_url(clazz: type, server_url: str, path: str, path_params: dataclass, gbls: dict[str, dict[str, dict[str, Any]]] = None) -> str: - path_param_fields: Tuple[Field, ...] = fields(clazz) +def generate_url( + server_url: str, + path: str, + path_params: Any, + gbls: Optional[Any] = None, +) -> str: + path_param_values: Dict[str, str] = {} + + globals_already_populated = _populate_path_params( + path_params, gbls, path_param_values, [] + ) + if gbls is not None: + _populate_path_params(gbls, None, path_param_values, globals_already_populated) + + for key, value in path_param_values.items(): + path = path.replace("{" + key + "}", value, 1) + + return remove_suffix(server_url, "/") + path + + +def _populate_path_params( + path_params: Any, + gbls: Any, + path_param_values: Dict[str, str], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] + + path_param_fields: Tuple[Field, ...] = fields(path_params) for field in path_param_fields: - request_metadata = field.metadata.get('request') - if request_metadata is not None: + if field.name in skip_fields: continue - param_metadata = field.metadata.get('path_param') + param_metadata = field.metadata.get("path_param") if param_metadata is None: continue - if param_metadata.get('style', 'simple') == 'simple': - param = getattr( - path_params, field.name) if path_params is not None else None - param = _populate_from_globals( - field.name, param, 'pathParam', gbls) - - if param is None: - continue - - if isinstance(param, list): - pp_vals: list[str] = [] - for pp_val in param: - if pp_val is None: - continue - pp_vals.append(_val_to_string(pp_val)) - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', ",".join(pp_vals), 1) - elif isinstance(param, dict): - pp_vals: list[str] = [] - for pp_key in param: - if param[pp_key] is None: - continue - if param_metadata.get('explode'): - pp_vals.append( - f"{pp_key}={_val_to_string(param[pp_key])}") - else: - pp_vals.append( - f"{pp_key},{_val_to_string(param[pp_key])}") - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', ",".join(pp_vals), 1) - elif not isinstance(param, (str, int, float, complex, bool)): - pp_vals: list[str] = [] - param_fields: Tuple[Field, ...] = fields(param) - for param_field in param_fields: - param_value_metadata = param_field.metadata.get( - 'path_param') - if not param_value_metadata: - continue + param = getattr(path_params, field.name) if path_params is not None else None + param, global_found = _populate_from_globals( + field.name, param, "path_param", gbls + ) + if global_found: + globals_already_populated.append(field.name) - parm_name = param_value_metadata.get( - 'field_name', field.name) + if param is None: + continue - param_field_val = getattr(param, param_field.name) - if param_field_val is None: - continue - if param_metadata.get('explode'): - pp_vals.append( - f"{parm_name}={_val_to_string(param_field_val)}") - else: - pp_vals.append( - f"{parm_name},{_val_to_string(param_field_val)}") - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', ",".join(pp_vals), 1) - else: - path = path.replace( - '{' + param_metadata.get('field_name', field.name) + '}', _val_to_string(param), 1) + f_name = param_metadata.get("field_name", field.name) + serialization = param_metadata.get("serialization", "") + if serialization != "": + serialized_params = _get_serialized_params( + param_metadata, field.type, f_name, param + ) + for key, value in serialized_params.items(): + path_param_values[key] = value + else: + if param_metadata.get("style", "simple") == "simple": + if isinstance(param, List): + pp_vals: List[str] = [] + for pp_val in param: + if pp_val is None: + continue + pp_vals.append(_val_to_string(pp_val)) + path_param_values[param_metadata.get("field_name", field.name)] = ( + ",".join(pp_vals) + ) + elif isinstance(param, Dict): + pp_vals: List[str] = [] + for pp_key in param: + if param[pp_key] is None: + continue + if param_metadata.get("explode"): + pp_vals.append(f"{pp_key}={_val_to_string(param[pp_key])}") + else: + pp_vals.append(f"{pp_key},{_val_to_string(param[pp_key])}") + path_param_values[param_metadata.get("field_name", field.name)] = ( + ",".join(pp_vals) + ) + elif not isinstance(param, (str, int, float, complex, bool, Decimal)): + pp_vals: List[str] = [] + param_fields: Tuple[Field, ...] = fields(param) + for param_field in param_fields: + param_value_metadata = param_field.metadata.get("path_param") + if not param_value_metadata: + continue + + param_name = param_value_metadata.get("field_name", field.name) + + param_field_val = getattr(param, param_field.name) + if param_field_val is None: + continue + if param_metadata.get("explode"): + pp_vals.append( + f"{param_name}={_val_to_string(param_field_val)}" + ) + else: + pp_vals.append( + f"{param_name},{_val_to_string(param_field_val)}" + ) + path_param_values[param_metadata.get("field_name", field.name)] = ( + ",".join(pp_vals) + ) + else: + path_param_values[param_metadata.get("field_name", field.name)] = ( + _val_to_string(param) + ) - return server_url.removesuffix("/") + path + return globals_already_populated def is_optional(field): return get_origin(field) is Union and type(None) in get_args(field) -def template_url(url_with_params: str, params: dict[str, str]) -> str: +def template_url(url_with_params: str, params: Dict[str, str]) -> str: for key, value in params.items(): - url_with_params = url_with_params.replace( - '{' + key + '}', value) + url_with_params = url_with_params.replace("{" + key + "}", value) return url_with_params -def get_query_params(clazz: type, query_params: dataclass, gbls: dict[str, dict[str, dict[str, Any]]] = None) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} +def get_query_params( + query_params: Any, + gbls: Optional[Any] = None, +) -> Dict[str, List[str]]: + params: Dict[str, List[str]] = {} + + globals_already_populated = _populate_query_params(query_params, gbls, params, []) + if gbls is not None: + _populate_query_params(gbls, None, params, globals_already_populated) + + return params + + +def _populate_query_params( + query_params: Any, + gbls: Any, + query_param_values: Dict[str, List[str]], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] - param_fields: Tuple[Field, ...] = fields(clazz) + param_fields: Tuple[Field, ...] = fields(query_params) for field in param_fields: - request_metadata = field.metadata.get('request') - if request_metadata is not None: + if field.name in skip_fields: continue - metadata = field.metadata.get('query_param') + metadata = field.metadata.get("query_param") if not metadata: continue param_name = field.name - value = getattr( - query_params, param_name) if query_params is not None else None + value = getattr(query_params, param_name) if query_params is not None else None - value = _populate_from_globals(param_name, value, 'queryParam', gbls) + value, global_found = _populate_from_globals( + param_name, value, "query_param", gbls + ) + if global_found: + globals_already_populated.append(param_name) f_name = metadata.get("field_name") - serialization = metadata.get('serialization', '') - if serialization != '': - params = params | _get_serialized_query_params( - metadata, f_name, value) + serialization = metadata.get("serialization", "") + if serialization != "": + serialized_parms = _get_serialized_params( + metadata, field.type, f_name, value + ) + for key, value in serialized_parms.items(): + if key in query_param_values: + query_param_values[key].extend(value) + else: + query_param_values[key] = [value] else: - style = metadata.get('style', 'form') - if style == 'deepObject': - params = params | _get_deep_object_query_params( - metadata, f_name, value) - elif style == 'form': - params = params | _get_form_query_params( - metadata, f_name, value) + style = metadata.get("style", "form") + if style == "deepObject": + _populate_deep_object_query_params( + metadata, f_name, value, query_param_values + ) + elif style == "form": + _populate_delimited_query_params( + metadata, f_name, value, ",", query_param_values + ) + elif style == "pipeDelimited": + _populate_delimited_query_params( + metadata, f_name, value, "|", query_param_values + ) else: - raise Exception('not yet implemented') - return params + raise Exception("not yet implemented") + + return globals_already_populated + +def get_headers(headers_params: Any, gbls: Optional[Any] = None) -> Dict[str, str]: + headers: Dict[str, str] = {} -def get_headers(headers_params: dataclass) -> dict[str, str]: - if headers_params is None: - return {} + globals_already_populated = [] + if headers_params is not None: + globals_already_populated = _populate_headers(headers_params, gbls, headers, []) + if gbls is not None: + _populate_headers(gbls, None, headers, globals_already_populated) + + return headers - headers: dict[str, str] = {} + +def _populate_headers( + headers_params: Any, + gbls: Any, + header_values: Dict[str, str], + skip_fields: List[str], +) -> List[str]: + globals_already_populated: List[str] = [] param_fields: Tuple[Field, ...] = fields(headers_params) for field in param_fields: - metadata = field.metadata.get('header') + if field.name in skip_fields: + continue + + metadata = field.metadata.get("header") if not metadata: continue - value = _serialize_header(metadata.get( - 'explode', False), getattr(headers_params, field.name)) + value, global_found = _populate_from_globals( + field.name, getattr(headers_params, field.name), "header", gbls + ) + if global_found: + globals_already_populated.append(field.name) + value = _serialize_header(metadata.get("explode", False), value) - if value != '': - headers[metadata.get('field_name', field.name)] = value + if value != "": + header_values[metadata.get("field_name", field.name)] = value - return headers + return globals_already_populated -def _get_serialized_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} +def _get_serialized_params( + metadata: Dict, field_type: type, field_name: str, obj: Any +) -> Dict[str, str]: + params: Dict[str, str] = {} - serialization = metadata.get('serialization', '') - if serialization == 'json': - params[metadata.get("field_name", field_name)] = marshal_json(obj) + serialization = metadata.get("serialization", "") + if serialization == "json": + params[metadata.get("field_name", field_name)] = marshal_json(obj, field_type) return params -def _get_deep_object_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - +def _populate_deep_object_query_params( + metadata: Dict, field_name: str, obj: Any, params: Dict[str, List[str]] +): if obj is None: - return params + return if is_dataclass(obj): obj_fields: Tuple[Field, ...] = fields(obj) for obj_field in obj_fields: - obj_param_metadata = obj_field.metadata.get('query_param') + obj_param_metadata = obj_field.metadata.get("query_param") if not obj_param_metadata: continue @@ -309,45 +420,55 @@ def _get_deep_object_query_params(metadata: dict, field_name: str, obj: any) -> if obj_val is None: continue - if isinstance(obj_val, list): + if isinstance(obj_val, List): for val in obj_val: if val is None: continue - if params.get(f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]') is None: - params[f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]'] = [ - ] + if ( + params.get( + f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]' + ) + is None + ): + params[ + f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]' + ] = [] params[ - f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]'].append(_val_to_string(val)) + f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]' + ].append(_val_to_string(val)) else: params[ - f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]'] = [ - _val_to_string(obj_val)] - elif isinstance(obj, dict): + f'{metadata.get("field_name", field_name)}[{obj_param_metadata.get("field_name", obj_field.name)}]' + ] = [_val_to_string(obj_val)] + elif isinstance(obj, Dict): for key, value in obj.items(): if value is None: continue - if isinstance(value, list): + if isinstance(value, List): for val in value: if val is None: continue - if params.get(f'{metadata.get("field_name", field_name)}[{key}]') is None: - params[f'{metadata.get("field_name", field_name)}[{key}]'] = [ - ] + if ( + params.get(f'{metadata.get("field_name", field_name)}[{key}]') + is None + ): + params[f'{metadata.get("field_name", field_name)}[{key}]'] = [] - params[ - f'{metadata.get("field_name", field_name)}[{key}]'].append(_val_to_string(val)) + params[f'{metadata.get("field_name", field_name)}[{key}]'].append( + _val_to_string(val) + ) else: params[f'{metadata.get("field_name", field_name)}[{key}]'] = [ - _val_to_string(value)] - return params + _val_to_string(value) + ] def _get_query_param_field_name(obj_field: Field) -> str: - obj_param_metadata = obj_field.metadata.get('query_param') + obj_param_metadata = obj_field.metadata.get("query_param") if not obj_param_metadata: return "" @@ -355,48 +476,87 @@ def _get_query_param_field_name(obj_field: Field) -> str: return obj_param_metadata.get("field_name", obj_field.name) -def _get_form_query_params(metadata: dict, field_name: str, obj: any) -> dict[str, list[str]]: - return _populate_form(field_name, metadata.get("explode", True), obj, _get_query_param_field_name) +def _populate_delimited_query_params( + metadata: Dict, + field_name: str, + obj: Any, + delimiter: str, + query_param_values: Dict[str, List[str]], +): + _populate_form( + field_name, + metadata.get("explode", True), + obj, + _get_query_param_field_name, + delimiter, + query_param_values, + ) SERIALIZATION_METHOD_TO_CONTENT_TYPE = { - 'json': 'application/json', - 'form': 'application/x-www-form-urlencoded', - 'multipart': 'multipart/form-data', - 'raw': 'application/octet-stream', - 'string': 'text/plain', + "json": "application/json", + "form": "application/x-www-form-urlencoded", + "multipart": "multipart/form-data", + "raw": "application/octet-stream", + "string": "text/plain", } -def serialize_request_body(request: dataclass, request_field_name: str, serialization_method: str) -> Tuple[str, any, any]: +def serialize_request_body( + request: Any, + request_type: type, + request_field_name: str, + nullable: bool, + optional: bool, + serialization_method: str, + encoder=None, +) -> Tuple[Optional[str], Optional[Any], Optional[Any]]: if request is None: - return None, None, None, None + if not nullable and optional: + return None, None, None if not is_dataclass(request) or not hasattr(request, request_field_name): - return serialize_content_type(request_field_name, SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method], request) + return serialize_content_type( + request_field_name, + request_type, + SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method], + request, + encoder, + ) request_val = getattr(request, request_field_name) + if request_val is None: + if not nullable and optional: + return None, None, None + request_fields: Tuple[Field, ...] = fields(request) request_metadata = None for field in request_fields: if field.name == request_field_name: - request_metadata = field.metadata.get('request') + request_metadata = field.metadata.get("request") break if request_metadata is None: - raise Exception('invalid request type') - - return serialize_content_type(request_field_name, request_metadata.get('media_type', 'application/octet-stream'), request_val) - - -def serialize_content_type(field_name: str, media_type: str, request: dataclass) -> Tuple[str, any, list[list[any]]]: - if re.match(r'(application|text)\/.*?\+*json.*', media_type) is not None: - return media_type, marshal_json(request), None - if re.match(r'multipart\/.*', media_type) is not None: + raise Exception("invalid request type") + + return serialize_content_type( + request_field_name, + request_type, + request_metadata.get("media_type", "application/octet-stream"), + request_val, + ) + + +def serialize_content_type( + field_name: str, request_type: Any, media_type: str, request: Any, encoder=None +) -> Tuple[Optional[str], Optional[Any], Optional[List[List[Any]]]]: + if re.match(r"(application|text)\/.*?\+*json.*", media_type) is not None: + return media_type, marshal_json(request, request_type, encoder), None + if re.match(r"multipart\/.*", media_type) is not None: return serialize_multipart_form(media_type, request) - if re.match(r'application\/x-www-form-urlencoded.*', media_type) is not None: + if re.match(r"application\/x-www-form-urlencoded.*", media_type) is not None: return media_type, serialize_form_data(field_name, request), None if isinstance(request, (bytes, bytearray)): return media_type, request, None @@ -404,11 +564,14 @@ def serialize_content_type(field_name: str, media_type: str, request: dataclass) return media_type, request, None raise Exception( - f"invalid request body type {type(request)} for mediaType {media_type}") + f"invalid request body type {type(request)} for mediaType {media_type}" + ) -def serialize_multipart_form(media_type: str, request: dataclass) -> Tuple[str, any, list[list[any]]]: - form: list[list[any]] = [] +def serialize_multipart_form( + media_type: str, request: Any +) -> Tuple[str, Any, List[List[Any]]]: + form: List[List[Any]] = [] request_fields = fields(request) for field in request_fields: @@ -416,7 +579,7 @@ def serialize_multipart_form(media_type: str, request: dataclass) -> Tuple[str, if val is None: continue - field_metadata = field.metadata.get('multipart_form') + field_metadata = field.metadata.get("multipart_form") if not field_metadata: continue @@ -428,42 +591,42 @@ def serialize_multipart_form(media_type: str, request: dataclass) -> Tuple[str, content = bytes() for file_field in file_fields: - file_metadata = file_field.metadata.get('multipart_form') + file_metadata = file_field.metadata.get("multipart_form") if file_metadata is None: continue if file_metadata.get("content") is True: content = getattr(val, file_field.name) else: - field_name = file_metadata.get( - "field_name", file_field.name) + field_name = file_metadata.get("field_name", file_field.name) file_name = getattr(val, file_field.name) if field_name == "" or file_name == "" or content == bytes(): - raise Exception('invalid multipart/form-data file') + raise Exception("invalid multipart/form-data file") form.append([field_name, [file_name, content]]) elif field_metadata.get("json") is True: - to_append = [field_metadata.get("field_name", field.name), [ - None, marshal_json(val), "application/json"]] + to_append = [ + field_metadata.get("field_name", field.name), + [None, marshal_json(val, field.type), "application/json"], + ] form.append(to_append) else: - field_name = field_metadata.get( - "field_name", field.name) - if isinstance(val, list): + field_name = field_metadata.get("field_name", field.name) + if isinstance(val, List): for value in val: if value is None: continue - form.append( - [field_name + "[]", [None, _val_to_string(value)]]) + form.append([field_name + "[]", [None, _val_to_string(value)]]) else: form.append([field_name, [None, _val_to_string(val)]]) return media_type, None, form -def serialize_dict(original: dict, explode: bool, field_name, existing: Optional[dict[str, list[str]]]) -> dict[ - str, list[str]]: +def serialize_dict( + original: Dict, explode: bool, field_name, existing: Optional[Dict[str, List[str]]] +) -> Dict[str, List[str]]: if existing is None: - existing = [] + existing = {} if explode is True: for key, val in original.items(): @@ -481,8 +644,8 @@ def serialize_dict(original: dict, explode: bool, field_name, existing: Optional return existing -def serialize_form_data(field_name: str, data: dataclass) -> dict[str, any]: - form: dict[str, list[str]] = {} +def serialize_form_data(field_name: str, data: Any) -> Dict[str, Any]: + form: Dict[str, List[str]] = {} if is_dataclass(data): for field in fields(data): @@ -490,32 +653,37 @@ def serialize_form_data(field_name: str, data: dataclass) -> dict[str, any]: if val is None: continue - metadata = field.metadata.get('form') + metadata = field.metadata.get("form") if metadata is None: continue - field_name = metadata.get('field_name', field.name) + field_name = metadata.get("field_name", field.name) - if metadata.get('json'): - form[field_name] = [marshal_json(val)] + if metadata.get("json"): + form[field_name] = [marshal_json(val, field.type)] else: - if metadata.get('style', 'form') == 'form': - form = form | _populate_form( - field_name, metadata.get('explode', True), val, _get_form_field_name) + if metadata.get("style", "form") == "form": + _populate_form( + field_name, + metadata.get("explode", True), + val, + _get_form_field_name, + ",", + form, + ) else: - raise Exception( - f'Invalid form style for field {field.name}') - elif isinstance(data, dict): + raise Exception(f"Invalid form style for field {field.name}") + elif isinstance(data, Dict): for key, value in data.items(): form[key] = [_val_to_string(value)] else: - raise Exception(f'Invalid request body type for field {field_name}') + raise Exception(f"Invalid request body type for field {field_name}") return form def _get_form_field_name(obj_field: Field) -> str: - obj_param_metadata = obj_field.metadata.get('form') + obj_param_metadata = obj_field.metadata.get("form") if not obj_param_metadata: return "" @@ -523,11 +691,16 @@ def _get_form_field_name(obj_field: Field) -> str: return obj_param_metadata.get("field_name", obj_field.name) -def _populate_form(field_name: str, explode: boolean, obj: any, get_field_name_func: Callable) -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - +def _populate_form( + field_name: str, + explode: boolean, + obj: Any, + get_field_name_func: Callable, + delimiter: str, + form: Dict[str, List[str]], +): if obj is None: - return params + return form if is_dataclass(obj): items = [] @@ -535,7 +708,7 @@ def _populate_form(field_name: str, explode: boolean, obj: any, get_field_name_f obj_fields: Tuple[Field, ...] = fields(obj) for obj_field in obj_fields: obj_field_name = get_field_name_func(obj_field) - if obj_field_name == '': + if obj_field_name == "": continue val = getattr(obj, obj_field.name) @@ -543,27 +716,26 @@ def _populate_form(field_name: str, explode: boolean, obj: any, get_field_name_f continue if explode: - params[obj_field_name] = [_val_to_string(val)] + form[obj_field_name] = [_val_to_string(val)] else: - items.append( - f'{obj_field_name},{_val_to_string(val)}') + items.append(f"{obj_field_name}{delimiter}{_val_to_string(val)}") if len(items) > 0: - params[field_name] = [','.join(items)] - elif isinstance(obj, dict): + form[field_name] = [delimiter.join(items)] + elif isinstance(obj, Dict): items = [] for key, value in obj.items(): if value is None: continue if explode: - params[key] = _val_to_string(value) + form[key] = [_val_to_string(value)] else: - items.append(f'{key},{_val_to_string(value)}') + items.append(f"{key}{delimiter}{_val_to_string(value)}") if len(items) > 0: - params[field_name] = [','.join(items)] - elif isinstance(obj, list): + form[field_name] = [delimiter.join(items)] + elif isinstance(obj, List): items = [] for value in obj: @@ -571,36 +743,35 @@ def _populate_form(field_name: str, explode: boolean, obj: any, get_field_name_f continue if explode: - if not field_name in params: - params[field_name] = [] - params[field_name].append(_val_to_string(value)) + if not field_name in form: + form[field_name] = [] + form[field_name].append(_val_to_string(value)) else: items.append(_val_to_string(value)) if len(items) > 0: - params[field_name] = [','.join([str(item) for item in items])] + form[field_name] = [delimiter.join([str(item) for item in items])] else: - params[field_name] = [_val_to_string(obj)] + form[field_name] = [_val_to_string(obj)] - return params + return form -def _serialize_header(explode: bool, obj: any) -> str: +def _serialize_header(explode: bool, obj: Any) -> str: if obj is None: - return '' + return "" if is_dataclass(obj): items = [] obj_fields: Tuple[Field, ...] = fields(obj) for obj_field in obj_fields: - obj_param_metadata = obj_field.metadata.get('header') + obj_param_metadata = obj_field.metadata.get("header") if not obj_param_metadata: continue - obj_field_name = obj_param_metadata.get( - 'field_name', obj_field.name) - if obj_field_name == '': + obj_field_name = obj_param_metadata.get("field_name", obj_field.name) + if obj_field_name == "": continue val = getattr(obj, obj_field.name) @@ -608,15 +779,14 @@ def _serialize_header(explode: bool, obj: any) -> str: continue if explode: - items.append( - f'{obj_field_name}={_val_to_string(val)}') + items.append(f"{obj_field_name}={_val_to_string(val)}") else: items.append(obj_field_name) items.append(_val_to_string(val)) if len(items) > 0: - return ','.join(items) - elif isinstance(obj, dict): + return ",".join(items) + elif isinstance(obj, Dict): items = [] for key, value in obj.items(): @@ -624,14 +794,14 @@ def _serialize_header(explode: bool, obj: any) -> str: continue if explode: - items.append(f'{key}={_val_to_string(value)}') + items.append(f"{key}={_val_to_string(value)}") else: items.append(key) items.append(_val_to_string(value)) if len(items) > 0: - return ','.join([str(item) for item in items]) - elif isinstance(obj, list): + return ",".join([str(item) for item in items]) + elif isinstance(obj, List): items = [] for value in obj: @@ -641,27 +811,36 @@ def _serialize_header(explode: bool, obj: any) -> str: items.append(_val_to_string(value)) if len(items) > 0: - return ','.join(items) + return ",".join(items) else: - return f'{_val_to_string(obj)}' + return f"{_val_to_string(obj)}" - return '' + return "" -def unmarshal_json(data, typ): - unmarhsal = make_dataclass('Unmarhsal', [('res', typ)], - bases=(DataClassJsonMixin,)) +def unmarshal_json(data, typ, decoder=None): + unmarshal = make_dataclass("Unmarshal", [("res", typ)], bases=(DataClassJsonMixin,)) json_dict = json.loads(data) - out = unmarhsal.from_dict({"res": json_dict}) - return out.res + try: + out = unmarshal.from_dict({"res": json_dict}) + except AttributeError as attr_err: + raise AttributeError( + f"unable to unmarshal {data} as {typ} - {attr_err}" + ) from attr_err + + return out.res if decoder is None else decoder(out.res) + +def marshal_json(val, typ, encoder=None): + if not is_optional_type(typ) and val is None: + raise ValueError(f"Could not marshal None into non-optional type: {typ}") -def marshal_json(val): - marshal = make_dataclass('Marshal', [('res', type(val))], - bases=(DataClassJsonMixin,)) + marshal = make_dataclass("Marshal", [("res", typ)], bases=(DataClassJsonMixin,)) marshaller = marshal(res=val) json_dict = marshaller.to_dict() - return json.dumps(json_dict["res"]) + val = json_dict["res"] if encoder is None else encoder(json_dict["res"]) + + return json.dumps(val, separators=(",", ":"), sort_keys=True) def match_content_type(content_type: str, pattern: str) -> boolean: @@ -669,7 +848,7 @@ def match_content_type(content_type: str, pattern: str) -> boolean: return True msg = Message() - msg['content-type'] = content_type + msg["content-type"] = content_type media_type = msg.get_content_type() if media_type == pattern: @@ -677,12 +856,22 @@ def match_content_type(content_type: str, pattern: str) -> boolean: parts = media_type.split("/") if len(parts) == 2: - if pattern in (f'{parts[0]}/*', f'*/{parts[1]}'): + if pattern in (f"{parts[0]}/*", f"*/{parts[1]}"): return True return False +def match_status_codes(status_codes: List[str], status_code: int) -> bool: + for code in status_codes: + if code == str(status_code): + return True + + if code.endswith("XX") and code.startswith(str(status_code)[:1]): + return True + return False + + def datetimeisoformat(optional: bool): def isoformatoptional(val): if optional and val is None: @@ -705,6 +894,111 @@ def datefromisoformat(date_str: str): return dateutil.parser.parse(date_str).date() +def bigintencoder(optional: bool): + def bigintencode(val: int): + if optional and val is None: + return None + return str(val) + + return bigintencode + + +def bigintdecoder(val): + if isinstance(val, float): + raise ValueError(f"{val} is a float") + return int(val) + + +def decimalencoder(optional: bool, as_str: bool): + def decimalencode(val: Decimal): + if optional and val is None: + return None + + if as_str: + return str(val) + + return float(val) + + return decimalencode + + +def decimaldecoder(val): + return Decimal(str(val)) + + +def map_encoder(optional: bool, value_encoder: Callable): + def map_encode(val: Dict): + if optional and val is None: + return None + + encoded = {} + for key, value in val.items(): + encoded[key] = value_encoder(value) + + return encoded + + return map_encode + + +def map_decoder(value_decoder: Callable): + def map_decode(val: Dict): + decoded = {} + for key, value in val.items(): + decoded[key] = value_decoder(value) + + return decoded + + return map_decode + + +def list_encoder(optional: bool, value_encoder: Callable): + def list_encode(val: List): + if optional and val is None: + return None + + encoded = [] + for value in val: + encoded.append(value_encoder(value)) + + return encoded + + return list_encode + + +def list_decoder(value_decoder: Callable): + def list_decode(val: List): + decoded = [] + for value in val: + decoded.append(value_decoder(value)) + + return decoded + + return list_decode + + +def union_encoder(all_encoders: Dict[str, Callable]): + def selective_encoder(val: Any): + if type(val) in all_encoders: + return all_encoders[type(val)](val) + return val + + return selective_encoder + + +def union_decoder(all_decoders: List[Callable]): + def selective_decoder(val: Any): + decoded = val + for decoder in all_decoders: + try: + decoded = decoder(val) + break + except (TypeError, ValueError): + continue + return decoded + + return selective_decoder + + def get_field_name(name): def override(_, _field_name=name): return _field_name @@ -712,24 +1006,55 @@ def override(_, _field_name=name): return override -def _val_to_string(val): +def _val_to_string(val) -> str: if isinstance(val, bool): return str(val).lower() if isinstance(val, datetime): - return val.isoformat().replace('+00:00', 'Z') + return str(val.isoformat().replace("+00:00", "Z")) if isinstance(val, Enum): - return val.value + return str(val.value) return str(val) -def _populate_from_globals(param_name: str, value: any, param_type: str, gbls: dict[str, dict[str, dict[str, Any]]]): - if value is None and gbls is not None: - if 'parameters' in gbls: - if param_type in gbls['parameters']: - if param_name in gbls['parameters'][param_type]: - global_value = gbls['parameters'][param_type][param_name] - if global_value is not None: - value = global_value +def _populate_from_globals( + param_name: str, value: Any, param_type: str, gbls: Any +) -> Tuple[Any, bool]: + if gbls is None: + return value, False + + global_fields = fields(gbls) + + found = False + for field in global_fields: + if field.name is not param_name: + continue + + found = True + + if value is not None: + return value, True + + global_value = getattr(gbls, field.name) + + param_metadata = field.metadata.get(param_type) + if param_metadata is None: + return value, True + + return global_value, True + + return value, found + + +def decoder_with_discriminator(field_name): + def decode_fx(obj): + kls = getattr(sys.modules["sdk.models.components"], obj[field_name]) + return unmarshal_json(json.dumps(obj), kls) + + return decode_fx + - return value +def remove_suffix(input_string, suffix): + if suffix and input_string.endswith(suffix): + return input_string[: -len(suffix)] + return input_string diff --git a/template_variables/src/epilot/variables.py b/template_variables/src/epilot/variables.py old mode 100755 new mode 100644 index 0158755dd..9481e03e3 --- a/template_variables/src/epilot/variables.py +++ b/template_variables/src/epilot/variables.py @@ -1,158 +1,260 @@ """Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" import requests as requests_http -from . import utils -from epilot.models import operations, shared -from typing import Optional +from .sdkconfiguration import SDKConfiguration +from epilot import utils +from epilot._hooks import AfterErrorContext, AfterSuccessContext, BeforeRequestContext, HookContext +from epilot.models import components, errors, operations +from typing import List, Optional class Variables: r"""Variables""" - _client: requests_http.Session - _security_client: requests_http.Session - _server_url: str - _language: str - _sdk_version: str - _gen_version: str - - def __init__(self, client: requests_http.Session, security_client: requests_http.Session, server_url: str, language: str, sdk_version: str, gen_version: str) -> None: - self._client = client - self._security_client = security_client - self._server_url = server_url - self._language = language - self._sdk_version = sdk_version - self._gen_version = gen_version - - def generate_q_rcode(self, request: operations.GenerateQRcodeRequest) -> operations.GenerateQRcodeResponse: - r"""generateQRcode - Generate QR Code for the given payload - """ - base_url = self._server_url - - url = base_url.removesuffix('/') + '/v1/template-variables/qrcode:generate' - - query_params = utils.get_query_params(operations.GenerateQRcodeRequest, request) - - client = self._security_client - - http_res = client.request('GET', url, params=query_params) - content_type = http_res.headers.get('Content-Type') + sdk_configuration: SDKConfiguration - res = operations.GenerateQRcodeResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + def __init__(self, sdk_config: SDKConfiguration) -> None: + self.sdk_configuration = sdk_config - if http_res.status_code == 200: - pass - - return res - - def get_categories(self, request: operations.GetCategoriesRequest) -> operations.GetCategoriesResponse: + + + def get_categories(self, lang: Optional[str] = None) -> operations.GetCategoriesResponse: r"""getCategories Get all template variable categories """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='getCategories', oauth2_scopes=[], security_source=self.sdk_configuration.security) + request = operations.GetCategoriesRequest( + lang=lang, + ) + + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = base_url.removesuffix('/') + '/v1/template-variables/categories' + url = base_url + '/v1/template-variables/categories' - query_params = utils.get_query_params(operations.GetCategoriesRequest, request) + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - client = self._security_client + query_params = { **utils.get_query_params(request), **query_params } + headers['Accept'] = 'application/json' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('GET', url, params=query_params) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('GET', url, params=query_params, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.GetCategoriesResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + + + + res = operations.GetCategoriesResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[list[shared.CategoryResult]]) - res.category_results = out + if utils.match_content_type(http_res.headers.get('Content-Type') or '', 'application/json'): + out = utils.unmarshal_json(http_res.text, Optional[List[components.CategoryResult]]) + res.classes = out + else: + content_type = http_res.headers.get('Content-Type') + raise errors.SDKError(f'unknown content-type received: {content_type}', http_res.status_code, http_res.text, http_res) + elif http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res - def get_variable_context(self, request: operations.GetVariableContextRequestBody) -> operations.GetVariableContextResponse: + + + def get_variable_context(self, request: Optional[operations.GetVariableContextRequestBody]) -> operations.GetVariableContextResponse: r"""getVariableContext Get full variable context - + Calls Entity API, User API, Brand API and others to construct full context object used for template variable replace - """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='getVariableContext', oauth2_scopes=[], security_source=self.sdk_configuration.security) + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = base_url.removesuffix('/') + '/v1/template-variables:context' + url = base_url + '/v1/template-variables:context' - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "request", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - client = self._security_client + req_content_type, data, form = utils.serialize_request_body(request, Optional[operations.GetVariableContextRequestBody], "request", False, True, 'json') + if req_content_type is not None and req_content_type not in ('multipart/form-data', 'multipart/mixed'): + headers['content-type'] = req_content_type + headers['Accept'] = 'application/json' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('POST', url, params=query_params, data=data, files=form, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.GetVariableContextResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + + + + res = operations.GetVariableContextResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[shared.VariableContext]) + if utils.match_content_type(http_res.headers.get('Content-Type') or '', 'application/json'): + out = utils.unmarshal_json(http_res.text, Optional[components.VariableContext]) res.variable_context = out + else: + content_type = http_res.headers.get('Content-Type') + raise errors.SDKError(f'unknown content-type received: {content_type}', http_res.status_code, http_res.text, http_res) + elif http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res - def replace_templates(self, request: operations.ReplaceTemplatesRequestBody) -> operations.ReplaceTemplatesResponse: + + + def replace_templates(self, request: Optional[operations.ReplaceTemplatesRequestBody]) -> operations.ReplaceTemplatesResponse: r"""replaceTemplates Replace variables in handlebars templates - + Takes in an array of input templates and outputs the output text with replaced variables - """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='replaceTemplates', oauth2_scopes=[], security_source=self.sdk_configuration.security) + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = base_url.removesuffix('/') + '/v1/template-variables:replace' + url = base_url + '/v1/template-variables:replace' - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "request", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - client = self._security_client + req_content_type, data, form = utils.serialize_request_body(request, Optional[operations.ReplaceTemplatesRequestBody], "request", False, True, 'json') + if req_content_type is not None and req_content_type not in ('multipart/form-data', 'multipart/mixed'): + headers['content-type'] = req_content_type + headers['Accept'] = 'application/json' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('POST', url, params=query_params, data=data, files=form, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.ReplaceTemplatesResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + + + + res = operations.ReplaceTemplatesResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[operations.ReplaceTemplates200ApplicationJSON]) - res.replace_templates_200_application_json_object = out + if utils.match_content_type(http_res.headers.get('Content-Type') or '', 'application/json'): + out = utils.unmarshal_json(http_res.text, Optional[operations.ReplaceTemplatesResponseBody]) + res.object = out + else: + content_type = http_res.headers.get('Content-Type') + raise errors.SDKError(f'unknown content-type received: {content_type}', http_res.status_code, http_res.text, http_res) + elif http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res - def search_variables(self, request: operations.SearchVariablesRequestBody) -> operations.SearchVariablesResponse: + + + def search_variables(self, request: Optional[operations.SearchVariablesRequestBody]) -> operations.SearchVariablesResponse: r"""searchVariables Search variables """ - base_url = self._server_url + hook_ctx = HookContext(operation_id='searchVariables', oauth2_scopes=[], security_source=self.sdk_configuration.security) + base_url = utils.template_url(*self.sdk_configuration.get_server_details()) - url = base_url.removesuffix('/') + '/v1/template-variables:search' + url = base_url + '/v1/template-variables:search' - headers = {} - req_content_type, data, form = utils.serialize_request_body(request, "request", 'json') - if req_content_type not in ('multipart/form-data', 'multipart/mixed'): - headers['content-type'] = req_content_type + if callable(self.sdk_configuration.security): + headers, query_params = utils.get_security(self.sdk_configuration.security()) + else: + headers, query_params = utils.get_security(self.sdk_configuration.security) - client = self._security_client + req_content_type, data, form = utils.serialize_request_body(request, Optional[operations.SearchVariablesRequestBody], "request", False, True, 'json') + if req_content_type is not None and req_content_type not in ('multipart/form-data', 'multipart/mixed'): + headers['content-type'] = req_content_type + headers['Accept'] = 'application/json' + headers['user-agent'] = self.sdk_configuration.user_agent + client = self.sdk_configuration.client - http_res = client.request('POST', url, data=data, files=form, headers=headers) - content_type = http_res.headers.get('Content-Type') + try: + req = client.prepare_request(requests_http.Request('POST', url, params=query_params, data=data, files=form, headers=headers)) + req = self.sdk_configuration.get_hooks().before_request(BeforeRequestContext(hook_ctx), req) + http_res = client.send(req) + except Exception as e: + _, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), None, e) + if e is not None: + raise e - res = operations.SearchVariablesResponse(status_code=http_res.status_code, content_type=content_type, raw_response=http_res) + if utils.match_status_codes(['4XX','5XX'], http_res.status_code): + result, e = self.sdk_configuration.get_hooks().after_error(AfterErrorContext(hook_ctx), http_res, None) + if e is not None: + raise e + if result is not None: + http_res = result + else: + http_res = self.sdk_configuration.get_hooks().after_success(AfterSuccessContext(hook_ctx), http_res) + + + + res = operations.SearchVariablesResponse(http_meta=components.HTTPMetadata(request=req, response=http_res)) if http_res.status_code == 200: - if utils.match_content_type(content_type, 'application/json'): - out = utils.unmarshal_json(http_res.text, Optional[list[shared.VariableResult]]) - res.variable_results = out + if utils.match_content_type(http_res.headers.get('Content-Type') or '', 'application/json'): + out = utils.unmarshal_json(http_res.text, Optional[List[components.VariableResult]]) + res.classes = out + else: + content_type = http_res.headers.get('Content-Type') + raise errors.SDKError(f'unknown content-type received: {content_type}', http_res.status_code, http_res.text, http_res) + elif http_res.status_code >= 400 and http_res.status_code < 500 or http_res.status_code >= 500 and http_res.status_code < 600: + raise errors.SDKError('API error occurred', http_res.status_code, http_res.text, http_res) + else: + raise errors.SDKError('unknown status code received', http_res.status_code, http_res.text, http_res) return res - \ No newline at end of file + + diff --git a/template_variables/tests/helpers.py b/template_variables/tests/helpers.py new file mode 100644 index 000000000..b3d095040 --- /dev/null +++ b/template_variables/tests/helpers.py @@ -0,0 +1,61 @@ +"""Code generated by Speakeasy (https://speakeasyapi.dev). DO NOT EDIT.""" + +import re + + +def sort_query_parameters(url): + parts = url.split("?") + + if len(parts) == 1: + return url + + query = parts[1] + params = query.split("&") + + params.sort(key=lambda x: x.split('=')[0]) + + return parts[0] + "?" + "&".join(params) + + +def sort_serialized_maps(inp: any, regex: str, delim: str): + + def sort_map(m): + entire_match = m.group(0) + + groups = m.groups() + + for group in groups: + pairs = [] + if '=' in group: + pairs = group.split(delim) + + pairs.sort(key=lambda x: x.split('=')[0]) + else: + values = group.split(delim) + + if len(values) == 1: + pairs = values + else: + pairs = [''] * int(len(values)/2) + # loop though every 2nd item + for i in range(0, len(values), 2): + pairs[int(i/2)] = values[i] + delim + values[i+1] + + pairs.sort(key=lambda x: x.split(delim)[0]) + + entire_match = entire_match.replace(group, delim.join(pairs)) + + return entire_match + + if isinstance(inp, str): + return re.sub(regex, sort_map, inp) + elif isinstance(inp, list): + for i, v in enumerate(inp): + inp[i] = sort_serialized_maps(v, regex, delim) + return inp + elif isinstance(inp, dict): + for k, v in inp.items(): + inp[k] = sort_serialized_maps(v, regex, delim) + return inp + else: + raise Exception("Unsupported type")